# typeship — SDK reference

Use the Typeship SDK to generate packages and manage Projects.
Client: `TypeshipClient`. Base URL: `https://typeship.dev/api/v1`.

```ts
import { TypeshipClient } from "typeship";

const client = new TypeshipClient({
  bearerToken: process.env.TYPESHIP_API_KEY, // ak_..., optional for generate
});
```

## projects

### projects.create

`POST /projects`

Create a Project

Creates a Project from a URL or GitHub Spec.
Automatic generation is enabled by default for a saved Project.

Free includes one saved Project, all selected Targets, and the first 25 operations per Target, with regeneration, history, delivery pull requests, and previews. Pro supports additional Projects and all operations. One-shot generation does not use a Project slot.

```ts
client.projects.create(body, params?, options?)
```

**Body**

| name | type | description |
| --- | --- | --- |
| name | `string` |  |
| spec | `SpecFields` |  |
| targets | `InitialTargetFields[]` | Initial first-class Targets. More than one may use the same generator with different identities or Deliveries. |
| auto_generate? | `boolean` | Whether Typeship should regenerate automatically when the source or saved configuration changes. |
| config? | `ProjectConfig | null` | Shared defaults inherited by every Target. GraphQL settings belong in spec.graphql. |

Returns `Promise<ApiResult<ProjectResponse, ProjectsCreateError>>`. Errors: BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, ConflictError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.projects.create({
  "name": "Parcel API",
  "spec": {
    "source": {
      "type": "url",
      "url": {
        "url": "https://api.parcel.example/openapi.json"
      }
    }
  },
  "targets": [
    {
      "name": "Parcel CLI",
      "type": "cli",
      "deliveries": [
        {
          "type": "repository",
          "repository": {
            "provider": "github",
            "identifier": "parcel-example/parcel-client",
            "module_path": "github.com/parcel-example/parcel-client",
            "publish_on_merge": false
          }
        }
      ]
    }
  ]
});
data; // ProjectResponse
```

### projects.list

`GET /projects` (paginated)

List Projects

```ts
client.projects.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |

Returns `PagePromise<Project, ProjectsListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.projects.list();
page.items;        // Project[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.projects.list()) {
  console.log(item);
}
```

### projects.get

`GET /projects/{project_id}`

Get a Project

Returns the Project's settings and Spec ID. List its Targets separately to retrieve Target configuration and Deliveries.

```ts
client.projects.get(projectId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| project_id | `ProjectId` |  |

Returns `Promise<ApiResult<ProjectResponse, ProjectsGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.projects.get("prj_4f8k2m7x9q1v6b3n");
data; // ProjectResponse
```

### projects.update

`PATCH /projects/{project_id}`

Update a Project

Omitted fields keep their current values. A supplied config replaces the entire stored object; null or an empty object clears it.
With auto_generate enabled, changing shared config queues a Generation for each Target whose effective config changes. A queued or running Target reuses that Generation.
Omitting If-Match applies the update to the current resource; with If-Match, a stale ETag returns 412 precondition_failed without saving.

A `409 target_busy` means a Target is publishing. Retrieve the Project, wait for publishing to finish, reconcile your update, and retry.
A `502 follow_up_failed` means the Project was saved, but an obsolete Draft pull request could not be retired. Retrieve the Project and retry the same update to finish retiring reviews if that update is still desired.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.projects.update(projectId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| project_id | `ProjectId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| name? | `string` |  |
| auto_generate? | `boolean` |  |
| config? | `ProjectConfig | null` | Replaces the Project's shared Target defaults. Send null to clear them. |

Returns `Promise<ApiResult<ProjectResponse, ProjectsUpdateError>>`. Errors: BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.projects.update("prj_4f8k2m7x9q1v6b3n", {
  "auto_generate": false
});
data; // ProjectResponse
```

### projects.delete

`DELETE /projects/{project_id}`

Delete a Project

A `502 repository_unavailable` means the Project was not deleted because its Draft pull requests could not be retired. Retry deletion to finish retiring the remaining reviews. Repeating a completed deletion returns `404`.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.projects.delete(projectId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| project_id | `ProjectId` |  |

Returns `Promise<ApiResult<DeletedProject, ProjectsDeleteError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, PreconditionFailedError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.projects.delete("prj_4f8k2m7x9q1v6b3n");
data; // DeletedProject
```

### projects.generate

`POST /projects/{project_id}/generate`

Generate a Project's Targets

Queues one Generation per active Target and returns their IDs. Retrieve each Generation until its status moves from `queued` to `running` and then `completed` or `failed`. `completed` means generated files are saved; check Delivery and Draft status separately for repository delivery and pull requests. A Target already queued or running is returned without starting another Generation. A `409 targets_inactive` means the Project has no active Target to generate. A matching Idempotency-Key replay returns the same Generations with their current statuses.

If the package already matches a destination and no Draft is open, delivery creates no commit, branch, or pull request. An existing Draft stays open. Automatic generation uses the same workflow.

```ts
client.projects.generate(projectId: string, body?, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| project_id | `ProjectId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| target_id? | `TargetId` | Generate only this active Target. Omit to generate all active Targets in the Project. |

Returns `Promise<ApiResult<GenerationBatch, ProjectsGenerateError>>`. Errors: BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, ConflictError, PayloadTooLargeError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.projects.generate("prj_4f8k2m7x9q1v6b3n", {
  "target_id": "tgt_5m8q2v7k1p9d4h6c"
});
data; // GenerationBatch
```

## specs

### specs.get

`GET /specs/{spec_id}`

Get a Spec

```ts
client.specs.get(specId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| spec_id | `SpecId` |  |

Returns `Promise<ApiResult<Spec, SpecsGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.specs.get("spec_2p8m4q7k1v9d6h3c");
data; // Spec
```

### specs.update

`PATCH /specs/{spec_id}`

Update a Spec

Resolves the source files before saving the update and records a new Spec Revision when the source changes.
Omitted fields remain unchanged; supplied objects and arrays replace the whole field.
If the Spec or its Project configuration changes during validation, returns 409 resource_changed without saving the rejected update. Retrieve the current Spec and Project, reconcile your changes,
and submit a new request with a new Idempotency-Key if using one.

See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.specs.update(specId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| spec_id | `SpecId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| source? | `SpecSourceInput` |  |
| patches? | `SpecPatch[]` | Replace all patches in order. An empty array removes every patch; null is invalid. |
| graphql? | `GraphqlSettings | null` | Replace all GraphQL settings. Null or an empty object clears them. |
| diagnostic_policy? | `DiagnosticPolicy` | Replace the complete policy and suppression list. Null and an empty object are invalid. |

Returns `Promise<ApiResult<Spec, SpecsUpdateError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.specs.update("spec_2p8m4q7k1v9d6h3c", {
  "source": {
    "type": "url",
    "url": {
      "url": "https://api.parcel.example/openapi.json"
    }
  }
});
data; // Spec
```

### specs.refresh

`POST /specs/{spec_id}/refresh`

Refresh a Spec

Fetches the configured source now and creates a new Spec Revision only when its content changes. Diagnostics then reads that revision. If automatic generation is enabled, refresh queues generation for active Targets even when the source is unchanged. A `502 follow_up_failed` means the new Spec Revision was recorded but generation could not be queued.

```ts
client.specs.refresh(specId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| spec_id | `SpecId` |  |

Returns `Promise<ApiResult<Spec, SpecsRefreshError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.specs.refresh("spec_2p8m4q7k1v9d6h3c");
data; // Spec
```

## specRevisions

### specRevisions.list

`GET /spec-revisions` (paginated)

List Spec Revisions

Lists Spec Revisions, newest first. Source content is not included; list a revision's files with listSpecRevisionFiles.

```ts
client.specRevisions.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| spec_id? | `SpecId` | Only revisions of this Spec. |

Returns `PagePromise<SpecRevision, SpecRevisionsListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.specRevisions.list();
page.items;        // SpecRevision[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.specRevisions.list()) {
  console.log(item);
}
```

### specRevisions.get

`GET /spec-revisions/{spec_revision_id}`

Get a Spec Revision

Returns metadata for a saved Spec Revision with a Diagnostics summary. Pass `include=diagnostics` to add every Diagnostic, evaluated with the Spec's current patches and Diagnostic policy. Add `filter=blocking` to receive only the locations that fail the policy, which is what to fix when `diagnostic_summary.status` is blocked. List its source files and resolved document with listSpecRevisionFiles.

```ts
client.specRevisions.get(specRevisionId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| spec_revision_id | `SpecRevisionId` |  |

**Params**

| name | type | description |
| --- | --- | --- |
| include? | `"diagnostics"` | Add related data to the response. `diagnostics` adds the `diagnostics` and `patch_diagnostics` arrays. |
| filter? | `"blocking" | "introduced"` | Narrow the included Diagnostics to matching locations. Requires include=diagnostics. blocking: locations that fail the Diagnostic policy. introduced: locations new since the baseline. A Diagnostic with no matching location is omitted. diagnostic_summary always describes the complete revision. |

Returns `Promise<ApiResult<SpecRevisionResponse, SpecRevisionsGetError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.specRevisions.get("srev_6m1q8v4k2p9d7h3c");
data; // SpecRevisionResponse
```

### specRevisions.listFiles

`GET /spec-revisions/{spec_revision_id}/files` (paginated)

List a Spec Revision's files

Lists the captured source files and the resolved document Typeship generated from, ordered by path. Read content with getFile.

```ts
client.specRevisions.listFiles(specRevisionId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| spec_revision_id | `SpecRevisionId` |  |

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |

Returns `PagePromise<SpecRevisionFile, SpecRevisionsListFilesError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.specRevisions.listFiles("srev_6m1q8v4k2p9d7h3c");
page.items;        // SpecRevisionFile[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.specRevisions.listFiles("srev_6m1q8v4k2p9d7h3c")) {
  console.log(item);
}
```

## targets

### targets.create

`POST /targets`

Create a Target

Creates a Target with its own configuration, Deliveries, and release history. Multiple Targets can use the same generator.

```ts
client.targets.create(body, params?, options?)
```

**Body**

| name | type | description |
| --- | --- | --- |
| project_id | `ProjectId` |  |
| name | `string` |  |
| type | `GeneratorKind` |  |
| status? | `"active" | "disabled"` |  |
| release_channel? | `"stable" | "prerelease"` |  |
| checks? | `TargetChecks` |  |
| config? | `TargetConfig | null` | Target-specific overrides merged over Project.config. GraphQL settings are rejected here and belong to the Spec. |
| deliveries? | `DeliveryInput[]` |  |

Returns `Promise<ApiResult<TargetResponse, TargetsCreateError>>`. Errors: BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.targets.create({
  "project_id": "prj_4f8k2m7x9q1v6b3n",
  "name": "Parcel CLI",
  "type": "cli",
  "config": {
    "cli": {
      "command_name": "parcel"
    }
  },
  "deliveries": [
    {
      "type": "repository",
      "repository": {
        "provider": "github",
        "identifier": "parcel-example/parcel-client",
        "module_path": "github.com/parcel-example/parcel-client",
        "publish_on_merge": false
      }
    }
  ]
});
data; // TargetResponse
```

### targets.list

`GET /targets` (paginated)

List Targets

```ts
client.targets.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| project_id? | `ProjectId` | Only Targets in this Project. |

Returns `PagePromise<Target, TargetsListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.targets.list();
page.items;        // Target[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.targets.list()) {
  console.log(item);
}
```

### targets.get

`GET /targets/{target_id}`

Get a Target

```ts
client.targets.get(targetId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| target_id | `TargetId` |  |

Returns `Promise<ApiResult<TargetResponse, TargetsGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.targets.get("tgt_5m8q2v7k1p9d4h6c");
data; // TargetResponse
```

### targets.update

`PATCH /targets/{target_id}`

Update a Target

Omitted fields keep their current values. Supplied config and checks replace their complete stored values. Change Deliveries with createDelivery, updateDelivery, and deleteDelivery.
With Project auto_generate enabled, changing Target config or checks queues that Target's Generation. A queued or running Target reuses that Generation.
Omitting If-Match applies the update to the current resource; with If-Match, a stale ETag returns 412 precondition_failed without saving.
Select the next version through PATCH /drafts/{draft_id} on the Target's draft_id.

A `409 target_busy` means the Target is publishing; wait for it to finish. A `409 delivery_conflict` means another Target owns the requested repository tree; retrieve both Targets, choose a free destination, and retry.
A `502 follow_up_failed` means the update was saved, but retiring an obsolete review or regenerating the Target failed. Retrieve the Target and follow the error's retryable and suggested_action fields.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.targets.update(targetId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| target_id | `TargetId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| name? | `string` |  |
| status? | `"active" | "disabled"` |  |
| release_channel? | `"stable" | "prerelease"` |  |
| checks? | `TargetChecks` |  |
| config? | `TargetConfig | null` | Replaces the complete stored override object. Send null or an empty object to resume Project inheritance. Effective values merge over Project.config; GraphQL settings belong to the Spec. |

Returns `Promise<ApiResult<TargetResponse, TargetsUpdateError>>`. Errors: BadRequestError, UnauthorizedError, PaymentRequiredError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.targets.update("tgt_5m8q2v7k1p9d4h6c", {
  "status": "disabled"
});
data; // TargetResponse
```

### targets.delete

`DELETE /targets/{target_id}`

Delete a Target

Deletes a Target with no Generation history, release history, or active Draft. A `409 resource_has_dependencies` means one of those resources still depends on it. Retrieve the Target, disable it instead, or resolve the dependency before retrying.

See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.targets.delete(targetId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| target_id | `TargetId` |  |

Returns `Promise<ApiResult<DeletedTarget, TargetsDeleteError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.targets.delete("tgt_5m8q2v7k1p9d4h6c");
data; // DeletedTarget
```

### targets.adopt

`POST /targets/{target_id}/adopt`

Adopt a package release

Checks the repository tag, package metadata, and registry artifact, then records the package as an Imported latest release. Opens the first Typeship Draft at the next major version; review it to establish the baseline for preserving existing code.

```ts
client.targets.adopt(targetId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| target_id | `TargetId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| version | `string` | Exact already-published package version to make the latest release. |
| tag | `string` | Immutable repository tag containing the matching package source. |

Returns `Promise<ApiResult<ReleaseResponse, TargetsAdoptError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.targets.adopt("tgt_5m8q2v7k1p9d4h6c", {
  "version": "1.0.0",
  "tag": "v1.0.0"
});
data; // ReleaseResponse
```

## deliveries

### deliveries.create

`POST /deliveries`

Create a Delivery

Adds a repository or hosted MCP Delivery to a Target. A Target has at most one Delivery of each type; a `409 delivery_exists` means it already has one, so update that Delivery instead.
With Project auto_generate enabled, adding a Delivery queues the Target's Generation. A queued or running Target reuses that Generation.

A `409 delivery_conflict` means another Target owns the requested repository directory. A `409 target_busy` means the Target is publishing; wait for it to finish.
A `502 follow_up_failed` means the Delivery was saved, but retiring an obsolete review or regenerating the Target failed. Get the Delivery and follow the error's retryable and suggested_action fields.

```ts
client.deliveries.create(body, params?, options?)
```

Returns `Promise<ApiResult<DeliveryResponse, DeliveriesCreateError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.deliveries.create({
  "target_id": "tgt_5m8q2v7k1p9d4h6c",
  "type": "repository",
  "repository": {
    "provider": "github",
    "identifier": "parcel-example/parcel-client",
    "module_path": "github.com/parcel-example/parcel-client",
    "publish_on_merge": false
  }
});
data; // DeliveryResponse
```

### deliveries.list

`GET /deliveries` (paginated)

List Deliveries

```ts
client.deliveries.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| target_id? | `TargetId` | Only Deliveries of this Target. |

Returns `PagePromise<Delivery, DeliveriesListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.deliveries.list();
page.items;        // Delivery[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.deliveries.list()) {
  console.log(item);
}
```

### deliveries.get

`GET /deliveries/{delivery_id}`

Get a Delivery

Returns the configured repository or hosted MCP Delivery for a Target. A Delivery in another organization returns 404 resource_not_found.

```ts
client.deliveries.get(deliveryId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| delivery_id | `DeliveryId` |  |

Returns `Promise<ApiResult<DeliveryResponse, DeliveriesGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.deliveries.get("dlv_4q8m2v7k1p9d5h6c");
data; // DeliveryResponse
```

### deliveries.update

`PATCH /deliveries/{delivery_id}`

Update a Delivery

Replaces a repository Delivery's settings. Omitted optional settings reset to their defaults. Hosted MCP Deliveries have no settings to update.
With Project auto_generate enabled, changing a Delivery queues the Target's Generation. A queued or running Target reuses that Generation.
Omitting If-Match applies the update to the current Delivery; with If-Match, a stale ETag returns 412 precondition_failed without saving.

A `409 delivery_conflict` means another Target owns the requested repository directory. A `409 target_busy` means the Target is publishing; wait for it to finish.
A `502 follow_up_failed` means the Delivery was saved, but retiring an obsolete review or regenerating the Target failed. Get the Delivery and follow the error's retryable and suggested_action fields.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.deliveries.update(deliveryId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| delivery_id | `DeliveryId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| repository | `RepositoryDeliverySettingsInput` | Replaces the complete repository settings, so omitted optional settings reset to their defaults. Only repository Deliveries have settings to update. |

Returns `Promise<ApiResult<DeliveryResponse, DeliveriesUpdateError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.deliveries.update("dlv_4q8m2v7k1p9d5h6c", {
  "repository": {
    "provider": "github",
    "identifier": "parcel-example/parcel-client",
    "module_path": "github.com/parcel-example/parcel-client",
    "publish_on_merge": true
  }
});
data; // DeliveryResponse
```

### deliveries.delete

`DELETE /deliveries/{delivery_id}`

Delete a Delivery

Removes a Delivery from its Target. Removing a repository Delivery retires the Target's open Draft pull request; removing a hosted MCP Delivery stops serving its URL. Recreating the type later allocates a new ID and, for hosted MCP, a new URL.

A `409 target_busy` means the Target is publishing; wait for it to finish. A `502 follow_up_failed` means the Delivery was removed, but retiring an obsolete review or regenerating the Target failed.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.deliveries.delete(deliveryId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| delivery_id | `DeliveryId` |  |

Returns `Promise<ApiResult<DeletedDelivery, DeliveriesDeleteError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.deliveries.delete("dlv_4q8m2v7k1p9d5h6c");
data; // DeletedDelivery
```

## generations

### generations.get

`GET /generations/{generation_id}`

Get a Generation

Returns the status of that Generation. `queued` and `running` mean generation is still in progress. `completed` means generated files are saved, not that repository delivery or a Draft is complete. List its files with listGenerationFiles and read each with getFile.

```ts
client.generations.get(generationId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| generation_id | `GenerationId` |  |

Returns `Promise<ApiResult<GenerationResponse, GenerationsGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.generations.get("gen_7h2p5d9c3m8w1k6q");
data; // GenerationResponse
```

### generations.list

`GET /generations` (paginated)

List Generations

```ts
client.generations.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| project_id? | `ProjectId` | Only Generations in this Project. |
| target_id? | `TargetId` | Only Generations of this Target. |
| status? | `GenerationStatus` | Only Generations with this status. |

Returns `PagePromise<Generation, GenerationsListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.generations.list();
page.items;        // Generation[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.generations.list()) {
  console.log(item);
}
```

### generations.listFiles

`GET /generations/{generation_id}/files` (paginated)

List a Generation's files

Lists the generated package's files, ordered by path. Read content with getFile.

```ts
client.generations.listFiles(generationId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| generation_id | `GenerationId` |  |

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |

Returns `PagePromise<FileModel, GenerationsListFilesError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.generations.listFiles("gen_7h2p5d9c3m8w1k6q");
page.items;        // FileModel[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.generations.listFiles("gen_7h2p5d9c3m8w1k6q")) {
  console.log(item);
}
```

## drafts

### drafts.list

`GET /drafts` (paginated)

List Drafts

Lists open and merged Drafts, newest first. Each Target has one open Draft; each merge adds a merged Draft.

```ts
client.drafts.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| target_id? | `TargetId` | Only Drafts of this Target. |
| status? | `DraftStatus` | Only Drafts with this status. |

Returns `PagePromise<Draft, DraftsListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.drafts.list();
page.items;        // Draft[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.drafts.list()) {
  console.log(item);
}
```

### drafts.get

`GET /drafts/{draft_id}`

Get a Draft

Returns the Draft's status. An open Draft also reports its typed reason when action is required, next version and its source, compatibility and version assessment, blocking errors, checks, and conflict counts. The response carries an `ETag`; send it in `If-Match` when updating the Draft to avoid changing a newer version selection.

```ts
client.drafts.get(draftId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| draft_id | `DraftId` |  |

Returns `Promise<ApiResult<DraftResponse, DraftsGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.drafts.get("drf_3q7m1v8k2p5d9h4c");
data; // DraftResponse
```

### drafts.update

`PATCH /drafts/{draft_id}`

Update a Draft

Checks your version choice against the required version bump, then regenerates the existing Draft pull request.

Send the Draft's `ETag` in `If-Match` to reject an intervening change with 412 precondition_failed before saving or regenerating. Omitting `If-Match` applies the selection to the current Draft. version_next is required; null restores automatic selection.

A `502` response means the selected version was saved, but regeneration failed. Follow the error's retryable and suggested_action fields. Repeating an unfinished selection resumes generation; repeating a completed selection starts no new work. If using If-Match, retrieve the Draft and confirm the saved selection before retrying with its current ETag.
A `409 draft_merged` means the Draft merged; retrieve the Target and select a version on its `draft_id`. A `409 target_busy` means the Target is publishing; wait and retry. A `409 version_occupied` means the version is already released; retrieve the Draft and releases, choose a new version, and retry.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.drafts.update(draftId: string, body, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| draft_id | `DraftId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| version_next | `string | null` | Exact SemVer, or null to return to automatic selection. |

Returns `Promise<ApiResult<DraftResponse, DraftsUpdateError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, PreconditionFailedError, UnprocessableEntityError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.drafts.update("drf_3q7m1v8k2p5d9h4c", {
  "version_next": "1.1.0"
});
data; // DraftResponse
```

### drafts.listFiles

`GET /drafts/{draft_id}/files` (paginated)

List a Draft's files

Lists the Draft's files that differ from the last merged package or need a conflict decision, ordered by path, without file content. Each conflict names its kind, the saved decision, and the sides you can read with getFile. With `filter=history`, lists files affected by a default-branch history rewrite; the list is empty when none is pending.

Returns `409 resource_changed` while Typeship is carrying the Draft's latest commit forward (status working), or when the Draft changes between pages.

```ts
client.drafts.listFiles(draftId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| draft_id | `DraftId` |  |

**Params**

| name | type | description |
| --- | --- | --- |
| filter? | `"conflicted" | "customized" | "history"` | conflicted: conflicts only. customized: files that differ from the last merged package. history: files affected by a default-branch history rewrite. Omit for conflicted and customized files. |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |

Returns `PagePromise<DraftFile, DraftsListFilesError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.drafts.listFiles("drf_3q7m1v8k2p5d9h4c");
page.items;        // DraftFile[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.drafts.listFiles("drf_3q7m1v8k2p5d9h4c")) {
  console.log(item);
}
```

### drafts.resolve

`POST /drafts/{draft_id}/resolve`

Resolve Draft conflicts

Resolves conflicts on the Draft's head_sha: keep yours or generated, or supply final content as text or, for binary files, base64. Choosing generated for a customized path replaces it with the generated file, or deletes a Draft-only file.

Conflict decisions are saved together and can be replaced until applied. Choosing generated for customized paths commits those changes together on the Draft branch. Returns the Draft. When every conflict has a decision, `conflicts.decided` equals `conflicts.total` and Typeship continues the Draft and runs checks. Paths that already match the Draft change nothing.

```ts
client.drafts.resolve(draftId: string, body, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| draft_id | `DraftId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| expected_head_sha | `string` | The Draft's head_sha. A newer Draft commit returns 409 resource_changed without saving. |
| resolutions | `DraftConflictDecision[]` | Unique current conflict or customized paths. Choose generated to discard a customization, including a Draft-only file. Final file content must total at most 2 MiB. Decisions apply together or not at all. |

Returns `Promise<ApiResult<DraftResponse, DraftsResolveError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.drafts.resolve("drf_3q7m1v8k2p5d9h4c", {
  "expected_head_sha": "0123456789abcdef0123456789abcdef01234567",
  "resolutions": [
    {
      "path": "src/index.ts",
      "keep": "content",
      "mode": "100644",
      "content": "export { ParcelClient } from \"./client.js\";\nexport type { Shipment, Label } from \"./types.js\";\nexport { createParcelClient } from \"./helper.js\";\n"
    }
  ]
});
data; // DraftResponse
```

### drafts.recover

`POST /drafts/{draft_id}/recover`

Recover a Draft's history

When the Draft has status `action_required` and reason `history_rewritten`, review affected files with `listDraftFiles` and `filter=history`, then approve with the Draft's `history_recovery` revisions. Approval saves the recovery without changing Git and returns the Draft; the next generation rebuilds it from the rewritten default branch. The previous Draft branch stays available, and overlapping code comes back as conflicts to resolve. A rewritten Draft branch alone needs no approval.

```ts
client.drafts.recover(draftId: string, body, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| draft_id | `DraftId` |  |

**Body**

| name | type | description |
| --- | --- | --- |
| expected_default_sha | `string` | The Draft's history_recovery.default_sha. |
| expected_head_sha | `string | null` | The Draft's history_recovery.head_sha; null when the Draft branch is absent. |

Returns `Promise<ApiResult<DraftResponse, DraftsRecoverError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.drafts.recover("drf_3q7m1v8k2p5d9h4c", {
  "expected_default_sha": "89abcdef0123456789abcdef0123456789abcdef",
  "expected_head_sha": "0123456789abcdef0123456789abcdef01234567"
});
data; // DraftResponse
```

## releases

### releases.list

`GET /releases` (paginated)

List Releases

```ts
client.releases.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| target_id? | `TargetId` | Only releases of this Target. |

Returns `PagePromise<Release, ReleasesListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.releases.list();
page.items;        // Release[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.releases.list()) {
  console.log(item);
}
```

### releases.get

`GET /releases/{release_id}`

Get a Release

```ts
client.releases.get(releaseId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| release_id | `ReleaseId` |  |

Returns `Promise<ApiResult<ReleaseResponse, ReleasesGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.releases.get("rel_7m2q8v4k1p9d5h6c");
data; // ReleaseResponse
```

### releases.retry

`POST /releases/{release_id}/retry`

Retry publishing a Release

Queues every failed or queued Publication of the release and starts its repository publishing workflow again. Publishing uses that release's version and accepted commit, even if a newer Draft or release exists. Completed Publications are not repeated.

Returns `202` with the Release. Get the Release until each Publication reaches `completed` or `failed`.

A `409 publication_not_retryable` means no Publication is queued or failed. A `502 repository_unavailable` means the repository publishing workflow could not be dispatched, and nothing was changed.

```ts
client.releases.retry(releaseId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| release_id | `ReleaseId` |  |

Returns `Promise<ApiResult<ReleaseResponse, ReleasesRetryError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.releases.retry("rel_7m2q8v4k1p9d5h6c");
data; // ReleaseResponse
```

## files

### files.get

`GET /files/{file_id}`

Get a File

Returns one bounded chunk of an immutable file: at most 24 KiB, as UTF-8 text or, for binary bytes, base64. When next_cursor is not null, repeat the request with cursor and concatenate the chunks in order. A file ID always returns the same bytes.

```ts
client.files.get(fileId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| file_id | `FileId` |  |

**Params**

| name | type | description |
| --- | --- | --- |
| cursor? | `string` | next_cursor from the preceding chunk of this file. |

Returns `Promise<ApiResult<FileResponse, FilesGetError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.files.get("file_4k8m2v7q1p9d5h6c");
data; // FileResponse
```

## packages

### packages.generate

`POST /generate`

Generate a package

Returns one generated package without creating a Project.

Supports [idempotent retries](https://typeship.dev/docs/typeship-api/idempotency); keyed responses include generated files in the replay cache.

Use `download.url` to save the complete ZIP, verify `download.sha256`, and extract it into an empty directory. The link expires at `download.expires_at` and grants access to anyone who has it. CLI, MCP, and SDK calls supply an idempotency key automatically. Agents should request `fields=["download","coverage","warnings","claim"]` to keep the MCP result compact; files can exceed the response limit. Download the ZIP instead of repeating generation to retrieve omitted files.

Anonymous and Free requests include the first 25 operations. Paid plans include all operations. Anonymous requests are rate limited by IP address. Check `coverage` for omitted operations; an invalid API key returns `401`.

An anonymous URL request without source headers may return `claim.url`. Sign in through that link within seven days to save the recipe as a Project.

```ts
client.packages.generate(body, params?, options?)
```

**Body**

| name | type | description |
| --- | --- | --- |
| spec | `SpecInput` |  |
| target | `{   type: GeneratorKind; }` | One-shot generator descriptor; no persisted Target is created. |
| package_name? | `string` | npm package or Python distribution override. Valid only for the TypeScript and Python SDK targets. |
| module_path? | `string` | Go module path override for the generated artifact's own module. Valid only for the Go SDK and CLI Targets. Projects derive this from the Go destination repository by default. |
| config? | `Config` |  |

Returns `Promise<ApiResult<GenerationResult, PackagesGenerateError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, ConflictError, PayloadTooLargeError, UnprocessableEntityError, RateLimitError, ServerError, ApiResponseError, UnexpectedApiError, TransportError.

```ts
const data = await client.packages.generate({
  "spec": {
    "url": "https://typeship.dev/examples/petstore/openapi.yaml"
  },
  "target": {
    "type": "cli"
  }
});
data; // GenerationResult
```

### packages.download

`GET /generate/download`

Download a generated package

Download the complete ZIP referenced by `packages_generate`'s `download.url`. Pass the token from that URL. No API key is needed; the token grants access only to that exact package until its replay window expires. Keep the token private.

The local MCP server saves this binary response to disk. On a hosted MCP connection, download the original URL directly to your workspace. Verify the ZIP against `download.sha256` before extracting it into an empty directory. Expired or invalid tokens return `404`; a new generation creates a new download.

```ts
client.packages.download(params, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| token | `string` | Private download token from download.url in the generation result. |

Returns `Promise<ApiResult<Blob, PackagesDownloadError>>`. Errors: BadRequestError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.packages.download({
  "token": "parcel_download_example_token_1234567890123"
});
data; // Blob
```

## organization

### organization.get

`GET /organization`

Get the Organization

Returns the organization associated with your credential. The Typeship CLI uses this endpoint for `whoami`.

```ts
client.organization.get(options?)
```

Returns `Promise<ApiResult<Organization, OrganizationGetError>>`. Errors: UnauthorizedError, ForbiddenError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.organization.get();
data; // Organization
```

## apiKeys

### apiKeys.list

`GET /api-keys` (paginated)

List API keys

Lists key metadata and the last four characters of each key. Full keys are not returned. Create keys in the Console.

```ts
client.apiKeys.list(params?, options?)
```

**Params**

| name | type | description |
| --- | --- | --- |
| limit? | `number` | Maximum number of resources to return. Omit for 20; otherwise supply base-10 digits representing an integer from 1 to 100. Empty, malformed, or out-of-range values return 400 input_invalid. List query parameters must appear only once; repeated or unrecognized parameters return 400 query_param_invalid. |
| cursor? | `string` | Opaque cursor from the preceding page's next_cursor. Valid only for the same organization, operation, filters, and ordering that issued it. Omit to start at the first page. Empty or malformed cursors, and cursors issued for different filters, return 400 cursor_invalid; start again from the first page. Repeated cursors return 400 query_param_invalid. The page limit may change between requests. |
| status? | `"active" | "revoked"` | Only keys with this status. |

Returns `PagePromise<ApiKey, ApiKeysListError>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
// one page:
const page = await client.apiKeys.list();
page.items;        // ApiKey[]
page.hasNextPage();

// or every item across every page:
for await (const item of client.apiKeys.list()) {
  console.log(item);
}
```

### apiKeys.get

`GET /api-keys/{api_key_id}`

Get an API key

Returns the key summary and its ETag for conditional revocation.

```ts
client.apiKeys.get(apiKeyId: string, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| api_key_id | `string` |  |

Returns `Promise<ApiResult<ApiKeyResponse, ApiKeysGetError>>`. Errors: UnauthorizedError, ForbiddenError, NotFoundError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.apiKeys.get("apikey_2nY8mR6pQ4vK9cH3");
data; // ApiKeyResponse
```

### apiKeys.revoke

`POST /api-keys/{api_key_id}/revoke`

Revoke an API key

Revokes a key immediately. The key stays listed with `status: revoked`. Repeating the request returns the same result.

With OAuth, members can revoke their own keys; organization admins can revoke any key. Organization API keys can revoke any key in their organization.
See [conditional writes](https://typeship.dev/docs/typeship-api#conditional-writes) for ETag and If-Match.

```ts
client.apiKeys.revoke(apiKeyId: string, params?, options?)
```

**Path arguments**

| name | type | description |
| --- | --- | --- |
| api_key_id | `string` |  |

Returns `Promise<ApiResult<ApiKeyResponse, ApiKeysRevokeError>>`. Errors: BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, PreconditionFailedError, RateLimitError, ServerError, UnexpectedApiError, TransportError.

```ts
const data = await client.apiKeys.revoke("apikey_2nY8mR6pQ4vK9cH3");
data; // ApiKeyResponse
```

## Types

```ts
// Typeship — API types.
// Generated by Typeship — https://typeship.dev

declare const unknownVariantTag: unique symbol;
/**
 * A tag value the server added after this SDK was generated. It is a string
 * at runtime; read it with `String(tag)`.
 */
export interface UnknownVariantTag extends String {
  readonly [unknownVariantTag]: true;
}
/** A union member the server added after this SDK was generated, with every field as received. */
export type UnknownVariant<Tag extends string> = { [K in Tag]: UnknownVariantTag } & Record<string, unknown>;

/** Unique identifier for a project. */
export type ProjectId = string;

/** Unique identifier for a generation. */
export type GenerationId = string;

/** Unique identifier for a project's logical API Spec. */
export type SpecId = string;

/** Unique identifier for an immutable resolved Spec Revision. */
export type SpecRevisionId = string;

/** Server-generated identifier used to correlate this response with Typeship logs. */
export type RequestId = string;

/** Request-level metadata present at the top level of every JSON response. */
export interface ResponseMetadata {
  request_id: RequestId;
}

/** Identifies a cursor-paginated collection. */
export type ListObject = "list";

/** Stable identifier for one configured generated product. */
export type TargetId = string;

export type DeliveryId = string;

/** Unique identifier for a Draft. */
export type DraftId = string;

export type ReleaseId = string;

/**
 * Package type selected by a Target. Several Targets may use the same type. The CLI is a
 * self-contained command-line package and requires no SDK Target.
 */
export const GeneratorKind = {
  CLI: "cli",
  MCP: "mcp",
  TYPESCRIPT_SDK: "typescript_sdk",
  PYTHON_SDK: "python_sdk",
  GO_SDK: "go_sdk",
} as const;
export type GeneratorKind = (typeof GeneratorKind)[keyof typeof GeneratorKind];

export interface UrlSpecInput {
  /**
   * URL of an OpenAPI document, a GraphQL SDL file, or a GraphQL
   * endpoint (introspected automatically). Fetched server-side.
   * Format: uri
   */
  url: string;
  /**
   * Request headers for a protected URL. Sent on the document GET and GraphQL introspection POST,
   * never returned or retained by one-shot generation.
   */
  headers?: Record<string, string>;
}

/** Response shape for UrlSpecInput. */
export interface UrlSpecInputRead {
  /**
   * URL of an OpenAPI document, a GraphQL SDL file, or a GraphQL
   * endpoint (introspected automatically). Fetched server-side.
   * Format: uri
   */
  url: string;
}

export interface InlineSpecInput {
  /**
   * Raw Spec text (OpenAPI JSON/YAML or GraphQL SDL). Up to 4 MB, because the request body carries
   * it; send Specs up to 10 MB with `url`.
   */
  inline: string;
}

/** A Spec for one-shot generation, provided as exactly one URL or inline entrypoint. */
export type SpecInput = UrlSpecInput | InlineSpecInput;

/** Response shape for SpecInput. */
export type SpecInputRead = UrlSpecInputRead | InlineSpecInput;

export interface GenerateRequest {
  spec: SpecInput;
  /** One-shot generator descriptor; no persisted Target is created. */
  target: {
    type: GeneratorKind;
  };
  /**
   * npm package or Python distribution override. Valid only for the TypeScript and Python SDK
   * targets.
   */
  package_name?: string;
  /**
   * Go module path override for the generated artifact's own module. Valid only for the Go SDK and
   * CLI Targets. Projects derive this from the Go destination repository by default.
   */
  module_path?: string;
  config?: Config;
}

/** Response shape for GenerateRequest. */
export interface GenerateRequestRead {
  spec: SpecInputRead;
  /** One-shot generator descriptor; no persisted Target is created. */
  target: {
    type: GeneratorKind | (string & {});
  };
  /**
   * npm package or Python distribution override. Valid only for the TypeScript and Python SDK
   * targets.
   */
  package_name?: string;
  /**
   * Go module path override for the generated artifact's own module. Valid only for the Go SDK and
   * CLI Targets. Projects derive this from the Go destination repository by default.
   */
  module_path?: string;
  config?: ConfigRead;
}

export interface GeneratedFile {
  /** Repo-relative path inside the generated package. */
  path: string;
  content: string;
  /**
   * Exact Git file mode. Omitted one-shot outputs are regular files.
   * Default: "100644"
   */
  mode?: "100644" | "100755";
}

/** Response shape for GeneratedFile. */
export interface GeneratedFileRead {
  /** Repo-relative path inside the generated package. */
  path: string;
  content: string;
  /**
   * Exact Git file mode. Omitted one-shot outputs are regular files.
   * Default: "100644"
   */
  mode?: ("100644" | "100755") | (string & {});
}

export interface GenerationWarning {
  /** Stable machine-readable warning code. */
  code: string;
  /** Human-readable explanation. */
  message: string;
  /** METHOD/path of the affected operation, when applicable. */
  operation?: string;
}

export interface GenerationCoverage {
  generated: number;
  omitted: number;
  total: number;
  /** METHOD/path identities of operations omitted from the package. */
  omitted_operations: string[];
  /** Present when a plan or anonymous limit omitted operations. */
  reason?: "anonymous" | "free_plan";
  /**
   * Sign-up link for anonymous capped runs.
   * Format: uri
   */
  signup_url?: string;
  /**
   * Upgrade link for capped signed-in runs.
   * Format: uri
   */
  upgrade_url?: string;
}

/** Response shape for GenerationCoverage. */
export interface GenerationCoverageRead {
  generated: number;
  omitted: number;
  total: number;
  /** METHOD/path identities of operations omitted from the package. */
  omitted_operations: string[];
  /** Present when a plan or anonymous limit omitted operations. */
  reason?: ("anonymous" | "free_plan") | (string & {});
  /**
   * Sign-up link for anonymous capped runs.
   * Format: uri
   */
  signup_url?: string;
  /**
   * Upgrade link for capped signed-in runs.
   * Format: uri
   */
  upgrade_url?: string;
}

/**
 * Unique identifier for one immutable file snapshot. An ID always returns the same bytes: a Spec
 * Revision, a Generation, and each Draft side name their own file IDs, and a new Draft commit gets
 * new IDs.
 */
export type FileId = string;

export interface FileModel {
  id: FileId;
  object: "file";
  /** Path within the Spec Revision, Generation package, or Target package. */
  path: string;
  size_bytes: number;
  /** Digest of the complete file. */
  sha256: string;
  /** utf8: content is text. base64: content is base64-encoded binary bytes. */
  encoding: "utf8" | "base64";
  /** Git file mode for package files; null for Spec source files. */
  mode: GitFileMode | null;
  /**
   * When Typeship first issued this file ID.
   * Format: date-time
   */
  created_at: string;
}

/** Response shape for FileModel. */
export interface FileModelRead {
  id: FileId;
  object: "file" | (string & {});
  /** Path within the Spec Revision, Generation package, or Target package. */
  path: string;
  size_bytes: number;
  /** Digest of the complete file. */
  sha256: string;
  /** utf8: content is text. base64: content is base64-encoded binary bytes. */
  encoding: ("utf8" | "base64") | (string & {});
  /** Git file mode for package files; null for Spec source files. */
  mode: GitFileMode | (string & {}) | null;
  /**
   * When Typeship first issued this file ID.
   * Format: date-time
   */
  created_at: string;
}

export type FileResponse = FileModel & {
  /**
   * At most 24 KiB of the file starting at offset, encoded as encoding says. Text chunks never
   * split a character; concatenate chunks in order.
   */
  content: string;
  /** Byte offset of this chunk in the file. */
  offset: number;
  /** Pass as cursor to read the next chunk; null at the end of the file. */
  next_cursor: string | null;
} & ResponseMetadata;

/** Response shape for FileResponse. */
export type FileResponseRead = FileModelRead & {
  /**
   * At most 24 KiB of the file starting at offset, encoded as encoding says. Text chunks never
   * split a character; concatenate chunks in order.
   */
  content: string;
  /** Byte offset of this chunk in the file. */
  offset: number;
  /** Pass as cursor to read the next chunk; null at the end of the file. */
  next_cursor: string | null;
} & ResponseMetadata;

export interface FileList {
  object: ListObject;
  data: FileModel[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for FileList. */
export interface FileListRead {
  object: ListObject;
  data: FileModelRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export type SpecRevisionFile = FileModel & {
  /**
   * entrypoint and reference: captured source files. resolved: the single normalized document
   * Typeship generated from.
   */
  role: "entrypoint" | "reference" | "resolved";
};

/** Response shape for SpecRevisionFile. */
export type SpecRevisionFileRead = FileModelRead & {
  /**
   * entrypoint and reference: captured source files. resolved: the single normalized document
   * Typeship generated from.
   */
  role: ("entrypoint" | "reference" | "resolved") | (string & {});
};

export interface SpecRevisionFileList {
  object: ListObject;
  data: SpecRevisionFile[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for SpecRevisionFileList. */
export interface SpecRevisionFileListRead {
  object: ListObject;
  data: SpecRevisionFileRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export interface GenerationResult {
  /** One generated package. It has no ID: download it with download.url before download.expires_at. */
  object: "package";
  files: GeneratedFile[];
  download?: GenerationDownload;
  warnings: GenerationWarning[];
  coverage: GenerationCoverage;
  /**
   * Anonymous, URL-sourced generations only. A link a signed-in person can open to turn this run
   * into a project in their organization (same Spec, Target, and config). Lasts seven days. Null
   * for inline Specs; absent on keyed calls.
   */
  claim?: null
    | {
        url: string;
        /** Format: date-time */
        expires_at: string;
      };
  request_id: RequestId;
}

/** Response shape for GenerationResult. */
export interface GenerationResultRead {
  /** One generated package. It has no ID: download it with download.url before download.expires_at. */
  object: "package" | (string & {});
  files: GeneratedFileRead[];
  download?: GenerationDownload;
  warnings: GenerationWarning[];
  coverage: GenerationCoverageRead;
  /**
   * Anonymous, URL-sourced generations only. A link a signed-in person can open to turn this run
   * into a project in their organization (same Spec, Target, and config). Lasts seven days. Null
   * for inline Specs; absent on keyed calls.
   */
  claim?: null
    | {
        url: string;
        /** Format: date-time */
        expires_at: string;
      };
  request_id: RequestId;
}

/**
 * Complete package ZIP from this exact result. Present on requests with Idempotency-Key, including
 * automatic CLI, MCP, and SDK keys. Download before expires_at, verify sha256, and extract into an
 * empty directory. Anyone with this URL can download the package; keep it private. Reading does not
 * generate again or extend the 24-hour replay window.
 */
export interface GenerationDownload {
  /** Format: uri */
  url: string;
  /** Format: date-time */
  expires_at: string;
  /** SHA-256 of the downloaded ZIP bytes. */
  sha256: string;
  size_bytes: number;
  file_count: number;
}

export interface UrlSpecSourceSettings {
  /**
   * URL fetched for every generation.
   * Format: uri
   */
  url: string;
  /** Whether Typeship has stored write-only request headers for this URL. */
  headers_configured: boolean;
}

/** Request shape for UrlSpecSourceSettings. */
export interface UrlSpecSourceSettingsWrite {
  /**
   * URL fetched for every generation.
   * Format: uri
   */
  url: string;
}

export interface UrlSpecSource {
  type: "url";
  url: UrlSpecSourceSettings;
}

/** Request shape for UrlSpecSource. */
export interface UrlSpecSourceWrite {
  type: "url";
  url: UrlSpecSourceSettingsWrite;
}

/** GitHub is the only launch provider; the field is stable for future adapters. */
export const RepositoryProvider = {
  GITHUB: "github",
} as const;
export type RepositoryProvider = (typeof RepositoryProvider)[keyof typeof RepositoryProvider];

/** Provider-native repository identity, opaque outside its adapter. */
export type RepositoryIdentifier = string;

export interface RepositorySpecSourceSettings {
  provider: RepositoryProvider;
  identifier: RepositoryIdentifier;
  /** Repository-relative Spec entrypoint. */
  path: string;
}

/** Response shape for RepositorySpecSourceSettings. */
export interface RepositorySpecSourceSettingsRead {
  provider: RepositoryProvider | (string & {});
  identifier: RepositoryIdentifier;
  /** Repository-relative Spec entrypoint. */
  path: string;
}

export interface RepositorySpecSource {
  type: "repository";
  repository: RepositorySpecSourceSettings;
}

/** Response shape for RepositorySpecSource. */
export interface RepositorySpecSourceRead {
  type: "repository";
  repository: RepositorySpecSourceSettingsRead;
}

/** The single source of truth for where a Project's Spec lives. */
export type SpecSource = UrlSpecSource | RepositorySpecSource;

/** Request shape for SpecSource. */
export type SpecSourceWrite = UrlSpecSourceWrite | RepositorySpecSource;

/** Response shape for SpecSource. */
export type SpecSourceRead = UrlSpecSource | RepositorySpecSourceRead | UnknownVariant<"type">;

export interface UrlSpecSourceSettingsInput {
  /**
   * URL of an OpenAPI document, GraphQL SDL file, or GraphQL endpoint.
   * Format: uri
   */
  url: string;
  /**
   * Request headers for a protected URL. Values are never returned or recorded in revision history.
   * When updating the same URL, omit headers to preserve the stored values or pass null to remove
   * them. Changing the URL without headers clears the old values so a credential is never forwarded
   * to a different source.
   */
  headers?: Record<string, string> | null;
}

/** Response shape for UrlSpecSourceSettingsInput. */
export interface UrlSpecSourceSettingsInputRead {
  /**
   * URL of an OpenAPI document, GraphQL SDL file, or GraphQL endpoint.
   * Format: uri
   */
  url: string;
}

export interface UrlSpecSourceInput {
  type: "url";
  url: UrlSpecSourceSettingsInput;
}

/** Response shape for UrlSpecSourceInput. */
export interface UrlSpecSourceInputRead {
  type: "url";
  url: UrlSpecSourceSettingsInputRead;
}

export interface RepositorySpecSourceSettingsInput {
  provider: RepositoryProvider;
  identifier: RepositoryIdentifier;
  /** Repository-relative Spec entrypoint. */
  path: string;
}

/** Response shape for RepositorySpecSourceSettingsInput. */
export interface RepositorySpecSourceSettingsInputRead {
  provider: RepositoryProvider | (string & {});
  identifier: RepositoryIdentifier;
  /** Repository-relative Spec entrypoint. */
  path: string;
}

export interface RepositorySpecSourceInput {
  type: "repository";
  repository: RepositorySpecSourceSettingsInput;
}

/** Response shape for RepositorySpecSourceInput. */
export interface RepositorySpecSourceInputRead {
  type: "repository";
  repository: RepositorySpecSourceSettingsInputRead;
}

export type SpecSourceInput = UrlSpecSourceInput | RepositorySpecSourceInput;

/** Response shape for SpecSourceInput. */
export type SpecSourceInputRead = UrlSpecSourceInputRead
  | RepositorySpecSourceInputRead
  | UnknownVariant<"type">;

/**
 * A fix applied to the resolved Spec before generation. Paths are JSON
 * Pointers into the document. A patch whose target no longer exists is
 * skipped and reported as a warning on the generation, never silently.
 */
export interface SpecPatch {
  op: "set" | "append" | "remove" | "rename";
  /**
   * JSON-Pointer-style path. Pattern segments enable bulk fixes:
   * * (any child), ** (any depth), [key=value] (filter), e.g.
   * /paths/**\/parameters/[name=account_id]/schema/type. Renaming a
   * schema under /components/schemas also rewrites its $refs.
   */
  path: string;
  /** set only; the replacement value. */
  value?: unknown;
  /** rename only; the new key name. */
  to?: string | null;
  reason?: string | null;
}

/** Response shape for SpecPatch. */
export interface SpecPatchRead {
  op: ("set" | "append" | "remove" | "rename") | (string & {});
  /**
   * JSON-Pointer-style path. Pattern segments enable bulk fixes:
   * * (any child), ** (any depth), [key=value] (filter), e.g.
   * /paths/**\/parameters/[name=account_id]/schema/type. Renaming a
   * schema under /components/schemas also rewrites its $refs.
   */
  path: string;
  /** set only; the replacement value. */
  value?: unknown;
  /** rename only; the new key name. */
  to?: string | null;
  reason?: string | null;
}

/**
 * One exact place where a Diagnostic rule found evidence, with its own state under the Spec's
 * Diagnostic policy.
 */
export interface DiagnosticLocation {
  /**
   * Whether this location fails the Spec's Diagnostic policy. Fix these locations to pass the
   * policy.
   */
  blocking: boolean;
  /**
   * Whether this location is new since baseline_spec_revision_id in the Diagnostic summary. Always
   * true when there is no baseline.
   */
  introduced: boolean;
  /**
   * Whether a reviewed exception in the Spec's Diagnostic policy covers this location, by its path
   * or for the whole rule. Suppressed locations never block.
   */
  suppressed: boolean;
  /** Source file path from the Spec Revision when the finding maps to a captured file. */
  file_path?: string;
  /** The captured source file, present with file_path. Read it with getFile. */
  file_id?: FileId;
  /** JSON Pointer for OpenAPI, or schema coordinate for GraphQL. */
  path: string;
  /** Human-readable operation coordinate when the location belongs to an operation. */
  operation?: string;
  /** Occurrence-specific evidence. This is not a remediation instruction. */
  evidence?: string;
}

/** A reviewable remediation that does not invent API behavior. */
export interface DiagnosticFix {
  /** Concise action for the API author. */
  title: string;
  /**
   * spec_patch is an exact OpenAPI edit Typeship can derive; source_edit requires author intent or
   * a lossless GraphQL source edit.
   */
  type: "spec_patch" | "source_edit";
  /** Exact patches when type is spec_patch. */
  patches?: SpecPatchResponse[];
  /** Source-level guidance when an exact patch would invent intent. */
  instructions?: string;
}

/** Response shape for DiagnosticFix. */
export interface DiagnosticFixRead {
  /** Concise action for the API author. */
  title: string;
  /**
   * spec_patch is an exact OpenAPI edit Typeship can derive; source_edit requires author intent or
   * a lossless GraphQL source edit.
   */
  type: ("spec_patch" | "source_edit") | (string & {});
  /** Exact patches when type is spec_patch. */
  patches?: SpecPatchResponseRead[];
  /** Source-level guidance when an exact patch would invent intent. */
  instructions?: string;
}

/**
 * Every occurrence of one Diagnostic rule in a Spec Revision, grouped into one decision.
 * Diagnostics are evaluated when read, using the Spec's current patches and Diagnostic policy.
 */
export interface Diagnostic {
  /** Stable rule identifier, unique within a Spec Revision. Suppressions name it as rule_id. */
  id: string;
  object: "diagnostic";
  /**
   * Whether any location fails the Spec's Diagnostic policy. Each location's blocking field names
   * which ones. Suppressed locations and, when only_new is set, locations present in the baseline
   * never block.
   */
  blocking: boolean;
  /**
   * Whether any location is new since baseline_spec_revision_id in the Diagnostic summary. Each
   * location's introduced field names which ones. Always true when there is no baseline.
   */
  introduced: boolean;
  /** Whether the rule reports invalid behavior, material risk, or an improvement. */
  severity: "error" | "warning" | "suggestion";
  /** Product dimension affected by the diagnostic. */
  category: "correctness" | "sdk_ergonomics" | "agent_usability" | "safety";
  /** Concise statement of the root cause. */
  title: string;
  /** One explanation of the finding and why it matters. */
  message: string;
  /** Public surfaces affected by the root cause. */
  surfaces: Array<"api" | "sdk" | "cli" | "mcp">;
  /** Whether remediation requires intent that the Spec cannot prove. */
  owner_decision_required: boolean;
  /**
   * The affected coordinates, kept under one grouped Diagnostic. With a filter, only the matching
   * locations.
   */
  locations: DiagnosticLocation[];
  fix?: DiagnosticFix;
  /**
   * Grounded instructions an agent can use to edit the source. The brief preserves existing
   * behavior and requires owner input when the contract cannot prove the missing product decision.
   */
  authoring_brief: string;
}

/** Response shape for Diagnostic. */
export interface DiagnosticRead {
  /** Stable rule identifier, unique within a Spec Revision. Suppressions name it as rule_id. */
  id: string;
  object: "diagnostic" | (string & {});
  /**
   * Whether any location fails the Spec's Diagnostic policy. Each location's blocking field names
   * which ones. Suppressed locations and, when only_new is set, locations present in the baseline
   * never block.
   */
  blocking: boolean;
  /**
   * Whether any location is new since baseline_spec_revision_id in the Diagnostic summary. Each
   * location's introduced field names which ones. Always true when there is no baseline.
   */
  introduced: boolean;
  /** Whether the rule reports invalid behavior, material risk, or an improvement. */
  severity: ("error" | "warning" | "suggestion") | (string & {});
  /** Product dimension affected by the diagnostic. */
  category: ("correctness" | "sdk_ergonomics" | "agent_usability" | "safety") | (string & {});
  /** Concise statement of the root cause. */
  title: string;
  /** One explanation of the finding and why it matters. */
  message: string;
  /** Public surfaces affected by the root cause. */
  surfaces: Array<("api" | "sdk" | "cli" | "mcp") | (string & {})>;
  /** Whether remediation requires intent that the Spec cannot prove. */
  owner_decision_required: boolean;
  /**
   * The affected coordinates, kept under one grouped Diagnostic. With a filter, only the matching
   * locations.
   */
  locations: DiagnosticLocation[];
  fix?: DiagnosticFixRead;
  /**
   * Grounded instructions an agent can use to edit the source. The brief preserves existing
   * behavior and requires owner input when the contract cannot prove the missing product decision.
   */
  authoring_brief: string;
}

/**
 * Counts of grouped Diagnostics, one per rule. Retrieve the revision with include=diagnostics for
 * each Diagnostic.
 */
export interface DiagnosticSummary {
  /**
   * passed: no Diagnostic fails the Spec's Diagnostic policy. blocked: at least one does; retrieve
   * with include=diagnostics and fix those marked blocking.
   */
  status: "passed" | "blocked";
  /** Diagnostics reporting invalid behavior. */
  error_count: number;
  /** Diagnostics reporting material risk. */
  warning_count: number;
  /** Diagnostics suggesting an improvement. */
  suggestion_count: number;
  /** Diagnostics that fail the Spec's Diagnostic policy. */
  blocking_count: number;
  /**
   * The previous revision of this Spec that introduced Diagnostics are compared with, or null for
   * the first revision.
   */
  baseline_spec_revision_id: SpecRevisionId | null;
}

/** Response shape for DiagnosticSummary. */
export interface DiagnosticSummaryRead {
  /**
   * passed: no Diagnostic fails the Spec's Diagnostic policy. blocked: at least one does; retrieve
   * with include=diagnostics and fix those marked blocking.
   */
  status: ("passed" | "blocked") | (string & {});
  /** Diagnostics reporting invalid behavior. */
  error_count: number;
  /** Diagnostics reporting material risk. */
  warning_count: number;
  /** Diagnostics suggesting an improvement. */
  suggestion_count: number;
  /** Diagnostics that fail the Spec's Diagnostic policy. */
  blocking_count: number;
  /**
   * The previous revision of this Spec that introduced Diagnostics are compared with, or null for
   * the first revision.
   */
  baseline_spec_revision_id: SpecRevisionId | null;
}

export interface DiagnosticSuppression {
  rule_id: string;
  /** Exact schema coordinate. Omit only to suppress every occurrence of the rule. */
  path?: string;
  /** The reviewed product decision behind this exception. */
  reason: string;
}

/**
 * Source pull-request enforcement threshold, new-versus-complete baseline, and explicitly reviewed
 * rule or location exceptions.
 */
export interface DiagnosticPolicy {
  /**
   * Severity threshold that fails the API change review check.
   * Default: "error"
   */
  fail_on: "never" | "error" | "warning";
  /**
   * Enforce only occurrences introduced by the proposed source change.
   * Default: true
   */
  only_new: boolean;
  /** Default: [] */
  suppressions: DiagnosticSuppression[];
}

/** Response shape for DiagnosticPolicy. */
export interface DiagnosticPolicyRead {
  /**
   * Severity threshold that fails the API change review check.
   * Default: "error"
   */
  fail_on: ("never" | "error" | "warning") | (string & {});
  /**
   * Enforce only occurrences introduced by the proposed source change.
   * Default: true
   */
  only_new: boolean;
  /** Default: [] */
  suppressions: DiagnosticSuppression[];
}

export interface DiagnosticWarning {
  code: "unsupported_format"
    | "invalid_document"
    | "invalid_patch"
    | "no_match"
    | "append_target_type"
    | "rename_target_type"
    | "rename_conflict";
  message: string;
}

/** Response shape for DiagnosticWarning. */
export interface DiagnosticWarningRead {
  code: ("unsupported_format"
    | "invalid_document"
    | "invalid_patch"
    | "no_match"
    | "append_target_type"
    | "rename_target_type"
    | "rename_conflict") | (string & {});
  message: string;
}

export interface RepositoryDeliverySettingsInput {
  provider: RepositoryProvider;
  identifier: RepositoryIdentifier;
  directory?: string | null;
  /** npm or Python registry identity where applicable. */
  package_name?: string | null;
  /** Go module identity for the Go SDK or CLI Target where applicable. */
  module_path?: string | null;
  /**
   * Commit repository-owned registry automation and report publication after the Draft merges.
   * Default: false
   */
  publish_on_merge?: boolean;
}

/** Response shape for RepositoryDeliverySettingsInput. */
export interface RepositoryDeliverySettingsInputRead {
  provider: RepositoryProvider | (string & {});
  identifier: RepositoryIdentifier;
  directory?: string | null;
  /** npm or Python registry identity where applicable. */
  package_name?: string | null;
  /** Go module identity for the Go SDK or CLI Target where applicable. */
  module_path?: string | null;
  /**
   * Commit repository-owned registry automation and report publication after the Draft merges.
   * Default: false
   */
  publish_on_merge?: boolean;
}

export interface RepositoryDeliveryInput {
  type: "repository";
  repository: RepositoryDeliverySettingsInput;
}

/** Response shape for RepositoryDeliveryInput. */
export interface RepositoryDeliveryInputRead {
  type: "repository";
  repository: RepositoryDeliverySettingsInputRead;
}

export interface HostedMcpDeliveryInput {
  type: "hosted_mcp";
}

export type DeliveryInput = RepositoryDeliveryInput | HostedMcpDeliveryInput;

/** Response shape for DeliveryInput. */
export type DeliveryInputRead = RepositoryDeliveryInputRead
  | HostedMcpDeliveryInput
  | UnknownVariant<"type">;

export interface RepositoryDeliveryCreateRequest {
  target_id: TargetId;
  type: "repository";
  repository: RepositoryDeliverySettingsInput;
}

/** Response shape for RepositoryDeliveryCreateRequest. */
export interface RepositoryDeliveryCreateRequestRead {
  target_id: TargetId;
  type: "repository";
  repository: RepositoryDeliverySettingsInputRead;
}

export interface HostedMcpDeliveryCreateRequest {
  target_id: TargetId;
  type: "hosted_mcp";
}

export type DeliveryCreateRequest = RepositoryDeliveryCreateRequest | HostedMcpDeliveryCreateRequest;

/** Response shape for DeliveryCreateRequest. */
export type DeliveryCreateRequestRead = RepositoryDeliveryCreateRequestRead
  | HostedMcpDeliveryCreateRequest
  | UnknownVariant<"type">;

export interface DeliveryUpdateRequest {
  /**
   * Replaces the complete repository settings, so omitted optional settings reset to their
   * defaults. Only repository Deliveries have settings to update.
   */
  repository: RepositoryDeliverySettingsInput;
}

/** Response shape for DeliveryUpdateRequest. */
export interface DeliveryUpdateRequestRead {
  /**
   * Replaces the complete repository settings, so omitted optional settings reset to their
   * defaults. Only repository Deliveries have settings to update.
   */
  repository: RepositoryDeliverySettingsInputRead;
}

export interface DeletedDelivery {
  id: DeliveryId;
  object: "delivery";
  deleted: true;
  request_id: RequestId;
}

/** Response shape for DeletedDelivery. */
export interface DeletedDeliveryRead {
  id: DeliveryId;
  object: "delivery" | (string & {});
  deleted: true;
  request_id: RequestId;
}

export interface RepositoryDeliverySettings {
  provider: RepositoryProvider;
  identifier: RepositoryIdentifier;
  directory: string | null;
  package_name: string | null;
  module_path: string | null;
  publish_on_merge: boolean;
}

/** Response shape for RepositoryDeliverySettings. */
export interface RepositoryDeliverySettingsRead {
  provider: RepositoryProvider | (string & {});
  identifier: RepositoryIdentifier;
  directory: string | null;
  package_name: string | null;
  module_path: string | null;
  publish_on_merge: boolean;
}

export interface HostedMcpDeliverySettings {
  /**
   * Hosted MCP endpoint for this Target, or null while it is being provisioned.
   * Format: uri
   */
  url: string | null;
}

export interface RepositoryDelivery {
  id: DeliveryId;
  object: "delivery";
  target_id: TargetId;
  type: "repository";
  /**
   * active: the repository accepts generated changes. action_required: inspect issues for the
   * correction. disabled: the Target is disabled and receives no changes.
   */
  status: "active" | "action_required" | "disabled";
  repository: RepositoryDeliverySettings;
  issues: RepositoryDeliveryIssue[];
  /** Repository check names Typeship expects before accepting a Draft. */
  required_checks: string[];
  /**
   * Last observed repository event relevant to this Delivery, if available. A failed event adds an
   * actionable issue.
   */
  last_event: RepositoryDeliveryEvent | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/** Response shape for RepositoryDelivery. */
export interface RepositoryDeliveryRead {
  id: DeliveryId;
  object: "delivery" | (string & {});
  target_id: TargetId;
  type: "repository";
  /**
   * active: the repository accepts generated changes. action_required: inspect issues for the
   * correction. disabled: the Target is disabled and receives no changes.
   */
  status: ("active" | "action_required" | "disabled") | (string & {});
  repository: RepositoryDeliverySettingsRead;
  issues: RepositoryDeliveryIssueRead[];
  /** Repository check names Typeship expects before accepting a Draft. */
  required_checks: string[];
  /**
   * Last observed repository event relevant to this Delivery, if available. A failed event adds an
   * actionable issue.
   */
  last_event: RepositoryDeliveryEventRead | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

export interface RepositoryDeliveryIssue {
  code: "app_not_installed"
    | "repository_unreachable"
    | "contents_write_missing"
    | "pull_request_missing"
    | "approval_label_missing"
    | "check_missing"
    | "event_failed";
  /** Specific customer action or repository setting to inspect. */
  message: string;
}

/** Response shape for RepositoryDeliveryIssue. */
export interface RepositoryDeliveryIssueRead {
  code: ("app_not_installed"
    | "repository_unreachable"
    | "contents_write_missing"
    | "pull_request_missing"
    | "approval_label_missing"
    | "check_missing"
    | "event_failed") | (string & {});
  /** Specific customer action or repository setting to inspect. */
  message: string;
}

export interface RepositoryDeliveryEvent {
  /** Repository event type. */
  event: string;
  /** superseded: a newer event for the same repository replaced this one before it finished. */
  status: "queued" | "running" | "completed" | "failed" | "superseded";
  /** Format: date-time */
  created_at: string;
}

/** Response shape for RepositoryDeliveryEvent. */
export interface RepositoryDeliveryEventRead {
  /** Repository event type. */
  event: string;
  /** superseded: a newer event for the same repository replaced this one before it finished. */
  status: ("queued" | "running" | "completed" | "failed" | "superseded") | (string & {});
  /** Format: date-time */
  created_at: string;
}

export interface HostedMcpDelivery {
  id: DeliveryId;
  object: "delivery";
  target_id: TargetId;
  type: "hosted_mcp";
  /**
   * active: the endpoint serves the Target's latest accepted package. disabled: the Target is
   * disabled and the endpoint is paused.
   */
  status: "active" | "disabled";
  hosted_mcp: HostedMcpDeliverySettings;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/** Response shape for HostedMcpDelivery. */
export interface HostedMcpDeliveryRead {
  id: DeliveryId;
  object: "delivery" | (string & {});
  target_id: TargetId;
  type: "hosted_mcp";
  /**
   * active: the endpoint serves the Target's latest accepted package. disabled: the Target is
   * disabled and the endpoint is paused.
   */
  status: ("active" | "disabled") | (string & {});
  hosted_mcp: HostedMcpDeliverySettings;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

export type Delivery = RepositoryDelivery | HostedMcpDelivery;

/** Response shape for Delivery. */
export type DeliveryRead = RepositoryDeliveryRead | HostedMcpDeliveryRead | UnknownVariant<"type">;

/**
 * repository is present for a repository Delivery, with issues, required_checks, and last_event;
 * hosted_mcp is present for a hosted_mcp Delivery.
 */
export interface DeliveryResponse {
  id: DeliveryId;
  object: "delivery";
  target_id: TargetId;
  type: "repository" | "hosted_mcp";
  status: "active" | "action_required" | "disabled";
  repository?: RepositoryDeliverySettings;
  issues?: RepositoryDeliveryIssue[];
  required_checks?: string[];
  last_event?: RepositoryDeliveryEvent | null;
  hosted_mcp?: HostedMcpDeliverySettings;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/** Response shape for DeliveryResponse. */
export interface DeliveryResponseRead {
  id: DeliveryId;
  object: "delivery" | (string & {});
  target_id: TargetId;
  type: ("repository" | "hosted_mcp") | (string & {});
  status: ("active" | "action_required" | "disabled") | (string & {});
  repository?: RepositoryDeliverySettingsRead;
  issues?: RepositoryDeliveryIssueRead[];
  required_checks?: string[];
  last_event?: RepositoryDeliveryEventRead | null;
  hosted_mcp?: HostedMcpDeliverySettings;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/**
 * Required checks run against the code in the Draft. Generated checks and customer commands share
 * one reproducible workflow; repository_required names existing repository checks. Supplying checks
 * replaces all settings. Omitted generated restores build, package, and public_entrypoint; omitted
 * repository_required and customer restore empty lists. An empty object restores these defaults. An
 * empty array clears the corresponding list.
 */
export interface TargetChecks {
  /** Default: ["build","package","public_entrypoint"] */
  generated?: Array<"build" | "package" | "public_entrypoint">;
  repository_required?: string[];
  customer?: Array<{
    name: string;
    command: string;
  }>;
}

/** Response shape for TargetChecks. */
export interface TargetChecksRead {
  /** Default: ["build","package","public_entrypoint"] */
  generated?: Array<("build" | "package" | "public_entrypoint") | (string & {})>;
  repository_required?: string[];
  customer?: Array<{
    name: string;
    command: string;
  }>;
}

export interface TargetCreateRequest {
  project_id: ProjectId;
  name: string;
  type: GeneratorKind;
  /** Default: "active" */
  status?: "active" | "disabled";
  /** Default: "stable" */
  release_channel?: "stable" | "prerelease";
  checks?: TargetChecks;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are rejected here and
   * belong to the Spec.
   */
  config?: TargetConfig | null;
  deliveries?: DeliveryInput[];
}

/** Response shape for TargetCreateRequest. */
export interface TargetCreateRequestRead {
  project_id: ProjectId;
  name: string;
  type: GeneratorKind | (string & {});
  /** Default: "active" */
  status?: ("active" | "disabled") | (string & {});
  /** Default: "stable" */
  release_channel?: ("stable" | "prerelease") | (string & {});
  checks?: TargetChecksRead;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are rejected here and
   * belong to the Spec.
   */
  config?: TargetConfigRead | null;
  deliveries?: DeliveryInputRead[];
}

export interface InitialTargetFields {
  name: string;
  type: GeneratorKind;
  /** Default: "active" */
  status?: "active" | "disabled";
  /** Default: "stable" */
  release_channel?: "stable" | "prerelease";
  checks?: TargetChecks;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are rejected here and
   * belong to the Spec.
   */
  config?: TargetConfig | null;
  deliveries?: DeliveryInput[];
}

/** Response shape for InitialTargetFields. */
export interface InitialTargetFieldsRead {
  name: string;
  type: GeneratorKind | (string & {});
  /** Default: "active" */
  status?: ("active" | "disabled") | (string & {});
  /** Default: "stable" */
  release_channel?: ("stable" | "prerelease") | (string & {});
  checks?: TargetChecksRead;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are rejected here and
   * belong to the Spec.
   */
  config?: TargetConfigRead | null;
  deliveries?: DeliveryInputRead[];
}

export interface TargetUpdateRequest {
  name?: string;
  status?: "active" | "disabled";
  release_channel?: "stable" | "prerelease";
  checks?: TargetChecks;
  /**
   * Replaces the complete stored override object. Send null or an empty object to resume Project
   * inheritance. Effective values merge over Project.config; GraphQL settings belong to the Spec.
   */
  config?: TargetConfig | null;
}

/** Response shape for TargetUpdateRequest. */
export interface TargetUpdateRequestRead {
  name?: string;
  status?: ("active" | "disabled") | (string & {});
  release_channel?: ("stable" | "prerelease") | (string & {});
  checks?: TargetChecksRead;
  /**
   * Replaces the complete stored override object. Send null or an empty object to resume Project
   * inheritance. Effective values merge over Project.config; GraphQL settings belong to the Spec.
   */
  config?: TargetConfigRead | null;
}

/**
 * All Targets follow reviewed SemVer. Before 1.0.0, breaking changes require a minor version; the
 * policy is fixed rather than configurable.
 */
export interface Target {
  id: TargetId;
  object: "target";
  project_id: ProjectId;
  spec_id: SpecId;
  name: string;
  type: GeneratorKind;
  status: "active" | "disabled";
  release_channel: "stable" | "prerelease";
  /**
   * Read-only version of the Target's latest release, or null before its first release. Publishing
   * status is separate; inspect the release for its results.
   */
  version_current: string | null;
  /** The Target's open Draft. After a merge it names the next Draft. */
  draft_id: DraftId;
  checks: TargetChecksResponse;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are Spec-owned and never
   * appear here.
   */
  config: TargetConfigResponse | null;
  /** At most one repository and one hosted MCP Delivery. */
  deliveries: Delivery[];
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id?: RequestId;
}

/** Request shape for Target. */
export interface TargetWrite {
  id: TargetId;
  object: "target";
  project_id: ProjectId;
  spec_id: SpecId;
  name: string;
  type: GeneratorKind;
  status: "active" | "disabled";
  release_channel: "stable" | "prerelease";
  checks: TargetChecksResponse;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are Spec-owned and never
   * appear here.
   */
  config: TargetConfigResponse | null;
  /** At most one repository and one hosted MCP Delivery. */
  deliveries: Delivery[];
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id?: RequestId;
}

/** Response shape for Target. */
export interface TargetRead {
  id: TargetId;
  object: "target" | (string & {});
  project_id: ProjectId;
  spec_id: SpecId;
  name: string;
  type: GeneratorKind | (string & {});
  status: ("active" | "disabled") | (string & {});
  release_channel: ("stable" | "prerelease") | (string & {});
  /**
   * Read-only version of the Target's latest release, or null before its first release. Publishing
   * status is separate; inspect the release for its results.
   */
  version_current: string | null;
  /** The Target's open Draft. After a merge it names the next Draft. */
  draft_id: DraftId;
  checks: TargetChecksResponseRead;
  /**
   * Target-specific overrides merged over Project.config. GraphQL settings are Spec-owned and never
   * appear here.
   */
  config: TargetConfigResponseRead | null;
  /** At most one repository and one hosted MCP Delivery. */
  deliveries: DeliveryRead[];
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id?: RequestId;
}

export type TargetResponse = Target & ResponseMetadata;

/** Request shape for TargetResponse. */
export type TargetResponseWrite = TargetWrite & ResponseMetadata;

/** Response shape for TargetResponse. */
export type TargetResponseRead = TargetRead & ResponseMetadata;

export interface DeliveryList {
  object: ListObject;
  data: Delivery[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for DeliveryList. */
export interface DeliveryListRead {
  object: ListObject;
  data: DeliveryRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export interface DraftList {
  object: ListObject;
  data: Draft[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for DraftList. */
export interface DraftListRead {
  object: ListObject;
  data: DraftRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export interface TargetList {
  object: ListObject;
  data: Target[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Request shape for TargetList. */
export interface TargetListWrite {
  object: ListObject;
  data: TargetWrite[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for TargetList. */
export interface TargetListRead {
  object: ListObject;
  data: TargetRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export interface Release {
  id: ReleaseId;
  object: "release";
  target_id: TargetId;
  /** Null only for a verified release imported during package adoption. */
  generation_id: GenerationId | null;
  origin: "typeship" | "imported";
  /** Immutable package version released from this Target. */
  version: string;
  /** The Target's release_channel when this version was released. */
  release_channel: "stable" | "prerelease";
  repository: RepositoryReferenceResponse | null;
  spec_revision_id: SpecRevisionId | null;
  /**
   * Git commit containing the accepted package. Compare it with the Delivery repository history or
   * checked-out commit.
   */
  commit_sha: string;
  checks: PackageCheck[];
  approvals: CompatibilityApproval[];
  /**
   * For an adopted Release, compare the tag and registry URL with the published package and its
   * artifact digest. Null for a Release created by Typeship.
   */
  import_provenance: {
    /** Git tag to compare with the repository release, if available. */
    tag: string | null;
    /**
     * Published package page to inspect, if available.
     * Format: uri
     */
    registry_url: string | null;
    /** Published artifact digest to compare with registry metadata, if available. */
    artifact_digest: string | null;
    /**
     * When Typeship recorded the adopted package.
     * Format: date-time
     */
    imported_at: string | null;
  }
    | null;
  /**
   * One entry per destination Typeship has attempted to publish. Empty when publishing is off for
   * the Target's repository Delivery.
   */
  publications: Publication[];
  /** Format: date-time */
  created_at: string;
  /**
   * When a Publication of this release last changed. The version, commit, and checks never change
   * after the release is created.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

/** Response shape for Release. */
export interface ReleaseRead {
  id: ReleaseId;
  object: "release" | (string & {});
  target_id: TargetId;
  /** Null only for a verified release imported during package adoption. */
  generation_id: GenerationId | null;
  origin: ("typeship" | "imported") | (string & {});
  /** Immutable package version released from this Target. */
  version: string;
  /** The Target's release_channel when this version was released. */
  release_channel: ("stable" | "prerelease") | (string & {});
  repository: RepositoryReferenceResponseRead | null;
  spec_revision_id: SpecRevisionId | null;
  /**
   * Git commit containing the accepted package. Compare it with the Delivery repository history or
   * checked-out commit.
   */
  commit_sha: string;
  checks: PackageCheckRead[];
  approvals: CompatibilityApprovalRead[];
  /**
   * For an adopted Release, compare the tag and registry URL with the published package and its
   * artifact digest. Null for a Release created by Typeship.
   */
  import_provenance: {
    /** Git tag to compare with the repository release, if available. */
    tag: string | null;
    /**
     * Published package page to inspect, if available.
     * Format: uri
     */
    registry_url: string | null;
    /** Published artifact digest to compare with registry metadata, if available. */
    artifact_digest: string | null;
    /**
     * When Typeship recorded the adopted package.
     * Format: date-time
     */
    imported_at: string | null;
  }
    | null;
  /**
   * One entry per destination Typeship has attempted to publish. Empty when publishing is off for
   * the Target's repository Delivery.
   */
  publications: PublicationRead[];
  /** Format: date-time */
  created_at: string;
  /**
   * When a Publication of this release last changed. The version, commit, and checks never change
   * after the release is created.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

export type ReleaseResponse = Release & ResponseMetadata;

/** Response shape for ReleaseResponse. */
export type ReleaseResponseRead = ReleaseRead & ResponseMetadata;

export interface ReleaseList {
  object: ListObject;
  data: Release[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for ReleaseList. */
export interface ReleaseListRead {
  object: ListObject;
  data: ReleaseRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** One destination's publishing progress for its Release. It has no ID; read it on the Release. */
export interface Publication {
  /**
   * Where the release is published. github is the repository's GitHub Release; the others are
   * package registries.
   */
  type: "github" | "npm" | "pypi" | "go" | "mcp";
  /**
   * queued: the repository workflow has not started this destination; get the Publication or its
   * Release again. running: the workflow is publishing; get it again. completed: the package is
   * published at registry_url. failed: read errors, correct the cause, then retry the Release.
   * Lifecycle events are publication.running, publication.completed, and publication.failed.
   */
  status: "queued" | "running" | "completed" | "failed";
  attempt: number;
  /** Format: uri */
  run_url: string | null;
  /** Format: uri */
  registry_url: string | null;
  artifact_digest: string | null;
  /** Recorded failures. Empty when this resource has no recorded failure. */
  errors: DomainError[];
  /** Format: date-time */
  started_at: string | null;
  /** Format: date-time */
  finished_at: string | null;
  /** Milliseconds from started_at to finished_at; null until the attempt finishes. */
  runtime_ms: number | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/** Response shape for Publication. */
export interface PublicationRead {
  /**
   * Where the release is published. github is the repository's GitHub Release; the others are
   * package registries.
   */
  type: ("github" | "npm" | "pypi" | "go" | "mcp") | (string & {});
  /**
   * queued: the repository workflow has not started this destination; get the Publication or its
   * Release again. running: the workflow is publishing; get it again. completed: the package is
   * published at registry_url. failed: read errors, correct the cause, then retry the Release.
   * Lifecycle events are publication.running, publication.completed, and publication.failed.
   */
  status: ("queued" | "running" | "completed" | "failed") | (string & {});
  attempt: number;
  /** Format: uri */
  run_url: string | null;
  /** Format: uri */
  registry_url: string | null;
  artifact_digest: string | null;
  /** Recorded failures. Empty when this resource has no recorded failure. */
  errors: DomainErrorRead[];
  /** Format: date-time */
  started_at: string | null;
  /** Format: date-time */
  finished_at: string | null;
  /** Milliseconds from started_at to finished_at; null until the attempt finishes. */
  runtime_ms: number | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/**
 * idle: the open Draft has no pending change; generate the Target to start one. working: Typeship
 * is generating, carrying repository edits forward, applying decisions, or checking the Draft;
 * retrieve it again. action_required: use the typed reason to find the customer's next action.
 * ready: required checks passed on head_sha; merge the pull request. merged: the pull request
 * merged and the Draft is final; retrieve the Target for the draft_id of its next Draft.
 */
export const DraftStatus = {
  IDLE: "idle",
  WORKING: "working",
  ACTION_REQUIRED: "action_required",
  READY: "ready",
  MERGED: "merged",
} as const;
export type DraftStatus = (typeof DraftStatus)[keyof typeof DraftStatus];

/**
 * conflict: resolve the listed files. checks_failed: correct failed package checks. review_failed:
 * correct the Draft title or version. checks_unavailable: restore a required check.
 * history_rewritten: review the affected files and approve recovery.
 */
export const DraftActionReason = {
  CONFLICT: "conflict",
  CHECKS_FAILED: "checks_failed",
  REVIEW_FAILED: "review_failed",
  CHECKS_UNAVAILABLE: "checks_unavailable",
  HISTORY_REWRITTEN: "history_rewritten",
} as const;
export type DraftActionReason = (typeof DraftActionReason)[keyof typeof DraftActionReason];

export interface DraftConflicts {
  /** Conflicts in the current merge stage. */
  total: number;
  /** Conflicts with a saved decision for head_sha. */
  decided: number;
}

/** The approval inputs for a default-branch history rewrite. */
export interface DraftHistoryRecovery {
  /** Rewritten default-branch commit. Send it as expected_default_sha. */
  default_sha: string;
  /** Draft commit Typeship last observed. Send it as expected_head_sha. */
  head_sha: string | null;
  /** Existing Draft branch that stays available after recovery opens a new Draft. */
  preserved_branch: string | null;
}

/** Comparison of the Draft's head_sha with the latest release. */
export interface DraftCompatibility {
  /** API surface comparison. unknown means analysis is unavailable. */
  api: "compatible" | "breaking" | "unknown";
  /**
   * Package and supported SDK source comparison. unknown means analysis is incomplete or
   * unavailable.
   */
  package: "compatible" | "breaking" | "unknown";
}

/** Response shape for DraftCompatibility. */
export interface DraftCompatibilityRead {
  /** API surface comparison. unknown means analysis is unavailable. */
  api: ("compatible" | "breaking" | "unknown") | (string & {});
  /**
   * Package and supported SDK source comparison. unknown means analysis is incomplete or
   * unavailable.
   */
  package: ("compatible" | "breaking" | "unknown") | (string & {});
}

/** How version_next relates to the assessed change. */
export interface DraftVersion {
  /**
   * Minimum assessed version bump. Approval never waives an insufficient bump. Null when no bump
   * has been determined.
   */
  bump_required: "major" | "minor" | "patch" | null;
  /** Whether version_next satisfies the assessed change. Null when no verdict is available. */
  correct: boolean | null;
  /** Latest release version used for the comparison. Null before the first release. */
  previous: string | null;
}

/** Response shape for DraftVersion. */
export interface DraftVersionRead {
  /**
   * Minimum assessed version bump. Approval never waives an insufficient bump. Null when no bump
   * has been determined.
   */
  bump_required: ("major" | "minor" | "patch" | null) | (string & {}) | null;
  /** Whether version_next satisfies the assessed change. Null when no verdict is available. */
  correct: boolean | null;
  /** Latest release version used for the comparison. Null before the first release. */
  previous: string | null;
}

/**
 * One reviewed package change for a Target. A Target has one open Draft, named by its draft_id;
 * when the pull request merges, the Draft becomes merged and final, and the Target opens a new
 * Draft with a new ID.
 */
export interface Draft {
  id: DraftId;
  object: "draft";
  target_id: TargetId;
  project_id: ProjectId;
  status: DraftStatus;
  /** Present and required when status is action_required; absent otherwise. */
  reason?: DraftActionReason;
  /** Next version for this Draft, or null before a version is selected. */
  version_next: string | null;
  /** Where version_next was selected; null once the Draft merged. */
  version_source: "automatic" | "console" | "api" | "github" | null;
  /** Null until the Draft has a generated change, and on a merged Draft. */
  compatibility: DraftCompatibility | null;
  /** Null until the Draft has a generated change, and on a merged Draft. */
  version: DraftVersion | null;
  /**
   * What blocks the Draft, one entry per finding, each with a code and suggested_action. Empty
   * unless status is action_required.
   */
  errors: ErrorDetail[];
  changes: {
    /** Cumulative changelog against the latest release. */
    changelog?: string | null;
    breaking_count?: number | null;
  }
    | null;
  /**
   * Draft commit that compatibility, version, checks, and conflicts describe. Send it as
   * expected_head_sha when resolving or discarding.
   */
  head_sha: string | null;
  /** The Draft pull request in the destination repository, or null before one is opened. */
  pull_request: {
    /** Format: uri */
    url: string;
    number: number;
  } | null;
  /** Generation whose package this Draft contains. */
  generation_id: GenerationId | null;
  /**
   * Release this Draft created when it merged; null while open, or when a merge changed only tests
   * or checks.
   */
  release_id: ReleaseId | null;
  /**
   * When the Draft opened.
   * Format: date-time
   */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  /** Conflict counts for the current merge stage; null when the Draft has no conflicts. */
  conflicts: DraftConflicts | null;
  /**
   * Files where the Draft differs from the last accepted package; null until the Draft is
   * integrated.
   */
  customized_files: number | null;
  /** Present only while status is action_required and reason is history_rewritten. */
  history_recovery: DraftHistoryRecovery | null;
  request_id?: RequestId;
  checks: PackageCheck[];
}

/** Response shape for Draft. */
export interface DraftRead {
  id: DraftId;
  object: "draft" | (string & {});
  target_id: TargetId;
  project_id: ProjectId;
  status: DraftStatus | (string & {});
  /** Present and required when status is action_required; absent otherwise. */
  reason?: DraftActionReason | (string & {});
  /** Next version for this Draft, or null before a version is selected. */
  version_next: string | null;
  /** Where version_next was selected; null once the Draft merged. */
  version_source: ("automatic" | "console" | "api" | "github" | null) | (string & {}) | null;
  /** Null until the Draft has a generated change, and on a merged Draft. */
  compatibility: DraftCompatibilityRead | null;
  /** Null until the Draft has a generated change, and on a merged Draft. */
  version: DraftVersionRead | null;
  /**
   * What blocks the Draft, one entry per finding, each with a code and suggested_action. Empty
   * unless status is action_required.
   */
  errors: ErrorDetailRead[];
  changes: {
    /** Cumulative changelog against the latest release. */
    changelog?: string | null;
    breaking_count?: number | null;
  }
    | null;
  /**
   * Draft commit that compatibility, version, checks, and conflicts describe. Send it as
   * expected_head_sha when resolving or discarding.
   */
  head_sha: string | null;
  /** The Draft pull request in the destination repository, or null before one is opened. */
  pull_request: {
    /** Format: uri */
    url: string;
    number: number;
  } | null;
  /** Generation whose package this Draft contains. */
  generation_id: GenerationId | null;
  /**
   * Release this Draft created when it merged; null while open, or when a merge changed only tests
   * or checks.
   */
  release_id: ReleaseId | null;
  /**
   * When the Draft opened.
   * Format: date-time
   */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  /** Conflict counts for the current merge stage; null when the Draft has no conflicts. */
  conflicts: DraftConflicts | null;
  /**
   * Files where the Draft differs from the last accepted package; null until the Draft is
   * integrated.
   */
  customized_files: number | null;
  /** Present only while status is action_required and reason is history_rewritten. */
  history_recovery: DraftHistoryRecovery | null;
  request_id?: RequestId;
  checks: PackageCheckRead[];
}

export type DraftResponse = Draft & ResponseMetadata;

/** Response shape for DraftResponse. */
export type DraftResponseRead = DraftRead & ResponseMetadata;

export interface DraftUpdateRequest {
  /** Exact SemVer, or null to return to automatic selection. */
  version_next: string | null;
}

export interface PackageCheck {
  name: string;
  source: "typeship" | "customer" | "repository" | "compatibility";
  required: boolean;
  status: "pending" | "passed" | "failed" | "not_assessed";
  reason: string;
  commit_sha: string;
  /** Format: uri */
  url: string | null;
  /** Format: date-time */
  observed_at: string | null;
}

/** Response shape for PackageCheck. */
export interface PackageCheckRead {
  name: string;
  source: ("typeship" | "customer" | "repository" | "compatibility") | (string & {});
  required: boolean;
  status: ("pending" | "passed" | "failed" | "not_assessed") | (string & {});
  reason: string;
  commit_sha: string;
  /** Format: uri */
  url: string | null;
  /** Format: date-time */
  observed_at: string | null;
}

export interface CompatibilityApproval {
  source: "source_pr" | "draft_pr";
  reason: string;
  approved_by: string;
  approved_sha: string;
  /** Format: date-time */
  approved_at: string;
}

/** Response shape for CompatibilityApproval. */
export interface CompatibilityApprovalRead {
  source: ("source_pr" | "draft_pr") | (string & {});
  reason: string;
  approved_by: string;
  approved_sha: string;
  /** Format: date-time */
  approved_at: string;
}

export interface TargetAdoption {
  /** Exact already-published package version to make the latest release. */
  version: string;
  /** Immutable repository tag containing the matching package source. */
  tag: string;
}

export interface SpecFields {
  source: SpecSourceInput;
  /** Default: [] */
  patches?: SpecPatch[];
  /** GraphQL-only endpoint, auth, environment, title, and scalar settings. */
  graphql?: GraphqlSettings | null;
  diagnostic_policy?: DiagnosticPolicy;
}

/** Response shape for SpecFields. */
export interface SpecFieldsRead {
  source: SpecSourceInputRead;
  /** Default: [] */
  patches?: SpecPatchRead[];
  /** GraphQL-only endpoint, auth, environment, title, and scalar settings. */
  graphql?: GraphqlSettingsRead | null;
  diagnostic_policy?: DiagnosticPolicyRead;
}

export interface Spec {
  id: SpecId;
  object: "spec";
  project_id: ProjectId;
  source: SpecSource;
  format: "openapi" | "graphql" | null;
  patches: SpecPatchResponse[];
  graphql: GraphqlSettingsResponse | null;
  diagnostic_policy: DiagnosticPolicyResponse;
  revision_latest_id: SpecRevisionId | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/** Request shape for Spec. */
export interface SpecWrite {
  id: SpecId;
  object: "spec";
  project_id: ProjectId;
  source: SpecSourceWrite;
  format: "openapi" | "graphql" | null;
  patches: SpecPatchResponse[];
  graphql: GraphqlSettingsResponse | null;
  diagnostic_policy: DiagnosticPolicyResponse;
  revision_latest_id: SpecRevisionId | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/** Response shape for Spec. */
export interface SpecRead {
  id: SpecId;
  object: "spec" | (string & {});
  project_id: ProjectId;
  source: SpecSourceRead;
  format: ("openapi" | "graphql" | null) | (string & {}) | null;
  patches: SpecPatchResponseRead[];
  graphql: GraphqlSettingsResponseRead | null;
  diagnostic_policy: DiagnosticPolicyResponseRead;
  revision_latest_id: SpecRevisionId | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/**
 * Omitted fields remain unchanged. Supplied objects and arrays replace the whole field. URL source
 * headers are preserved when the URL is unchanged and headers are omitted; null or empty headers
 * clear them.
 */
export interface SpecUpdateRequest {
  source?: SpecSourceInput;
  /** Replace all patches in order. An empty array removes every patch; null is invalid. */
  patches?: SpecPatch[];
  /** Replace all GraphQL settings. Null or an empty object clears them. */
  graphql?: GraphqlSettings | null;
  /** Replace the complete policy and suppression list. Null and an empty object are invalid. */
  diagnostic_policy?: DiagnosticPolicy;
}

/** Response shape for SpecUpdateRequest. */
export interface SpecUpdateRequestRead {
  source?: SpecSourceInputRead;
  /** Replace all patches in order. An empty array removes every patch; null is invalid. */
  patches?: SpecPatchRead[];
  /** Replace all GraphQL settings. Null or an empty object clears them. */
  graphql?: GraphqlSettingsRead | null;
  /** Replace the complete policy and suppression list. Null and an empty object are invalid. */
  diagnostic_policy?: DiagnosticPolicyRead;
}

/**
 * Project-owned identity, Spec reference, generation controls, and shared configuration. Targets
 * and Deliveries are available only through their canonical Target endpoints.
 */
export interface Project {
  id: ProjectId;
  object: "project";
  name: string;
  spec_id: SpecId;
  /**
   * Regenerate when the Spec or saved configuration changes. Enabled by default for new Projects.
   * Set false to generate only when requested.
   */
  auto_generate: boolean;
  /**
   * Shared defaults inherited by every Target. A Target's config overrides these defaults; GraphQL
   * settings remain Spec-owned.
   */
  config: ProjectConfigResponse | null;
  /** Format: date-time */
  created_at: string;
  /**
   * When the project configuration last changed.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

/** Request shape for Project. */
export interface ProjectWrite {
  name: string;
  spec_id: SpecId;
  /**
   * Regenerate when the Spec or saved configuration changes. Enabled by default for new Projects.
   * Set false to generate only when requested.
   */
  auto_generate: boolean;
  /**
   * Shared defaults inherited by every Target. A Target's config overrides these defaults; GraphQL
   * settings remain Spec-owned.
   */
  config: ProjectConfigResponse | null;
  request_id?: RequestId;
}

/** Response shape for Project. */
export interface ProjectRead {
  id: ProjectId;
  object: "project" | (string & {});
  name: string;
  spec_id: SpecId;
  /**
   * Regenerate when the Spec or saved configuration changes. Enabled by default for new Projects.
   * Set false to generate only when requested.
   */
  auto_generate: boolean;
  /**
   * Shared defaults inherited by every Target. A Target's config overrides these defaults; GraphQL
   * settings remain Spec-owned.
   */
  config: ProjectConfigResponseRead | null;
  /** Format: date-time */
  created_at: string;
  /**
   * When the project configuration last changed.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

export type ProjectResponse = Project & ResponseMetadata;

/** Request shape for ProjectResponse. */
export type ProjectResponseWrite = ProjectWrite & ResponseMetadata;

/** Response shape for ProjectResponse. */
export type ProjectResponseRead = ProjectRead & ResponseMetadata;

export interface CreateProjectRequest {
  name: string;
  spec: SpecFields;
  /**
   * Initial first-class Targets. More than one may use the same generator with different identities
   * or Deliveries.
   */
  targets: InitialTargetFields[];
  /**
   * Whether Typeship should regenerate automatically when the source or saved configuration
   * changes.
   * Default: true
   */
  auto_generate?: boolean;
  /** Shared defaults inherited by every Target. GraphQL settings belong in spec.graphql. */
  config?: ProjectConfig | null;
}

/** Response shape for CreateProjectRequest. */
export interface CreateProjectRequestRead {
  name: string;
  spec: SpecFieldsRead;
  /**
   * Initial first-class Targets. More than one may use the same generator with different identities
   * or Deliveries.
   */
  targets: InitialTargetFieldsRead[];
  /**
   * Whether Typeship should regenerate automatically when the source or saved configuration
   * changes.
   * Default: true
   */
  auto_generate?: boolean;
  /** Shared defaults inherited by every Target. GraphQL settings belong in spec.graphql. */
  config?: ProjectConfigRead | null;
}

export interface UpdateProjectRequest {
  name?: string;
  auto_generate?: boolean;
  /** Replaces the Project's shared Target defaults. Send null to clear them. */
  config?: ProjectConfig | null;
}

/** Response shape for UpdateProjectRequest. */
export interface UpdateProjectRequestRead {
  name?: string;
  auto_generate?: boolean;
  /** Replaces the Project's shared Target defaults. Send null to clear them. */
  config?: ProjectConfigRead | null;
}

/**
 * The organization an API key belongs to. Members share its projects, keys, and plan; sign-in
 * identity is not part of the API.
 */
export interface Organization {
  /** Opaque, output-only organization identifier. Copy it unchanged; its format is not a contract. */
  id: string;
  object: "organization";
  /** The organization's display name. */
  name: string;
  plan: "free" | "pro" | "enterprise";
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/** Request shape for Organization. */
export interface OrganizationWrite {
  object: "organization";
  /** The organization's display name. */
  name: string;
  plan: "free" | "pro" | "enterprise";
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/** Response shape for Organization. */
export interface OrganizationRead {
  /** Opaque, output-only organization identifier. Copy it unchanged; its format is not a contract. */
  id: string;
  object: "organization" | (string & {});
  /** The organization's display name. */
  name: string;
  plan: ("free" | "pro" | "enterprise") | (string & {});
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
  request_id: RequestId;
}

/**
 * Authorization-server metadata used by generated OAuth flows. Secrets and runtime credentials are
 * never accepted here.
 */
export interface OAuthServer {
  /**
   * Exact authorization-server issuer, including any tenant path.
   * Format: uri
   */
  issuer?: string | null;
  /**
   * Exact metadata URL when it cannot be derived from the issuer.
   * Format: uri
   */
  discovery_url?: string | null;
  /**
   * Authorization endpoint override.
   * Format: uri
   */
  authorization_url?: string | null;
  /**
   * Token endpoint override.
   * Format: uri
   */
  token_url?: string | null;
  /**
   * Device-authorization endpoint override.
   * Format: uri
   */
  device_authorization_url?: string | null;
  /** Default scopes requested during login. */
  scopes?: string[] | null;
  /** Default audience included in authorization and token requests. */
  audience?: string | null;
  /**
   * Protected API resource included in authorization and token requests.
   * Format: uri
   */
  resource?: string | null;
}

/**
 * OAuth application available to generated products. Public clients support interactive login;
 * confidential clients support runtime-supplied machine credentials. Client secrets are never
 * stored.
 */
export interface OAuthApplication {
  /** OAuth client identifier. */
  client_id: string;
  /** Interactive login method. Browser login uses Authorization Code with PKCE. */
  login_method?: "browser" | "device" | null;
  /** How a runtime-supplied client secret is sent for machine grants. */
  client_auth_method?: "post" | "basic" | null;
  /**
   * Loopback callback URL for browser login.
   * Format: uri
   */
  redirect_uri?: string | null;
  /** Provider parameter used to request an organization during browser login. */
  organization_parameter?: "organization" | "organization_id" | null;
}

/** Response shape for OAuthApplication. */
export interface OAuthApplicationRead {
  /** OAuth client identifier. */
  client_id: string;
  /** Interactive login method. Browser login uses Authorization Code with PKCE. */
  login_method?: ("browser" | "device" | null) | (string & {}) | null;
  /** How a runtime-supplied client secret is sent for machine grants. */
  client_auth_method?: ("post" | "basic" | null) | (string & {}) | null;
  /**
   * Loopback callback URL for browser login.
   * Format: uri
   */
  redirect_uri?: string | null;
  /** Provider parameter used to request an organization during browser login. */
  organization_parameter?: ("organization" | "organization_id" | null) | (string & {}) | null;
}

/**
 * Authenticated identity read used to verify a login before it is saved. Operation is auto-detected
 * when omitted or null. At least one of subject_field, account_field, or organization_field must be
 * a non-null JSON Pointer. Null clears an individual mapping while another remains. Set
 * identity_verification itself to null to remove the whole policy.
 */
export type IdentityVerification = {
  /** resource.method of a safe identity read with no required arguments. */
  operation?: string | null;
  /** JSON Pointer to the stable caller ID in the identity response. */
  subject_field?: string | null;
  /** JSON Pointer to the customer account ID. */
  account_field?: string | null;
  /** JSON Pointer to the customer organization ID. */
  organization_field?: string | null;
} & ({
  subject_field: string;
}
  | {
      account_field: string;
    }
  | {
      organization_field: string;
    });

/** OAuth application and request-value overrides for one named API environment. */
export interface AuthenticationEnvironment {
  oauth_application?: string | null;
  scopes?: string[] | null;
  audience?: string | null;
  /** Format: uri */
  resource?: string | null;
}

/**
 * Public authentication defaults for generated clients and tools. Stored Projects own the OAuth
 * server, application catalog, and identity policy; one-shot generation accepts the same shape for
 * one run. Runtime credentials and client secrets are never accepted.
 */
export interface AuthenticationConfig {
  oauth_server?: OAuthServer | null;
  /** OAuth applications keyed by a stable name. */
  oauth_applications?: Record<string, OAuthApplication> | null;
  /** Default OAuth application used by generated products. */
  oauth_application?: string | null;
  identity_verification?: IdentityVerification | null;
  /**
   * Base URL of a custom browser-approval backend implementing the start, status, and revoke
   * contract. Used only when OAuth is not configured.
   * Format: uri
   */
  approval_url?: string | null;
  /** Authentication selections keyed by generated API environment name. */
  environments?: Record<string, AuthenticationEnvironment> | null;
  /**
   * Environment variables the generated CLI, MCP server, and SDK environment fallbacks read, keyed
   * by security scheme name. A string names the token or key variable; a Basic scheme takes {
   * username, password }. Wins over the scheme's x-typeship-env extension. Without either, names
   * derive from the package and scheme.
   */
  credential_variables?: Record<string, string | {
    username: string;
    password: string;
  }>
    | null;
  /**
   * Whether a parameter carries the operation's credential, keyed by operationId, "METHOD /path",
   * or "*" for every operation, then by the parameter's wire name. true leaves the parameter out of
   * generated signatures, CLI flags, and MCP tool input, because the configured credential already
   * reaches the API; false keeps it. Wins over the parameter's x-typeship-credential extension and
   * the generator's inference.
   */
  credential_parameters?: Record<string, Record<string, boolean>> | null;
}

export interface TargetAuthenticationEnvironment {
  oauth_application?: string | null;
}

/**
 * Selects a Project OAuth application for one Target. OAuth server metadata, applications, and
 * identity policy remain Project-owned.
 */
export interface TargetAuthenticationConfig {
  /** Project OAuth application to use. Omit to inherit the Project default. */
  oauth_application?: string | null;
  /** Project OAuth application selections keyed by API environment. */
  environments?: Record<string, TargetAuthenticationEnvironment> | null;
}

/** How the generated CLI behaves. Part of Config. */
export interface CliBehavior {
  /** Command users run, independent of how the CLI is distributed. */
  command_name?: string | null;
  /**
   * Opt in to a once-a-day registry check that prints an upgrade hint. Off by default; generated
   * code phones nobody unless this is enabled.
   */
  update_notice?: boolean;
  /**
   * Public HTTP(S) URL read by the optional changelog command in generated CLIs. Supports UTF-8
   * Markdown, plain text, and static HTML; embedded credentials are not allowed. Omit or clear to
   * disable, then regenerate.
   */
  changelog_url?: string | null;
  /**
   * Where the generated CLI's feedback command sends users. GitHub issues/new URLs get a prefilled
   * title and environment details.
   */
  support_url?: string | null;
  /**
   * Hosted MCP endpoint installed by the generated CLI instead of launching the package's local
   * stdio server.
   */
  mcp_url?: string | null;
  /** GitHub owner/name of the skills package the generated CLI offers to install during init. */
  skills_repo?: string | null;
}

/** How the generated CLI behaves. Part of Config. */
export interface TargetCliBehavior {
  /** Command users run, independent of how the CLI is distributed. */
  command_name?: string | null;
  /**
   * Opt in to a once-a-day registry check that prints an upgrade hint. Off by default; generated
   * code phones nobody unless this is enabled.
   */
  update_notice?: boolean;
  /**
   * Public HTTP(S) URL read by the optional changelog command in generated CLIs. Supports UTF-8
   * Markdown, plain text, and static HTML; embedded credentials are not allowed. Omit or clear to
   * disable, then regenerate.
   */
  changelog_url?: string | null;
  /**
   * Where the generated CLI's feedback command sends users. GitHub issues/new URLs get a prefilled
   * title and environment details.
   */
  support_url?: string | null;
  /**
   * Hosted MCP endpoint installed by the generated CLI instead of launching the package's local
   * stdio server.
   */
  mcp_url?: string | null;
  /** GitHub owner/name of the skills package the generated CLI offers to install during init. */
  skills_repo?: string | null;
  /**
   * Enable webhook relay sessions for this CLI Target. Requires Pro. Turning it off prevents new
   * sessions.
   */
  relay?: boolean;
  /**
   * Also generate unit tests for the helper code a CLI shares, such as raw API path checks, saved
   * credentials, and MCP client configuration. Applies to cli Targets. Off by default; tests for
   * the generated commands are always included.
   */
  unit_tests?: boolean;
}

/** How generated MCP servers and the Typeship-hosted endpoint behave. Part of Config. */
export interface McpBehavior {
  /** Stable official MCP registry name, independent of the server runtime. */
  registry_name?: string | null;
  /**
   * Authorization for callers connecting to a generated MCP server deployed over HTTP. The hosting
   * application resolves upstream API credentials separately at runtime. This setting does not
   * apply to the Typeship-hosted endpoint.
   */
  access?: {
    /**
     * Exact issuer allowed to sign MCP connection tokens.
     * Format: uri
     */
    issuer: string;
    /**
     * Canonical public URL of the self-hosted MCP endpoint that connection tokens must target.
     * Format: uri
     */
    resource: string;
    /**
     * Public signing-key endpoint. Omit to discover it from the issuer.
     * Format: uri
     */
    jwks_url?: string;
    /** Minimum scopes required to connect to the self-hosted MCP server. */
    scopes?: string[];
  };
  /**
   * MCP tool shape. meta collapses per-operation tools into search_docs, read_docs, and execute so
   * large APIs don't flood an agent's context window. Auto considers the serialized tool schemas,
   * switching near 10k tokens or above 100 operations.
   */
  tool_mode?: "auto" | "operations" | "meta";
  /**
   * Guidance appended to the MCP server's instructions, which agents read once when they connect
   * (server/discover): what to call first, conventions the spec does not state, what not to do.
   * Carried by the package's server and the hosted endpoint alike.
   */
  instructions?: string | null;
  /**
   * Hand-written MCP tool descriptions keyed by operationId or "METHOD /path". Each replaces the
   * text typeship derives for that operation (summary, first sentence, method and path, deprecation
   * and auth notes). For flows the spec cannot describe, such as a multi-step upload. Keys that
   * match no operation are reported as generation warnings.
   */
  tool_descriptions?: Record<string, string>;
  /**
   * Exact name-or-ID resolver overrides keyed first by the target operationId or "METHOD /path",
   * then by its wire argument name. A resolver names one read collection operation plus 1-4 item
   * fields to match case-insensitively; false opts that argument out of strict inference.
   */
  reference_resolvers?: Record<string, Record<string, false
    | {
        /** OperationId, "METHOD /path", MCP tool name, or dotted resource.method of the list operation. */
        via: string;
        /** Item fields compared exactly and case-insensitively, such as name, slug, key, or email. */
        match: string[];
        /** Item field substituted into the requested argument. Defaults to id. */
        id?: string;
      }>>;
}

/** Response shape for McpBehavior. */
export interface McpBehaviorRead {
  /** Stable official MCP registry name, independent of the server runtime. */
  registry_name?: string | null;
  /**
   * Authorization for callers connecting to a generated MCP server deployed over HTTP. The hosting
   * application resolves upstream API credentials separately at runtime. This setting does not
   * apply to the Typeship-hosted endpoint.
   */
  access?: {
    /**
     * Exact issuer allowed to sign MCP connection tokens.
     * Format: uri
     */
    issuer: string;
    /**
     * Canonical public URL of the self-hosted MCP endpoint that connection tokens must target.
     * Format: uri
     */
    resource: string;
    /**
     * Public signing-key endpoint. Omit to discover it from the issuer.
     * Format: uri
     */
    jwks_url?: string;
    /** Minimum scopes required to connect to the self-hosted MCP server. */
    scopes?: string[];
  };
  /**
   * MCP tool shape. meta collapses per-operation tools into search_docs, read_docs, and execute so
   * large APIs don't flood an agent's context window. Auto considers the serialized tool schemas,
   * switching near 10k tokens or above 100 operations.
   */
  tool_mode?: ("auto" | "operations" | "meta") | (string & {});
  /**
   * Guidance appended to the MCP server's instructions, which agents read once when they connect
   * (server/discover): what to call first, conventions the spec does not state, what not to do.
   * Carried by the package's server and the hosted endpoint alike.
   */
  instructions?: string | null;
  /**
   * Hand-written MCP tool descriptions keyed by operationId or "METHOD /path". Each replaces the
   * text typeship derives for that operation (summary, first sentence, method and path, deprecation
   * and auth notes). For flows the spec cannot describe, such as a multi-step upload. Keys that
   * match no operation are reported as generation warnings.
   */
  tool_descriptions?: Record<string, string>;
  /**
   * Exact name-or-ID resolver overrides keyed first by the target operationId or "METHOD /path",
   * then by its wire argument name. A resolver names one read collection operation plus 1-4 item
   * fields to match case-insensitively; false opts that argument out of strict inference.
   */
  reference_resolvers?: Record<string, Record<string, false | (string & {})
    | {
        /** OperationId, "METHOD /path", MCP tool name, or dotted resource.method of the list operation. */
        via: string;
        /** Item fields compared exactly and case-insensitively, such as name, slug, key, or email. */
        match: string[];
        /** Item field substituted into the requested argument. Defaults to id. */
        id?: string;
      }>>;
}

/** Generated README behavior. Part of Config. */
export interface ReadmeBehavior {
  /**
   * operationId or "METHOD /path" to feature as the README's first API call. It must be present in
   * the generated package and callable with no required input beyond path placeholders. Missing or
   * unsuitable choices produce a warning and use the automatic example.
   */
  quickstart_operation?: string | null;
}

/**
 * Published-package metadata the API spec does not own. Repository is derived from each
 * destination.
 */
export interface PackageBehavior {
  /**
   * The API's name as generated READMEs, AGENTS.md, package descriptions, and help text show it,
   * such as "Parcel" for a Spec titled "Parcel - Public API". Display only: package, client, and
   * command names still come from the Spec. Defaults to the Spec title with common noise removed
   * ("Parcel - API" shows as Parcel).
   */
  title?: string | null;
  /** Homepage written into registry metadata. */
  homepage?: string | null;
  /** SPDX identifier written into registry metadata. Defaults to info.license. */
  license?: string | null;
  /**
   * Exact LICENSE file contents. Supply this for licences the engine does not build in; MIT is
   * built in when copyright is also set.
   */
  license_text?: string | null;
  /** Copyright line used in generated license files. */
  copyright?: string | null;
  /** Go identifier when the destination repository name is unsuitable. */
  go_package_name?: string | null;
}

/**
 * Everything Typeship needs beyond the Spec, in one object: generation customization (globals,
 * retries, pagination, readme) and how the generated tooling behaves (cli, mcp, package, docs_url).
 * Plain configuration. Typeship never requires vendor extensions inside the Spec itself. One-shot
 * generation also accepts GraphQL settings here; stored projects keep those settings on their Spec.
 */
export interface Config {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRule | boolean>;
  graphql?: GraphqlSettings;
  auth?: AuthenticationConfig;
  cli?: CliBehavior;
  mcp?: McpBehavior;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** Response shape for Config. */
export interface ConfigRead {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleRead | boolean>;
  graphql?: GraphqlSettingsRead;
  auth?: AuthenticationConfig;
  cli?: CliBehavior;
  mcp?: McpBehaviorRead;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/**
 * Shared generated-client and tooling behavior for a stored Project. Every Target inherits these
 * defaults. Target.config is merged over them for one Target; top-level values replace defaults
 * while cli, mcp, auth, readme, and package merge by field. GraphQL-only source settings live on
 * the Project's Spec and are rejected in both stored config scopes.
 */
export interface ProjectConfig {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRule | boolean>;
  auth?: AuthenticationConfig;
  cli?: CliBehavior;
  mcp?: McpBehavior;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** Response shape for ProjectConfig. */
export interface ProjectConfigRead {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleRead | boolean>;
  auth?: AuthenticationConfig;
  cli?: CliBehavior;
  mcp?: McpBehaviorRead;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/**
 * Target-specific generation and delivery overrides. Authentication may only select a Project-owned
 * OAuth application. OAuth server metadata, applications, and identity policy remain Project-owned.
 * Self-hosted MCP access may be overridden for a Target-specific deployment.
 */
export interface TargetConfig {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRule | boolean>;
  auth?: TargetAuthenticationConfig;
  cli?: TargetCliBehavior;
  mcp?: McpBehavior;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** Response shape for TargetConfig. */
export interface TargetConfigRead {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuning;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleRead | boolean>;
  auth?: TargetAuthenticationConfig;
  cli?: TargetCliBehavior;
  mcp?: McpBehaviorRead;
  readme?: ReadmeBehavior;
  package?: PackageBehavior;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** What a GraphQL schema cannot say about itself. Ignored for OpenAPI specs. */
export interface GraphqlSettings {
  /**
   * The URL every request is POSTed to; the generated client's default baseUrl. Defaults to the URL
   * the schema was fetched from. Without either, baseUrl is a required client option.
   * Format: uri
   */
  endpoint?: string;
  /**
   * Named endpoints (sandbox, production). Each becomes a client environment; the first is the
   * default unless endpoint is set.
   */
  environments?: Array<{
    name: string;
    /** Format: uri */
    url: string;
  }>;
  /**
   * How requests authenticate. bearer sends Authorization: Bearer; basic is for key-pair APIs
   * (public key as username, private key as password); basic_api_key sends one API key as the
   * Basic-auth username with an empty password; api_key sends a header named by api_key_header;
   * api_key_or_bearer sends a key in api_key_header (Authorization for a raw key) and also accepts
   * an OAuth access token as Authorization: Bearer; none generates no auth option.
   * Default: "bearer"
   */
  auth?: "bearer"
    | "basic"
    | "basic_api_key"
    | "api_key"
    | "api_key_or_bearer"
    | "none";
  /**
   * Header carrying the key when auth is api_key or api_key_or_bearer. Required for those modes;
   * Typeship does not invent a vendor-specific header name.
   */
  api_key_header?: string;
  /**
   * The API's name; drives the package and client names ("Acme" gives acme and AcmeClient).
   * Defaults to a name derived from the endpoint's host.
   */
  title?: string;
  /**
   * JSON representation of each custom scalar, keyed by GraphQL scalar name. Unmapped scalars
   * generate as the language's untyped JSON value and produce a warning. Unmatched keys warn.
   */
  scalars?: Record<string, "string" | "integer" | "number" | "boolean" | "json">;
  /**
   * Object types that report a failure when an operation's union or interface result resolves to
   * them (errors returned as data). Replaces the default, which is every member whose name ends in
   * Error when the result can also be something else. An empty array treats no result as a failure.
   * Names that are not object types in the schema produce a generation warning.
   */
  error_types?: string[];
  /**
   * Page size a paginated connection call sends as first when the caller passes neither first nor
   * last. Relay servers such as GitHub reject a connection query without one. Ignored for a
   * connection whose first argument has a schema default.
   * Default: 100
   */
  page_size?: number;
}

/** Response shape for GraphqlSettings. */
export interface GraphqlSettingsRead {
  /**
   * The URL every request is POSTed to; the generated client's default baseUrl. Defaults to the URL
   * the schema was fetched from. Without either, baseUrl is a required client option.
   * Format: uri
   */
  endpoint?: string;
  /**
   * Named endpoints (sandbox, production). Each becomes a client environment; the first is the
   * default unless endpoint is set.
   */
  environments?: Array<{
    name: string;
    /** Format: uri */
    url: string;
  }>;
  /**
   * How requests authenticate. bearer sends Authorization: Bearer; basic is for key-pair APIs
   * (public key as username, private key as password); basic_api_key sends one API key as the
   * Basic-auth username with an empty password; api_key sends a header named by api_key_header;
   * api_key_or_bearer sends a key in api_key_header (Authorization for a raw key) and also accepts
   * an OAuth access token as Authorization: Bearer; none generates no auth option.
   * Default: "bearer"
   */
  auth?: ("bearer"
    | "basic"
    | "basic_api_key"
    | "api_key"
    | "api_key_or_bearer"
    | "none") | (string & {});
  /**
   * Header carrying the key when auth is api_key or api_key_or_bearer. Required for those modes;
   * Typeship does not invent a vendor-specific header name.
   */
  api_key_header?: string;
  /**
   * The API's name; drives the package and client names ("Acme" gives acme and AcmeClient).
   * Defaults to a name derived from the endpoint's host.
   */
  title?: string;
  /**
   * JSON representation of each custom scalar, keyed by GraphQL scalar name. Unmapped scalars
   * generate as the language's untyped JSON value and produce a warning. Unmatched keys warn.
   */
  scalars?: Record<string, ("string" | "integer" | "number" | "boolean" | "json") | (string & {})>;
  /**
   * Object types that report a failure when an operation's union or interface result resolves to
   * them (errors returned as data). Replaces the default, which is every member whose name ends in
   * Error when the result can also be something else. An empty array treats no result as a failure.
   * Names that are not object types in the schema produce a generation warning.
   */
  error_types?: string[];
  /**
   * Page size a paginated connection call sends as first when the caller passes neither first nor
   * last. Relay servers such as GitHub reject a connection query without one. Ignored for a
   * connection whose first argument has a schema default.
   * Default: 100
   */
  page_size?: number;
}

/**
 * Retry behavior. Top-level fields adjust every operation; operations maps operationId or "METHOD
 * /path" keys to per-operation overrides.
 */
export interface RetryTuning {
  max_retries?: number;
  /** Replaces the default retryable set (408, 429, 500, 502, 503, 504). */
  statuses?: number[];
  initial_delay_ms?: number;
  max_delay_ms?: number;
  /** Also retry non-idempotent methods (POST/PATCH). */
  retry_non_idempotent?: boolean;
  /** Shorthand for max_retries 0. */
  disabled?: boolean;
  operations?: Record<string, RetryTuning>;
}

export interface PaginationRule {
  /** Default: "cursor" */
  style?: "cursor" | "cursor_from_last_id" | "page" | "offset";
  /** Response field holding the item array. */
  items_field: string;
  cursor_param?: string;
  next_cursor_field?: string;
  has_more_field?: string;
  id_field?: string;
  page_param?: string;
  offset_param?: string;
  limit_param?: string;
}

/** Response shape for PaginationRule. */
export interface PaginationRuleRead {
  /** Default: "cursor" */
  style?: ("cursor" | "cursor_from_last_id" | "page" | "offset") | (string & {});
  /** Response field holding the item array. */
  items_field: string;
  cursor_param?: string;
  next_cursor_field?: string;
  has_more_field?: string;
  id_field?: string;
  page_param?: string;
  offset_param?: string;
  limit_param?: string;
}

/**
 * A Generation moves from queued to running, then completes when its files are saved or fails.
 * Delivery and Draft status are separate.
 */
export const GenerationStatus = {
  QUEUED: "queued",
  RUNNING: "running",
  COMPLETED: "completed",
  FAILED: "failed",
} as const;
export type GenerationStatus = (typeof GenerationStatus)[keyof typeof GenerationStatus];

export const GenerationTrigger = {
  MANUAL: "manual",
  SPEC_CHANGED: "spec_changed",
  CONFIG_CHANGED: "config_changed",
  PREVIEW: "preview",
} as const;
export type GenerationTrigger = (typeof GenerationTrigger)[keyof typeof GenerationTrigger];

export interface Generation {
  id: GenerationId;
  object: "generation";
  project_id: ProjectId;
  spec_revision_id: SpecRevisionId | null;
  status: GenerationStatus;
  trigger: GenerationTrigger;
  target_id: TargetId | null;
  type: GeneratorKind;
  /** Package name; null until known. */
  name: string | null;
  /** Package version; null until known. */
  version: string | null;
  warnings: GenerationWarning[];
  /** Operation coverage; null until generation has finished. */
  coverage: GenerationCoverage | null;
  /** Generated package files. List them with listGenerationFiles. */
  file_count: number;
  errors: DomainError[];
  /**
   * Milliseconds from the start of the run until it completed or failed; null while queued or
   * running.
   */
  runtime_ms: number | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/** Request shape for Generation. */
export interface GenerationWrite {
  id: GenerationId;
  project_id: ProjectId;
  spec_revision_id: SpecRevisionId | null;
  status: GenerationStatus;
  trigger: GenerationTrigger;
  target_id: TargetId | null;
  type: GeneratorKind;
  /** Package name; null until known. */
  name: string | null;
  /** Package version; null until known. */
  version: string | null;
  warnings: GenerationWarning[];
  /** Operation coverage; null until generation has finished. */
  coverage: GenerationCoverage | null;
  /** Generated package files. List them with listGenerationFiles. */
  file_count: number;
  errors: DomainError[];
  /**
   * Milliseconds from the start of the run until it completed or failed; null while queued or
   * running.
   */
  runtime_ms: number | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

/** Response shape for Generation. */
export interface GenerationRead {
  id: GenerationId;
  object: "generation" | (string & {});
  project_id: ProjectId;
  spec_revision_id: SpecRevisionId | null;
  status: GenerationStatus | (string & {});
  trigger: GenerationTrigger | (string & {});
  target_id: TargetId | null;
  type: GeneratorKind | (string & {});
  /** Package name; null until known. */
  name: string | null;
  /** Package version; null until known. */
  version: string | null;
  warnings: GenerationWarning[];
  /** Operation coverage; null until generation has finished. */
  coverage: GenerationCoverageRead | null;
  /** Generated package files. List them with listGenerationFiles. */
  file_count: number;
  errors: DomainErrorRead[];
  /**
   * Milliseconds from the start of the run until it completed or failed; null while queued or
   * running.
   */
  runtime_ms: number | null;
  /** Format: date-time */
  created_at: string;
  /** Format: date-time */
  updated_at: string;
}

export type GenerationResponse = Generation & ResponseMetadata;

/** Request shape for GenerationResponse. */
export type GenerationResponseWrite = GenerationWrite & ResponseMetadata;

/** Response shape for GenerationResponse. */
export type GenerationResponseRead = GenerationRead & ResponseMetadata;

/**
 * One Generation per selected Target. Retrieve each Generation for current status and generated
 * files.
 */
export interface GenerationBatch {
  data: Generation[];
  request_id: RequestId;
}

/** Request shape for GenerationBatch. */
export interface GenerationBatchWrite {
  data: GenerationWrite[];
  request_id: RequestId;
}

/** Response shape for GenerationBatch. */
export interface GenerationBatchRead {
  data: GenerationRead[];
  request_id: RequestId;
}

export interface ApiKey {
  id: string;
  object: "api_key";
  name: string;
  /** Last four characters of the secret; the secret itself is never stored. */
  last4: string;
  /**
   * active: the key authenticates requests. revoked: it no longer does and cannot be restored;
   * create a new key in the Console or with typeship login.
   */
  status: "active" | "revoked";
  /** Format: date-time */
  last_used_at: string | null;
  /** Format: date-time */
  created_at: string;
  /**
   * When the key last changed, such as its revocation.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

/** Response shape for ApiKey. */
export interface ApiKeyRead {
  id: string;
  object: "api_key" | (string & {});
  name: string;
  /** Last four characters of the secret; the secret itself is never stored. */
  last4: string;
  /**
   * active: the key authenticates requests. revoked: it no longer does and cannot be restored;
   * create a new key in the Console or with typeship login.
   */
  status: ("active" | "revoked") | (string & {});
  /** Format: date-time */
  last_used_at: string | null;
  /** Format: date-time */
  created_at: string;
  /**
   * When the key last changed, such as its revocation.
   * Format: date-time
   */
  updated_at: string;
  request_id?: RequestId;
}

export type ApiKeyResponse = ApiKey & ResponseMetadata;

/** Response shape for ApiKeyResponse. */
export type ApiKeyResponseRead = ApiKeyRead & ResponseMetadata;

export interface UrlSpecRevisionSource {
  type: "url";
  url: {
    /** Format: uri */
    url: string;
  };
}

export interface RepositorySpecRevisionSource {
  type: "repository";
  repository: {
    provider: RepositoryProvider;
    identifier: RepositoryIdentifier;
    /** Repository-relative Spec entrypoint path. */
    path: string;
    /** Git ref resolved for this revision, when recorded. */
    ref?: string | null;
    /** Exact Git commit consumed, when recorded. */
    commit_sha?: string | null;
  };
}

/** Response shape for RepositorySpecRevisionSource. */
export interface RepositorySpecRevisionSourceRead {
  type: "repository";
  repository: {
    provider: RepositoryProvider | (string & {});
    identifier: RepositoryIdentifier;
    /** Repository-relative Spec entrypoint path. */
    path: string;
    /** Git ref resolved for this revision, when recorded. */
    ref?: string | null;
    /** Exact Git commit consumed, when recorded. */
    commit_sha?: string | null;
  };
}

export type SpecRevisionSource = UrlSpecRevisionSource | RepositorySpecRevisionSource;

/** Response shape for SpecRevisionSource. */
export type SpecRevisionSourceRead = UrlSpecRevisionSource
  | RepositorySpecRevisionSourceRead
  | UnknownVariant<"type">;

export interface SpecRevision {
  id: SpecRevisionId;
  object: "spec_revision";
  project_id: ProjectId;
  spec_id: SpecId;
  format: "openapi" | "graphql";
  file_count: number;
  /** SHA-256 digest of every source file path, digest, and size in the resolved graph. */
  sha256: string;
  /** Total bytes across all source files. */
  size_bytes: number;
  /** Origin recorded when this immutable revision was created. */
  source: SpecRevisionSource | null;
  /** Present on retrieve; list responses omit it. */
  diagnostic_summary?: DiagnosticSummary;
  /** Present only with include=diagnostics. Ordered by severity, then rule identifier. */
  diagnostics?: Diagnostic[];
  /**
   * Present only with include=diagnostics. Coded misses or conflicts from applying the Spec's
   * patches to this revision.
   */
  patch_diagnostics?: DiagnosticWarning[];
  /** Format: date-time */
  created_at: string;
  request_id?: RequestId;
}

/** Response shape for SpecRevision. */
export interface SpecRevisionRead {
  id: SpecRevisionId;
  object: "spec_revision" | (string & {});
  project_id: ProjectId;
  spec_id: SpecId;
  format: ("openapi" | "graphql") | (string & {});
  file_count: number;
  /** SHA-256 digest of every source file path, digest, and size in the resolved graph. */
  sha256: string;
  /** Total bytes across all source files. */
  size_bytes: number;
  /** Origin recorded when this immutable revision was created. */
  source: SpecRevisionSourceRead | null;
  /** Present on retrieve; list responses omit it. */
  diagnostic_summary?: DiagnosticSummaryRead;
  /** Present only with include=diagnostics. Ordered by severity, then rule identifier. */
  diagnostics?: DiagnosticRead[];
  /**
   * Present only with include=diagnostics. Coded misses or conflicts from applying the Spec's
   * patches to this revision.
   */
  patch_diagnostics?: DiagnosticWarningRead[];
  /** Format: date-time */
  created_at: string;
  request_id?: RequestId;
}

export type SpecRevisionResponse = SpecRevision & ResponseMetadata;

/** Response shape for SpecRevisionResponse. */
export type SpecRevisionResponseRead = SpecRevisionRead & ResponseMetadata;

export interface ProjectList {
  object: ListObject;
  data: Project[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Request shape for ProjectList. */
export interface ProjectListWrite {
  object: ListObject;
  data: ProjectWrite[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for ProjectList. */
export interface ProjectListRead {
  object: ListObject;
  data: ProjectRead[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

export interface GenerationList {
  object: ListObject;
  data: Generation[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Request shape for GenerationList. */
export interface GenerationListWrite {
  object: ListObject;
  data: GenerationWrite[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for GenerationList. */
export interface GenerationListRead {
  object: ListObject;
  data: GenerationRead[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

export interface SpecRevisionList {
  object: ListObject;
  data: SpecRevision[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for SpecRevisionList. */
export interface SpecRevisionListRead {
  object: ListObject;
  data: SpecRevisionRead[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

export interface ApiKeyList {
  object: ListObject;
  data: ApiKey[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for ApiKeyList. */
export interface ApiKeyListRead {
  object: ListObject;
  data: ApiKeyRead[];
  /** Whether another page is available after this one. */
  has_more: boolean;
  /** Pass this value as cursor to retrieve the next page; null on the last page. */
  next_cursor: string | null;
  request_id: RequestId;
}

export interface DeletedProject {
  id: ProjectId;
  object: "project";
  deleted: true;
  request_id: RequestId;
}

/** Response shape for DeletedProject. */
export interface DeletedProjectRead {
  id: ProjectId;
  object: "project" | (string & {});
  deleted: true;
  request_id: RequestId;
}

export interface DeletedTarget {
  id: TargetId;
  object: "target";
  deleted: true;
  request_id: RequestId;
}

/** Response shape for DeletedTarget. */
export interface DeletedTargetRead {
  id: TargetId;
  object: "target" | (string & {});
  deleted: true;
  request_id: RequestId;
}

/**
 * Who can resolve the error. request: change the request. auth: fix the credential or its grant.
 * idempotency: change or wait on the Idempotency-Key. rate_limit: wait before retrying.
 * organization: the organization's plan must change. source: a system you own failed, such as the
 * Spec URL, repository, or package registry. api: Typeship failed.
 */
export const ErrorType = {
  REQUEST: "request",
  AUTH: "auth",
  IDEMPOTENCY: "idempotency",
  RATE_LIMIT: "rate_limit",
  ORGANIZATION: "organization",
  SOURCE: "source",
  API: "api",
} as const;
export type ErrorType = (typeof ErrorType)[keyof typeof ErrorType];

/** Stable programmatic identifier. Do not branch on message. */
export const ErrorCode = {
  INPUT_INVALID: "input_invalid",
  INPUT_MISSING: "input_missing",
  INPUT_TYPE_INVALID: "input_type_invalid",
  INPUT_FORMAT_INVALID: "input_format_invalid",
  INPUT_TOO_LONG: "input_too_long",
  INPUT_TOO_SHORT: "input_too_short",
  INPUT_DUPLICATE: "input_duplicate",
  INPUT_UNKNOWN: "input_unknown",
  QUERY_PARAM_INVALID: "query_param_invalid",
  CURSOR_INVALID: "cursor_invalid",
  METHOD_NOT_ALLOWED: "method_not_allowed",
  RESOURCE_NOT_FOUND: "resource_not_found",
  IDEMPOTENCY_KEY_INVALID: "idempotency_key_invalid",
  IDEMPOTENCY_KEY_REUSED: "idempotency_key_reused",
  IDEMPOTENCY_KEY_IN_USE: "idempotency_key_in_use",
  AUTH_REQUIRED: "auth_required",
  API_KEY_INVALID: "api_key_invalid",
  TOKEN_INVALID: "token_invalid",
  ORGANIZATION_REQUIRED: "organization_required",
  INSUFFICIENT_SCOPE: "insufficient_scope",
  ROLE_INSUFFICIENT: "role_insufficient",
  RATE_LIMIT_EXCEEDED: "rate_limit_exceeded",
  FEATURE_NOT_AVAILABLE: "feature_not_available",
  QUOTA_EXCEEDED: "quota_exceeded",
  SPEC_INVALID: "spec_invalid",
  SPEC_TOO_LARGE: "spec_too_large",
  SPEC_UNREACHABLE: "spec_unreachable",
  REPOSITORY_PROVIDER_UNSUPPORTED: "repository_provider_unsupported",
  REPOSITORY_DISCONNECTED: "repository_disconnected",
  REPOSITORY_UNAVAILABLE: "repository_unavailable",
  TARGET_BUSY: "target_busy",
  TARGETS_INACTIVE: "targets_inactive",
  NO_DRAFT: "no_draft",
  DRAFT_MERGED: "draft_merged",
  RESOURCE_CHANGED: "resource_changed",
  PRECONDITION_FAILED: "precondition_failed",
  VERSION_INVALID: "version_invalid",
  VERSION_OCCUPIED: "version_occupied",
  VERSION_TOO_LOW: "version_too_low",
  TARGET_ALREADY_RELEASED: "target_already_released",
  ADOPTION_UNVERIFIED: "adoption_unverified",
  PUBLICATION_DISABLED: "publication_disabled",
  PUBLICATION_NOT_RETRYABLE: "publication_not_retryable",
  PUBLICATION_RECOVERY_UNAVAILABLE: "publication_recovery_unavailable",
  PUBLICATION_FAILED: "publication_failed",
  DELIVERY_CONFLICT: "delivery_conflict",
  DELIVERY_EXISTS: "delivery_exists",
  RESOURCE_HAS_DEPENDENCIES: "resource_has_dependencies",
  CUSTOMIZATION_CONFLICT: "customization_conflict",
  CHECKS_FAILED: "checks_failed",
  DRAFT_TITLE_INVALID: "draft_title_invalid",
  HISTORY_RECOVERY_REQUIRED: "history_recovery_required",
  CHECKS_UNAVAILABLE: "checks_unavailable",
  REGENERATION_FAILED: "regeneration_failed",
  FOLLOW_UP_FAILED: "follow_up_failed",
  API_ERROR: "api_error",
} as const;
export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode];

export interface ErrorDetail {
  type: ErrorType;
  code: ErrorCode;
  phase?: FailurePhase;
  /** The affected Target when an operation reports failures for multiple Targets. */
  target_id?: TargetId;
  /**
   * JSON Pointer to the invalid field within the request part named by in. When in is omitted, the
   * pointer refers to the request body. Header pointers use lowercase header names, such as
   * /idempotency-key.
   */
  field?: string;
  /**
   * Request part containing field. Query-parameter errors use query; header errors use header. Body
   * errors use body or omit in.
   */
  in?: "body" | "query" | "header";
  /** Human-readable explanation. Its wording may change. */
  message: string;
  /**
   * Whether another attempt can succeed without correcting the inputs. For a recorded failure,
   * start generation or publishing again; retrieving the resource or replaying an idempotency key
   * does not start another attempt.
   */
  retryable: boolean;
  /** Stable, concise recovery instruction suitable for a person or agent. */
  suggested_action: string;
  /**
   * Documentation for this class of error.
   * Format: uri
   */
  docs_url: string;
}

/** Response shape for ErrorDetail. */
export interface ErrorDetailRead {
  type: ErrorType | (string & {});
  code: ErrorCode | (string & {});
  phase?: FailurePhase | (string & {});
  /** The affected Target when an operation reports failures for multiple Targets. */
  target_id?: TargetId;
  /**
   * JSON Pointer to the invalid field within the request part named by in. When in is omitted, the
   * pointer refers to the request body. Header pointers use lowercase header names, such as
   * /idempotency-key.
   */
  field?: string;
  /**
   * Request part containing field. Query-parameter errors use query; header errors use header. Body
   * errors use body or omit in.
   */
  in?: ("body" | "query" | "header") | (string & {});
  /** Human-readable explanation. Its wording may change. */
  message: string;
  /**
   * Whether another attempt can succeed without correcting the inputs. For a recorded failure,
   * start generation or publishing again; retrieving the resource or replaying an idempotency key
   * does not start another attempt.
   */
  retryable: boolean;
  /** Stable, concise recovery instruction suitable for a person or agent. */
  suggested_action: string;
  /**
   * Documentation for this class of error.
   * Format: uri
   */
  docs_url: string;
}

export interface RepositoryReferenceResponse {
  provider: RepositoryProvider;
  identifier: RepositoryIdentifier;
}

/** Response shape for RepositoryReferenceResponse. */
export interface RepositoryReferenceResponseRead {
  provider: RepositoryProvider | (string & {});
  identifier: RepositoryIdentifier;
}

/**
 * A fix applied to the resolved Spec before generation. Paths are JSON
 * Pointers into the document. A patch whose target no longer exists is
 * skipped and reported as a warning on the generation, never silently.
 */
export interface SpecPatchResponse {
  op: "set" | "append" | "remove" | "rename";
  /**
   * JSON-Pointer-style path. Pattern segments enable bulk fixes:
   * * (any child), ** (any depth), [key=value] (filter), e.g.
   * /paths/**\/parameters/[name=account_id]/schema/type. Renaming a
   * schema under /components/schemas also rewrites its $refs.
   */
  path: string;
  /** set only; the replacement value. */
  value?: unknown;
  /** rename only; the new key name. */
  to?: string | null;
  reason?: string | null;
}

/** Response shape for SpecPatchResponse. */
export interface SpecPatchResponseRead {
  op: ("set" | "append" | "remove" | "rename") | (string & {});
  /**
   * JSON-Pointer-style path. Pattern segments enable bulk fixes:
   * * (any child), ** (any depth), [key=value] (filter), e.g.
   * /paths/**\/parameters/[name=account_id]/schema/type. Renaming a
   * schema under /components/schemas also rewrites its $refs.
   */
  path: string;
  /** set only; the replacement value. */
  value?: unknown;
  /** rename only; the new key name. */
  to?: string | null;
  reason?: string | null;
}

export interface DiagnosticSuppressionResponse {
  rule_id: string;
  /** Exact schema coordinate. Omit only to suppress every occurrence of the rule. */
  path?: string;
  /** The reviewed product decision behind this exception. */
  reason: string;
}

/**
 * Source pull-request enforcement threshold, new-versus-complete baseline, and explicitly reviewed
 * rule or location exceptions.
 */
export interface DiagnosticPolicyResponse {
  /**
   * Severity threshold that fails the API change review check.
   * Default: "error"
   */
  fail_on: "never" | "error" | "warning";
  /**
   * Enforce only occurrences introduced by the proposed source change.
   * Default: true
   */
  only_new: boolean;
  /** Default: [] */
  suppressions: DiagnosticSuppressionResponse[];
}

/** Response shape for DiagnosticPolicyResponse. */
export interface DiagnosticPolicyResponseRead {
  /**
   * Severity threshold that fails the API change review check.
   * Default: "error"
   */
  fail_on: ("never" | "error" | "warning") | (string & {});
  /**
   * Enforce only occurrences introduced by the proposed source change.
   * Default: true
   */
  only_new: boolean;
  /** Default: [] */
  suppressions: DiagnosticSuppressionResponse[];
}

/**
 * Required checks run against the code in the Draft. Generated checks and customer commands share
 * one reproducible workflow; repository_required names existing repository checks. Supplying checks
 * replaces all settings. Omitted generated restores build, package, and public_entrypoint; omitted
 * repository_required and customer restore empty lists. An empty object restores these defaults. An
 * empty array clears the corresponding list.
 */
export interface TargetChecksResponse {
  /** Default: ["build","package","public_entrypoint"] */
  generated?: Array<"build" | "package" | "public_entrypoint">;
  repository_required?: string[];
  customer?: Array<{
    name: string;
    command: string;
  }>;
}

/** Response shape for TargetChecksResponse. */
export interface TargetChecksResponseRead {
  /** Default: ["build","package","public_entrypoint"] */
  generated?: Array<("build" | "package" | "public_entrypoint") | (string & {})>;
  repository_required?: string[];
  customer?: Array<{
    name: string;
    command: string;
  }>;
}

/**
 * Authorization-server metadata used by generated OAuth flows. Secrets and runtime credentials are
 * never accepted here.
 */
export interface OAuthServerResponse {
  /**
   * Exact authorization-server issuer, including any tenant path.
   * Format: uri
   */
  issuer?: string | null;
  /**
   * Exact metadata URL when it cannot be derived from the issuer.
   * Format: uri
   */
  discovery_url?: string | null;
  /**
   * Authorization endpoint override.
   * Format: uri
   */
  authorization_url?: string | null;
  /**
   * Token endpoint override.
   * Format: uri
   */
  token_url?: string | null;
  /**
   * Device-authorization endpoint override.
   * Format: uri
   */
  device_authorization_url?: string | null;
  /** Default scopes requested during login. */
  scopes?: string[] | null;
  /** Default audience included in authorization and token requests. */
  audience?: string | null;
  /**
   * Protected API resource included in authorization and token requests.
   * Format: uri
   */
  resource?: string | null;
}

/**
 * OAuth application available to generated products. Public clients support interactive login;
 * confidential clients support runtime-supplied machine credentials. Client secrets are never
 * stored.
 */
export interface OAuthApplicationResponse {
  /** OAuth client identifier. */
  client_id: string;
  /** Interactive login method. Browser login uses Authorization Code with PKCE. */
  login_method?: "browser" | "device" | null;
  /** How a runtime-supplied client secret is sent for machine grants. */
  client_auth_method?: "post" | "basic" | null;
  /**
   * Loopback callback URL for browser login.
   * Format: uri
   */
  redirect_uri?: string | null;
  /** Provider parameter used to request an organization during browser login. */
  organization_parameter?: "organization" | "organization_id" | null;
}

/** Response shape for OAuthApplicationResponse. */
export interface OAuthApplicationResponseRead {
  /** OAuth client identifier. */
  client_id: string;
  /** Interactive login method. Browser login uses Authorization Code with PKCE. */
  login_method?: ("browser" | "device" | null) | (string & {}) | null;
  /** How a runtime-supplied client secret is sent for machine grants. */
  client_auth_method?: ("post" | "basic" | null) | (string & {}) | null;
  /**
   * Loopback callback URL for browser login.
   * Format: uri
   */
  redirect_uri?: string | null;
  /** Provider parameter used to request an organization during browser login. */
  organization_parameter?: ("organization" | "organization_id" | null) | (string & {}) | null;
}

/**
 * Authenticated identity read used to verify a login before it is saved. Operation is auto-detected
 * when omitted or null. At least one of subject_field, account_field, or organization_field must be
 * a non-null JSON Pointer. Null clears an individual mapping while another remains. Set
 * identity_verification itself to null to remove the whole policy.
 */
export type IdentityVerificationResponse = {
  /** resource.method of a safe identity read with no required arguments. */
  operation?: string | null;
  /** JSON Pointer to the stable caller ID in the identity response. */
  subject_field?: string | null;
  /** JSON Pointer to the customer account ID. */
  account_field?: string | null;
  /** JSON Pointer to the customer organization ID. */
  organization_field?: string | null;
} & ({
  subject_field: string;
}
  | {
      account_field: string;
    }
  | {
      organization_field: string;
    });

/** OAuth application and request-value overrides for one named API environment. */
export interface AuthenticationEnvironmentResponse {
  oauth_application?: string | null;
  scopes?: string[] | null;
  audience?: string | null;
  /** Format: uri */
  resource?: string | null;
}

/**
 * Public authentication defaults for generated clients and tools. Stored Projects own the OAuth
 * server, application catalog, and identity policy; one-shot generation accepts the same shape for
 * one run. Runtime credentials and client secrets are never accepted.
 */
export interface AuthenticationConfigResponse {
  oauth_server?: OAuthServerResponse | null;
  /** OAuth applications keyed by a stable name. */
  oauth_applications?: Record<string, OAuthApplicationResponse> | null;
  /** Default OAuth application used by generated products. */
  oauth_application?: string | null;
  identity_verification?: IdentityVerificationResponse | null;
  /**
   * Base URL of a custom browser-approval backend implementing the start, status, and revoke
   * contract. Used only when OAuth is not configured.
   * Format: uri
   */
  approval_url?: string | null;
  /** Authentication selections keyed by generated API environment name. */
  environments?: Record<string, AuthenticationEnvironmentResponse> | null;
  /**
   * Environment variables the generated CLI, MCP server, and SDK environment fallbacks read, keyed
   * by security scheme name. A string names the token or key variable; a Basic scheme takes {
   * username, password }. Wins over the scheme's x-typeship-env extension. Without either, names
   * derive from the package and scheme.
   */
  credential_variables?: Record<string, string | {
    username: string;
    password: string;
  }>
    | null;
  /**
   * Whether a parameter carries the operation's credential, keyed by operationId, "METHOD /path",
   * or "*" for every operation, then by the parameter's wire name. true leaves the parameter out of
   * generated signatures, CLI flags, and MCP tool input, because the configured credential already
   * reaches the API; false keeps it. Wins over the parameter's x-typeship-credential extension and
   * the generator's inference.
   */
  credential_parameters?: Record<string, Record<string, boolean>> | null;
}

export interface TargetAuthenticationEnvironmentResponse {
  oauth_application?: string | null;
}

/**
 * Selects a Project OAuth application for one Target. OAuth server metadata, applications, and
 * identity policy remain Project-owned.
 */
export interface TargetAuthenticationConfigResponse {
  /** Project OAuth application to use. Omit to inherit the Project default. */
  oauth_application?: string | null;
  /** Project OAuth application selections keyed by API environment. */
  environments?: Record<string, TargetAuthenticationEnvironmentResponse> | null;
}

/** How the generated CLI behaves. Part of Config. */
export interface CliBehaviorResponse {
  /** Command users run, independent of how the CLI is distributed. */
  command_name?: string | null;
  /**
   * Opt in to a once-a-day registry check that prints an upgrade hint. Off by default; generated
   * code phones nobody unless this is enabled.
   */
  update_notice?: boolean;
  /**
   * Public HTTP(S) URL read by the optional changelog command in generated CLIs. Supports UTF-8
   * Markdown, plain text, and static HTML; embedded credentials are not allowed. Omit or clear to
   * disable, then regenerate.
   */
  changelog_url?: string | null;
  /**
   * Where the generated CLI's feedback command sends users. GitHub issues/new URLs get a prefilled
   * title and environment details.
   */
  support_url?: string | null;
  /**
   * Hosted MCP endpoint installed by the generated CLI instead of launching the package's local
   * stdio server.
   */
  mcp_url?: string | null;
  /** GitHub owner/name of the skills package the generated CLI offers to install during init. */
  skills_repo?: string | null;
}

/** How the generated CLI behaves. Part of Config. */
export interface TargetCliBehaviorResponse {
  /** Command users run, independent of how the CLI is distributed. */
  command_name?: string | null;
  /**
   * Opt in to a once-a-day registry check that prints an upgrade hint. Off by default; generated
   * code phones nobody unless this is enabled.
   */
  update_notice?: boolean;
  /**
   * Public HTTP(S) URL read by the optional changelog command in generated CLIs. Supports UTF-8
   * Markdown, plain text, and static HTML; embedded credentials are not allowed. Omit or clear to
   * disable, then regenerate.
   */
  changelog_url?: string | null;
  /**
   * Where the generated CLI's feedback command sends users. GitHub issues/new URLs get a prefilled
   * title and environment details.
   */
  support_url?: string | null;
  /**
   * Hosted MCP endpoint installed by the generated CLI instead of launching the package's local
   * stdio server.
   */
  mcp_url?: string | null;
  /** GitHub owner/name of the skills package the generated CLI offers to install during init. */
  skills_repo?: string | null;
  /**
   * Enable webhook relay sessions for this CLI Target. Requires Pro. Turning it off prevents new
   * sessions.
   */
  relay?: boolean;
  /**
   * Also generate unit tests for the helper code a CLI shares, such as raw API path checks, saved
   * credentials, and MCP client configuration. Applies to cli Targets. Off by default; tests for
   * the generated commands are always included.
   */
  unit_tests?: boolean;
}

/** How generated MCP servers and the Typeship-hosted endpoint behave. Part of Config. */
export interface McpBehaviorResponse {
  /** Stable official MCP registry name, independent of the server runtime. */
  registry_name?: string | null;
  /**
   * Authorization for callers connecting to a generated MCP server deployed over HTTP. The hosting
   * application resolves upstream API credentials separately at runtime. This setting does not
   * apply to the Typeship-hosted endpoint.
   */
  access?: {
    /**
     * Exact issuer allowed to sign MCP connection tokens.
     * Format: uri
     */
    issuer: string;
    /**
     * Canonical public URL of the self-hosted MCP endpoint that connection tokens must target.
     * Format: uri
     */
    resource: string;
    /**
     * Public signing-key endpoint. Omit to discover it from the issuer.
     * Format: uri
     */
    jwks_url?: string;
    /** Minimum scopes required to connect to the self-hosted MCP server. */
    scopes?: string[];
  };
  /**
   * MCP tool shape. meta collapses per-operation tools into search_docs, read_docs, and execute so
   * large APIs don't flood an agent's context window. Auto considers the serialized tool schemas,
   * switching near 10k tokens or above 100 operations.
   */
  tool_mode?: "auto" | "operations" | "meta";
  /**
   * Guidance appended to the MCP server's instructions, which agents read once when they connect
   * (server/discover): what to call first, conventions the spec does not state, what not to do.
   * Carried by the package's server and the hosted endpoint alike.
   */
  instructions?: string | null;
  /**
   * Hand-written MCP tool descriptions keyed by operationId or "METHOD /path". Each replaces the
   * text typeship derives for that operation (summary, first sentence, method and path, deprecation
   * and auth notes). For flows the spec cannot describe, such as a multi-step upload. Keys that
   * match no operation are reported as generation warnings.
   */
  tool_descriptions?: Record<string, string>;
  /**
   * Exact name-or-ID resolver overrides keyed first by the target operationId or "METHOD /path",
   * then by its wire argument name. A resolver names one read collection operation plus 1-4 item
   * fields to match case-insensitively; false opts that argument out of strict inference.
   */
  reference_resolvers?: Record<string, Record<string, false
    | {
        /** OperationId, "METHOD /path", MCP tool name, or dotted resource.method of the list operation. */
        via: string;
        /** Item fields compared exactly and case-insensitively, such as name, slug, key, or email. */
        match: string[];
        /** Item field substituted into the requested argument. Defaults to id. */
        id?: string;
      }>>;
}

/** Response shape for McpBehaviorResponse. */
export interface McpBehaviorResponseRead {
  /** Stable official MCP registry name, independent of the server runtime. */
  registry_name?: string | null;
  /**
   * Authorization for callers connecting to a generated MCP server deployed over HTTP. The hosting
   * application resolves upstream API credentials separately at runtime. This setting does not
   * apply to the Typeship-hosted endpoint.
   */
  access?: {
    /**
     * Exact issuer allowed to sign MCP connection tokens.
     * Format: uri
     */
    issuer: string;
    /**
     * Canonical public URL of the self-hosted MCP endpoint that connection tokens must target.
     * Format: uri
     */
    resource: string;
    /**
     * Public signing-key endpoint. Omit to discover it from the issuer.
     * Format: uri
     */
    jwks_url?: string;
    /** Minimum scopes required to connect to the self-hosted MCP server. */
    scopes?: string[];
  };
  /**
   * MCP tool shape. meta collapses per-operation tools into search_docs, read_docs, and execute so
   * large APIs don't flood an agent's context window. Auto considers the serialized tool schemas,
   * switching near 10k tokens or above 100 operations.
   */
  tool_mode?: ("auto" | "operations" | "meta") | (string & {});
  /**
   * Guidance appended to the MCP server's instructions, which agents read once when they connect
   * (server/discover): what to call first, conventions the spec does not state, what not to do.
   * Carried by the package's server and the hosted endpoint alike.
   */
  instructions?: string | null;
  /**
   * Hand-written MCP tool descriptions keyed by operationId or "METHOD /path". Each replaces the
   * text typeship derives for that operation (summary, first sentence, method and path, deprecation
   * and auth notes). For flows the spec cannot describe, such as a multi-step upload. Keys that
   * match no operation are reported as generation warnings.
   */
  tool_descriptions?: Record<string, string>;
  /**
   * Exact name-or-ID resolver overrides keyed first by the target operationId or "METHOD /path",
   * then by its wire argument name. A resolver names one read collection operation plus 1-4 item
   * fields to match case-insensitively; false opts that argument out of strict inference.
   */
  reference_resolvers?: Record<string, Record<string, false | (string & {})
    | {
        /** OperationId, "METHOD /path", MCP tool name, or dotted resource.method of the list operation. */
        via: string;
        /** Item fields compared exactly and case-insensitively, such as name, slug, key, or email. */
        match: string[];
        /** Item field substituted into the requested argument. Defaults to id. */
        id?: string;
      }>>;
}

/** Generated README behavior. Part of Config. */
export interface ReadmeBehaviorResponse {
  /**
   * operationId or "METHOD /path" to feature as the README's first API call. It must be present in
   * the generated package and callable with no required input beyond path placeholders. Missing or
   * unsuitable choices produce a warning and use the automatic example.
   */
  quickstart_operation?: string | null;
}

/**
 * Published-package metadata the API spec does not own. Repository is derived from each
 * destination.
 */
export interface PackageBehaviorResponse {
  /**
   * The API's name as generated READMEs, AGENTS.md, package descriptions, and help text show it,
   * such as "Parcel" for a Spec titled "Parcel - Public API". Display only: package, client, and
   * command names still come from the Spec. Defaults to the Spec title with common noise removed
   * ("Parcel - API" shows as Parcel).
   */
  title?: string | null;
  /** Homepage written into registry metadata. */
  homepage?: string | null;
  /** SPDX identifier written into registry metadata. Defaults to info.license. */
  license?: string | null;
  /**
   * Exact LICENSE file contents. Supply this for licences the engine does not build in; MIT is
   * built in when copyright is also set.
   */
  license_text?: string | null;
  /** Copyright line used in generated license files. */
  copyright?: string | null;
  /** Go identifier when the destination repository name is unsuitable. */
  go_package_name?: string | null;
}

/**
 * Shared generated-client and tooling behavior for a stored Project. Every Target inherits these
 * defaults. Target.config is merged over them for one Target; top-level values replace defaults
 * while cli, mcp, auth, readme, and package merge by field. GraphQL-only source settings live on
 * the Project's Spec and are rejected in both stored config scopes.
 */
export interface ProjectConfigResponse {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuningResponse;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleResponse | boolean>;
  auth?: AuthenticationConfigResponse;
  cli?: CliBehaviorResponse;
  mcp?: McpBehaviorResponse;
  readme?: ReadmeBehaviorResponse;
  package?: PackageBehaviorResponse;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** Response shape for ProjectConfigResponse. */
export interface ProjectConfigResponseRead {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuningResponse;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleResponseRead | boolean>;
  auth?: AuthenticationConfigResponse;
  cli?: CliBehaviorResponse;
  mcp?: McpBehaviorResponseRead;
  readme?: ReadmeBehaviorResponse;
  package?: PackageBehaviorResponse;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/**
 * Target-specific generation and delivery overrides. Authentication may only select a Project-owned
 * OAuth application. OAuth server metadata, applications, and identity policy remain Project-owned.
 * Self-hosted MCP access may be overridden for a Target-specific deployment.
 */
export interface TargetConfigResponse {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuningResponse;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleResponse | boolean>;
  auth?: TargetAuthenticationConfigResponse;
  cli?: TargetCliBehaviorResponse;
  mcp?: McpBehaviorResponse;
  readme?: ReadmeBehaviorResponse;
  package?: PackageBehaviorResponse;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** Response shape for TargetConfigResponse. */
export interface TargetConfigResponseRead {
  /**
   * Wire names of query/header parameters that become settable once on the generated client and
   * auto-apply to every operation that accepts them; per-call values win. Names that match nothing
   * are reported as generation warnings.
   */
  globals?: string[];
  /**
   * Generate only matching operations: tag names, or path globs such as `/zones/**` (`*` is one
   * path segment, `**` any number), optionally after an HTTP method (`DELETE /zones/*`). Applied
   * before the Spec size limit, with components nothing references any more removed, so a one-shot
   * run can generate part of a Spec up to 64 MB. Selectors that match nothing are reported as
   * generation warnings.
   */
  include?: string[];
  /** Leave out matching operations (tag names or path globs, as for `include`). Wins over `include`. */
  exclude?: string[];
  retries?: RetryTuningResponse;
  /**
   * Per-operation pagination control, keyed by operationId or "METHOD /path". Unmatched keys are
   * reported as generation warnings.
   */
  pagination?: Record<string, PaginationRuleResponseRead | boolean>;
  auth?: TargetAuthenticationConfigResponse;
  cli?: TargetCliBehaviorResponse;
  mcp?: McpBehaviorResponseRead;
  readme?: ReadmeBehaviorResponse;
  package?: PackageBehaviorResponse;
  /**
   * The API's documentation site. Read through its llms.txt by the generated CLI's docs command,
   * the MCP server's docs tools, and the package's AGENTS.md. Defaults to the Spec's externalDocs
   * URL.
   * Format: uri
   */
  docs_url?: string | null;
  /**
   * Exact llms.txt URL when the documentation site does not publish it at docs_url + /llms.txt.
   * Format: uri
   */
  docs_index_url?: string | null;
}

/** What a GraphQL schema cannot say about itself. Ignored for OpenAPI specs. */
export interface GraphqlSettingsResponse {
  /**
   * The URL every request is POSTed to; the generated client's default baseUrl. Defaults to the URL
   * the schema was fetched from. Without either, baseUrl is a required client option.
   * Format: uri
   */
  endpoint?: string;
  /**
   * Named endpoints (sandbox, production). Each becomes a client environment; the first is the
   * default unless endpoint is set.
   */
  environments?: Array<{
    name: string;
    /** Format: uri */
    url: string;
  }>;
  /**
   * How requests authenticate. bearer sends Authorization: Bearer; basic is for key-pair APIs
   * (public key as username, private key as password); basic_api_key sends one API key as the
   * Basic-auth username with an empty password; api_key sends a header named by api_key_header;
   * api_key_or_bearer sends a key in api_key_header (Authorization for a raw key) and also accepts
   * an OAuth access token as Authorization: Bearer; none generates no auth option.
   * Default: "bearer"
   */
  auth?: "bearer"
    | "basic"
    | "basic_api_key"
    | "api_key"
    | "api_key_or_bearer"
    | "none";
  /**
   * Header carrying the key when auth is api_key or api_key_or_bearer. Required for those modes;
   * Typeship does not invent a vendor-specific header name.
   */
  api_key_header?: string;
  /**
   * The API's name; drives the package and client names ("Acme" gives acme and AcmeClient).
   * Defaults to a name derived from the endpoint's host.
   */
  title?: string;
  /**
   * JSON representation of each custom scalar, keyed by GraphQL scalar name. Unmapped scalars
   * generate as the language's untyped JSON value and produce a warning. Unmatched keys warn.
   */
  scalars?: Record<string, "string" | "integer" | "number" | "boolean" | "json">;
  /**
   * Object types that report a failure when an operation's union or interface result resolves to
   * them (errors returned as data). Replaces the default, which is every member whose name ends in
   * Error when the result can also be something else. An empty array treats no result as a failure.
   * Names that are not object types in the schema produce a generation warning.
   */
  error_types?: string[];
  /**
   * Page size a paginated connection call sends as first when the caller passes neither first nor
   * last. Relay servers such as GitHub reject a connection query without one. Ignored for a
   * connection whose first argument has a schema default.
   * Default: 100
   */
  page_size?: number;
}

/** Response shape for GraphqlSettingsResponse. */
export interface GraphqlSettingsResponseRead {
  /**
   * The URL every request is POSTed to; the generated client's default baseUrl. Defaults to the URL
   * the schema was fetched from. Without either, baseUrl is a required client option.
   * Format: uri
   */
  endpoint?: string;
  /**
   * Named endpoints (sandbox, production). Each becomes a client environment; the first is the
   * default unless endpoint is set.
   */
  environments?: Array<{
    name: string;
    /** Format: uri */
    url: string;
  }>;
  /**
   * How requests authenticate. bearer sends Authorization: Bearer; basic is for key-pair APIs
   * (public key as username, private key as password); basic_api_key sends one API key as the
   * Basic-auth username with an empty password; api_key sends a header named by api_key_header;
   * api_key_or_bearer sends a key in api_key_header (Authorization for a raw key) and also accepts
   * an OAuth access token as Authorization: Bearer; none generates no auth option.
   * Default: "bearer"
   */
  auth?: ("bearer"
    | "basic"
    | "basic_api_key"
    | "api_key"
    | "api_key_or_bearer"
    | "none") | (string & {});
  /**
   * Header carrying the key when auth is api_key or api_key_or_bearer. Required for those modes;
   * Typeship does not invent a vendor-specific header name.
   */
  api_key_header?: string;
  /**
   * The API's name; drives the package and client names ("Acme" gives acme and AcmeClient).
   * Defaults to a name derived from the endpoint's host.
   */
  title?: string;
  /**
   * JSON representation of each custom scalar, keyed by GraphQL scalar name. Unmapped scalars
   * generate as the language's untyped JSON value and produce a warning. Unmatched keys warn.
   */
  scalars?: Record<string, ("string" | "integer" | "number" | "boolean" | "json") | (string & {})>;
  /**
   * Object types that report a failure when an operation's union or interface result resolves to
   * them (errors returned as data). Replaces the default, which is every member whose name ends in
   * Error when the result can also be something else. An empty array treats no result as a failure.
   * Names that are not object types in the schema produce a generation warning.
   */
  error_types?: string[];
  /**
   * Page size a paginated connection call sends as first when the caller passes neither first nor
   * last. Relay servers such as GitHub reject a connection query without one. Ignored for a
   * connection whose first argument has a schema default.
   * Default: 100
   */
  page_size?: number;
}

/**
 * Retry behavior. Top-level fields adjust every operation; operations maps operationId or "METHOD
 * /path" keys to per-operation overrides.
 */
export interface RetryTuningResponse {
  max_retries?: number;
  /** Replaces the default retryable set (408, 429, 500, 502, 503, 504). */
  statuses?: number[];
  initial_delay_ms?: number;
  max_delay_ms?: number;
  /** Also retry non-idempotent methods (POST/PATCH). */
  retry_non_idempotent?: boolean;
  /** Shorthand for max_retries 0. */
  disabled?: boolean;
  operations?: Record<string, RetryTuningResponse>;
}

export interface PaginationRuleResponse {
  /** Default: "cursor" */
  style?: "cursor" | "cursor_from_last_id" | "page" | "offset";
  /** Response field holding the item array. */
  items_field: string;
  cursor_param?: string;
  next_cursor_field?: string;
  has_more_field?: string;
  id_field?: string;
  page_param?: string;
  offset_param?: string;
  limit_param?: string;
}

/** Response shape for PaginationRuleResponse. */
export interface PaginationRuleResponseRead {
  /** Default: "cursor" */
  style?: ("cursor" | "cursor_from_last_id" | "page" | "offset") | (string & {});
  /** Response field holding the item array. */
  items_field: string;
  cursor_param?: string;
  next_cursor_field?: string;
  has_more_field?: string;
  id_field?: string;
  page_param?: string;
  offset_param?: string;
  limit_param?: string;
}

export interface ErrorModel {
  errors: ErrorDetail[];
  request_id: RequestId;
}

/** Response shape for ErrorModel. */
export interface ErrorModelRead {
  errors: ErrorDetailRead[];
  request_id: RequestId;
}

/** Git file mode. 100755 is executable; 120000 is a symbolic link whose content is its target. */
export const GitFileMode = {
  V_100644: "100644",
  V_100755: "100755",
  V_120000: "120000",
} as const;
export type GitFileMode = (typeof GitFileMode)[keyof typeof GitFileMode];

/**
 * File IDs for each side of a conflict or history comparison. null means the file is absent on that
 * side.
 */
export interface DraftFileSides {
  base: FileId | null;
  yours: FileId | null;
  generated: FileId | null;
}

export interface DraftFileConflict {
  /**
   * Why the Draft needs a decision. no_common_version: there is no last merged version to compare,
   * such as the first Draft of an adopted package. file_ownership: generated output collides with a
   * file you added. yours_deleted_generated_changed and generated_deleted_yours_changed: one side
   * deleted a file the other changed. overlapping_text: both sides edited the same lines.
   * too_large_to_merge: the file has too many changed lines to merge line by line. binary_changed
   * and file_mode_changed: both sides changed binary content or the file mode.
   */
  type: "no_common_version"
    | "file_ownership"
    | "yours_deleted_generated_changed"
    | "generated_deleted_yours_changed"
    | "overlapping_text"
    | "too_large_to_merge"
    | "binary_changed"
    | "file_mode_changed";
  /**
   * Where the code in this Draft comes from: newly generated files, commits on the default branch,
   * or edits from a Draft whose branch was rebased, reset, or deleted. Typeship may find another
   * conflict after these decisions are applied.
   */
  source: "generation" | "default_branch" | "previous_draft";
  /**
   * Decision saved for this conflict on head_sha; null when none. Typeship continues when every
   * conflict has a decision.
   */
  decision: "yours" | "generated" | "content" | null;
}

/** Response shape for DraftFileConflict. */
export interface DraftFileConflictRead {
  /**
   * Why the Draft needs a decision. no_common_version: there is no last merged version to compare,
   * such as the first Draft of an adopted package. file_ownership: generated output collides with a
   * file you added. yours_deleted_generated_changed and generated_deleted_yours_changed: one side
   * deleted a file the other changed. overlapping_text: both sides edited the same lines.
   * too_large_to_merge: the file has too many changed lines to merge line by line. binary_changed
   * and file_mode_changed: both sides changed binary content or the file mode.
   */
  type: ("no_common_version"
    | "file_ownership"
    | "yours_deleted_generated_changed"
    | "generated_deleted_yours_changed"
    | "overlapping_text"
    | "too_large_to_merge"
    | "binary_changed"
    | "file_mode_changed") | (string & {});
  /**
   * Where the code in this Draft comes from: newly generated files, commits on the default branch,
   * or edits from a Draft whose branch was rebased, reset, or deleted. Typeship may find another
   * conflict after these decisions are applied.
   */
  source: ("generation" | "default_branch" | "previous_draft") | (string & {});
  /**
   * Decision saved for this conflict on head_sha; null when none. Typeship continues when every
   * conflict has a decision.
   */
  decision: ("yours" | "generated" | "content" | null) | (string & {}) | null;
}

export interface DraftFileHistory {
  /**
   * How the rewritten default branch differs from the last merged package; null when only the Draft
   * differs.
   */
  change: "added" | "edited" | "deleted" | "mode_changed" | null;
  /**
   * The Draft branch has a different version than the rewritten default branch. Recovery carries
   * the Draft version forward.
   */
  draft_differs: boolean;
}

/** Response shape for DraftFileHistory. */
export interface DraftFileHistoryRead {
  /**
   * How the rewritten default branch differs from the last merged package; null when only the Draft
   * differs.
   */
  change: ("added" | "edited" | "deleted" | "mode_changed" | null) | (string & {}) | null;
  /**
   * The Draft branch has a different version than the rewritten default branch. Recovery carries
   * the Draft version forward.
   */
  draft_differs: boolean;
}

export interface DraftFile {
  object: "draft_file";
  /** Path relative to the Target's package directory. */
  path: string;
  /** How the Draft differs from the last merged package at this path; null when it does not. */
  customization: "added" | "edited" | "deleted" | "mode_changed" | null;
  conflict: DraftFileConflict | null;
  history: DraftFileHistory | null;
  /** File IDs to read with getFile for a conflict or history file; null for other customized files. */
  sides: DraftFileSides | null;
}

/** Response shape for DraftFile. */
export interface DraftFileRead {
  object: "draft_file" | (string & {});
  /** Path relative to the Target's package directory. */
  path: string;
  /** How the Draft differs from the last merged package at this path; null when it does not. */
  customization: ("added" | "edited" | "deleted" | "mode_changed" | null) | (string & {}) | null;
  conflict: DraftFileConflictRead | null;
  history: DraftFileHistoryRead | null;
  /** File IDs to read with getFile for a conflict or history file; null for other customized files. */
  sides: DraftFileSides | null;
}

export interface DraftFileList {
  object: ListObject;
  data: DraftFile[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

/** Response shape for DraftFileList. */
export interface DraftFileListRead {
  object: ListObject;
  data: DraftFileRead[];
  has_more: boolean;
  next_cursor: string | null;
  request_id: RequestId;
}

export type DraftConflictDecision = {
  path: string;
  /** Keep that version of the file exactly. Keeping an absent version deletes the path. */
  keep: "yours" | "generated";
}
  | {
      path: string;
      keep: "content";
      /** Final file text, stored as UTF-8. An empty string creates an empty file. */
      content: string;
      mode: GitFileMode;
    }
  | {
      path: string;
      keep: "content";
      /** Final file bytes as canonical base64, for binary files. */
      content_base64: string;
      mode: GitFileMode;
    }
  | {
      path: string;
      keep: "content";
      /** Delete this file. */
      content: null;
    };

/** Response shape for DraftConflictDecision. */
export type DraftConflictDecisionRead = {
  path: string;
  /** Keep that version of the file exactly. Keeping an absent version deletes the path. */
  keep: ("yours" | "generated") | (string & {});
}
  | {
      path: string;
      keep: "content" | (string & {});
      /** Final file text, stored as UTF-8. An empty string creates an empty file. */
      content: string;
      mode: GitFileMode | (string & {});
    }
  | {
      path: string;
      keep: "content" | (string & {});
      /** Final file bytes as canonical base64, for binary files. */
      content_base64: string;
      mode: GitFileMode | (string & {});
    }
  | {
      path: string;
      keep: "content" | (string & {});
      /** Delete this file. */
      content: null;
    };

export interface DraftResolveRequest {
  /** The Draft's head_sha. A newer Draft commit returns 409 resource_changed without saving. */
  expected_head_sha: string;
  /**
   * Unique current conflict or customized paths. Choose generated to discard a customization,
   * including a Draft-only file. Final file content must total at most 2 MiB. Decisions apply
   * together or not at all.
   */
  resolutions: DraftConflictDecision[];
}

/** Response shape for DraftResolveRequest. */
export interface DraftResolveRequestRead {
  /** The Draft's head_sha. A newer Draft commit returns 409 resource_changed without saving. */
  expected_head_sha: string;
  /**
   * Unique current conflict or customized paths. Choose generated to discard a customization,
   * including a Draft-only file. Final file content must total at most 2 MiB. Decisions apply
   * together or not at all.
   */
  resolutions: DraftConflictDecisionRead[];
}

export interface GenerateProjectRequest {
  /** Generate only this active Target. Omit to generate all active Targets in the Project. */
  target_id?: TargetId;
}

/** The stage that failed. A delivery failure does not change a completed Generation's status. */
export const FailurePhase = {
  SPEC: "spec",
  GENERATION: "generation",
  DELIVERY: "delivery",
  PUBLICATION: "publication",
} as const;
export type FailurePhase = (typeof FailurePhase)[keyof typeof FailurePhase];

export type DomainError = ErrorDetail & {
  phase: FailurePhase;
};

/** Response shape for DomainError. */
export type DomainErrorRead = ErrorDetailRead & {
  phase: FailurePhase | (string & {});
};

export interface DraftRecoverRequest {
  /** The Draft's history_recovery.default_sha. */
  expected_default_sha: string;
  /** The Draft's history_recovery.head_sha; null when the Draft branch is absent. */
  expected_head_sha: string | null;
}
```
