# Bucket

> Buckets: files by key, private by default, with signed links and an S3-compatible escape hatch.

```python
bucket = noclick.Bucket.from_name("uploads", create_if_missing=True)
bucket.put("invoices/0042.pdf", pdf_bytes, content_type="application/pdf")
link = bucket.signed_url("invoices/0042.pdf", expires_in=3600)
```

A key is a path-like name (`invoices/0042.pdf`); `/` separates folders only
by convention, so listing with `delimiter="/"` shows them as folders.

## Bucket

```typescript
class Bucket
```

A bucket of files by key. Private by default: files are reached through this client or a
`signedUrl`; a public bucket also serves each file at `url(key)`. Its region is a location hint
object storage places it by when it has room there, fixed when it's created.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `name` | `string` |  |
| `public` | `boolean` | Whether every file is readable at `url(key)` without a link. |
| `sizeBytes` | `number | null` |  |
| `objectCount` | `number | null` |  |
| `publicBaseUrl` | `string | null` | Where a public bucket serves its files (null while it's private). |
| `usedBy` | `UsedBy[]` | Who uses it: apps that bind it and agents with it in their tools. |
| `notifications` | `BucketNotification[]` | Where it tells about new files (`notify`). |
| `region` | `RegionName | null` | The region it keeps its data in, fixed when it was created. |
| `userId` | `string | null` |  |
| `createdAt` | `Date | null` |  |
| `consoleUrl` | `string | null` | This bucket in the developer console (null off the hosted API). |

Types:

```typescript
/** An app that binds a database or a bucket, under its `binding` name. */
interface UsedBy {
  kind: string;
  id: string;
  name: string;
  binding: string | null;
}

/** Where a bucket tells about new files (`notify`): the `queue` (its name) and `prefix` (null for every file). */
interface BucketNotification {
  queue: string;
  prefix: string | null;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Bucket.only

```typescript
only(...operations: BucketTool[]): BucketOperations
```

A tool ref to some of its operations, for `tools`: `"objects"`, `"head"`, `"put"` (store a
file from a `url` or from `text`, so the model never handles bytes), `"signed_url"` (a link
that reads a file) and `"remove"`. The bucket itself in `tools` gives all five, as
`{name}__objects` and so on; policy names them `bucket.objects`, `bucket.put`, ... (`bucket.*`).

Parameters:

- `operations` (`BucketTool[]`, required)

Returns: A ref to just those operations, to list in `tools=`; `bind(...)` fixes arguments.

Types:

```typescript
type BucketTool = (typeof BUCKET_TOOLS)[number];
```

### Bucket.create

```typescript
static create(
  name: string,
  options?: BucketCreateOptions & AllowExisting,
): Promise<Bucket>
```

Create a bucket, unique by name per user (a taken name throws `Conflict` with `existingId`, or with
`allowExisting: true` returns the bucket already there, as it is).

Parameters:

- `name` (`string`, required)
- `options.public` (`boolean`, default `false`): Serve every file at a plain URL (`url(key)`); private by default.
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.allowExisting` (`boolean`): A taken name returns the object already there, as it is: nothing about it changes.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The new, empty bucket.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Bucket.fromName

```typescript
static fromName(
  name: string,
  options?: BucketCreateOptions & { createIfMissing?: boolean },
): Bucket
```

A lazy reference to the bucket called `name` for the current (or given) user. With
`createIfMissing` it's created on first use; one that exists is used as it is.

Parameters:

- `name` (`string`, required)
- `options.createIfMissing` (`boolean`)
- `options.public` (`boolean`, default `false`): Serve every file at a plain URL (`url(key)`); private by default.
- `options.region` (`RegionName`): Where it runs or keeps its data (`regions()`); omitted, your account's default region.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A bucket that loads (or is created) the first time it's used. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type RegionName = "us-east" | "us-west" | "eu" | "ap" | "in";
```

### Bucket.fromId

```typescript
static fromId(bucketId: string, options?: CallOptions): Bucket
```

A lazy reference to a bucket by id.

Parameters:

- `bucketId` (`string`, required)
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.

Returns: A bucket that loads the first time you read a field. Nothing is sent yet.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Bucket.get

```typescript
static get(bucketId: string, options?: CallOptions): Promise<Bucket>
```

Load a bucket by id now; an unknown id raises `noclick.NotFound`.

Parameters:

- `bucketId` (`string`, required)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The bucket, loaded: whether it's public, how many files it holds and their total size.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### Bucket.list

```typescript
static list(options?: ReadOptions & { limit?: number }): Promise<Bucket[]>
```

The current user's buckets (or those `userFilter` covers).

Parameters:

- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching bucket, newest first, fetched page by page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Bucket.listPage

```typescript
static listPage(options?: ReadOptions & PageOptions): Promise<Page<Bucket>>
```

One page of buckets; pass `nextCursor` back as `cursor`.

Parameters:

- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.userFilter` (`UserFilter`): Which users the read covers (`user_id` query), instead of acting as one (`user`).
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: A page whose `data` holds the buckets and whose `next_cursor` is `None` on the last page.

Types:

```typescript
/**
 * Which users a read covers: `ALL_USERS`, `NO_USER`, a `User` or your id for one. Sent as the
 * `user_id` query parameter, never as the `NoClick-User` header, so it filters without acting as the user.
 */
type UserFilter = typeof ALL_USERS | typeof NO_USER | UserRef;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;
```

### Bucket.put

```typescript
put(
  key: string,
  data: BucketData,
  options?: BucketPutOptions,
): Promise<BucketObject>
```

Store `data` at `key`, replacing what was there (up to 100 MB; larger files go through a `PUT` signed link).

Parameters:

- `key` (`string`, required)
- `data` (`BucketData`, required)
- `options.contentType` (`string`): Guessed from the key's extension when omitted.
- `options.metadata` (`Record<string, string>`): Up to 2 KB of your own string pairs, returned with the file.

Returns: The file as stored, with its `size` and `etag`.

Types:

```typescript
/** Bytes, text (sent as UTF-8), an `ArrayBuffer` or a `Blob`. */
type BucketData = string | Uint8Array | ArrayBuffer | Blob;
```

### Bucket.read

```typescript
read(key: string): Promise<Uint8Array>
```

The file's bytes; a missing key throws `NotFound`.

Parameters:

- `key` (`string`, required)

Returns: The file's bytes, exactly as stored; decode text yourself.

### Bucket.head

```typescript
head(key: string): Promise<BucketObject>
```

A file's size, type, etag and metadata, without downloading it.

Parameters:

- `key` (`string`, required)

Returns: The file's size, content type, etag, metadata and when it last changed.

### Bucket.objects

```typescript
objects(
  options?: BucketObjectsOptions & { limit?: number },
): Promise<BucketObject[]>
```

The files under `prefix`, in key order (or the first `limit`), fetched page by page.

Parameters:

- `options.delimiter` (`string`): `"/"` rolls keys below the next `/` into one folder entry each.
- `options.limit` (`number`): Return at most this many.
- `options.prefix` (`string`)

Returns: Every matching file (or the first `limit`), fetched page by page.

### Bucket.objectsPage

```typescript
objectsPage(
  options?: BucketObjectsOptions & PageOptions,
): Promise<Page<BucketObject>>
```

One page of `objects`; pass `nextCursor` back as `cursor`.

Parameters:

- `options.delimiter` (`string`): `"/"` rolls keys below the next `/` into one folder entry each.
- `options.cursor` (`string | null`): The `next_cursor` of the page before; omit it for the first page.
- `options.limit` (`number`): Return at most this many.
- `options.prefix` (`string`)

Returns: A page whose `data` holds `BucketObject`s and whose `next_cursor` is `None` on the last page.

### Bucket.remove

```typescript
remove(key: string): Promise<void>
```

Delete the file at `key` (a key that isn't there is fine).

Parameters:

- `key` (`string`, required)

### Bucket.versions

```typescript
versions(key: string): Promise<ObjectVersion[]>
```

What `key` held before each write through NoClick of the last 30 days, newest first.

Parameters:

- `key` (`string`, required)

Returns: Each earlier version.

### Bucket.restoreVersion

```typescript
restoreVersion(
  key: string,
  version: ObjectVersion | string,
): Promise<BucketObject>
```

Put `key` back as `version` held it; what it holds now is kept as a version in turn.

Parameters:

- `key` (`string`, required)
- `version` (`ObjectVersion | string`, required)

Returns: The file, as it's stored again.

### Bucket.signedUrl

```typescript
signedUrl(key: string, options?: BucketSignedUrlOptions): Promise<string>
```

A link that reads (`GET`) or uploads (`PUT`) the file without a NoClick key, until it expires.

Parameters:

- `key` (`string`, required)
- `options.method` (`"GET" | "PUT"`, default `"GET"`): `GET` reads the file, `PUT` uploads it (up to 5 GB).
- `options.expiresIn` (`number`, default `3600`): Seconds the link works: 60 to 604,800 (a week); 3600 by default.
- `options.contentType` (`string`): A `PUT` link's upload must send this type.

Returns: The link. Anyone who has it can use it until it expires, so hand it only to whoever needs it.

### Bucket.startUpload

```typescript
startUpload(key: string, options?: BucketUploadOptions): Promise<BucketUpload>
```

Begin uploading the file at `key` in parts: for a file bigger than a `PUT` link carries (5 GB), or one a page
sends a piece at a time. Sign a link per part with `uploadPartUrls`, `PUT` each part's bytes to its link (a
browser can, straight from a page: each answers with an `ETag` header), then join them with `completeUpload`, or
drop them with `abortUpload`. Each part is 5 MiB to 5 GiB, every part but the last the same size, up to 10,000
parts. Nothing is at `key` until the upload completes, and one left unfinished is dropped after 7 days. An app's
own code uploads this way, since S3 credentials stay with a person.

    const upload = await bucket.startUpload("b737/fcom.pdf", { contentType: "application/pdf" });

Parameters:

- `key` (`string`, required)
- `options.contentType` (`string`): Guessed from the key's extension when omitted.
- `options.metadata` (`Record<string, string>`): Up to 2 KB of your own string pairs, kept with the file.

Returns: The upload: its `upload_id` and the part sizes it takes.

### Bucket.uploadPartUrls

```typescript
uploadPartUrls(
  key: string,
  uploadId: string,
  partNumbers: Iterable<number>,
  options?: BucketPartUrlsOptions,
): Promise<Record<number, string>>
```

A `PUT` link for each of `partNumbers` (1 to 10,000) of the upload. `PUT` a part's bytes to its link: the
answer's `ETag` header names the part for `completeUpload`. A part uploaded again replaces it, so a failed part
is simply sent again.

    const links = await bucket.uploadPartUrls("b737/fcom.pdf", uploadId, [1, 2, 3], { expiresIn: 3600 });

Parameters:

- `key` (`string`, required)
- `uploadId` (`string`, required)
- `partNumbers` (`Iterable<number>`, required)
- `options.expiresIn` (`number`, default `3600`): Seconds the links work: 60 to 604,800 (a week); 3600 by default.

Returns: Each part number's link.

### Bucket.completeUpload

```typescript
completeUpload(
  key: string,
  uploadId: string,
  parts: Record<number, string>,
): Promise<BucketObject>
```

Join the uploaded parts into the file at `key`, in part number order: `parts` maps each part's number to the
`ETag` its upload answered with. What `key` held is kept as an earlier version, as `put` keeps it. Parts that
can't be joined throw `InvalidRequest` saying why (a wrong ETag, a part but the last under 5 MiB, or parts but the
last of different sizes); an upload already completed, aborted or over 7 days old throws `NotFound`.

    const stored = await bucket.completeUpload("b737/fcom.pdf", uploadId, { 1: etag1, 2: etag2 });

Parameters:

- `key` (`string`, required)
- `uploadId` (`string`, required)
- `parts` (`Record<number, string>`, required)

Returns: The file as stored, with its `size` and `etag`.

### Bucket.abortUpload

```typescript
abortUpload(key: string, uploadId: string): Promise<void>
```

Drop the upload and every part sent. One already completed or aborted is fine.

Parameters:

- `key` (`string`, required)
- `uploadId` (`string`, required)

### Bucket.url

```typescript
url(key: string): Promise<string>
```

The plain URL a public bucket serves `key` at; a private bucket throws `NotAvailable`.

Parameters:

- `key` (`string`, required)

Returns: `public_base_url` followed by the key; it works for as long as the bucket stays public.

### Bucket.update

```typescript
update(options: { public?: boolean }): Promise<this>
```

Change the bucket's settings; making it private stops every public URL at once.

Parameters:

- `options.public` (`boolean`)

Returns: This bucket, with the server's current fields.

### Bucket.notify

```typescript
notify(
  queue: string | { _ensure(): Promise<JsonObject> },
  options?: { prefix?: string; enabled?: boolean },
): Promise<this>
```

Put a message on `queue` (a `Queue` or its name, in the bucket's own user) for every file stored
under `prefix` (the whole bucket when omitted), however it arrived: `put`, a `PUT` signed link or
S3 credentials. The message is `{ event: "put", bucket, key, size, content_type, etag, at }`.
Asking again for the same queue and prefix changes nothing; `enabled: false` stops it.

    await recordings.notify("new-recordings", { prefix: "calls/" });

Parameters:

- `queue` (`string | { _ensure(): Promise<JsonObject> }`, required)
- `options.prefix` (`string`)
- `options.enabled` (`boolean`)

Returns: This bucket, whose `notifications` list where it tells.

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

### Bucket.s3Credentials

```typescript
s3Credentials(
  options?: { readOnly?: boolean; ttlS?: number },
): Promise<S3Credentials>
```

Keys for the S3-compatible endpoint, valid `ttlS` seconds (900 to 43,200; 3600 by default). They're for you and
your own code: an app's deployed code is refused them (`PermissionDenied`) and uploads big files in parts
(`startUpload`) instead.

Parameters:

- `options.readOnly` (`boolean`)
- `options.ttlS` (`number`, default `3600`)

Returns: The endpoint, bucket name, keys and `expires_at`. The secret is shown once; mint new ones when they expire.

### Bucket.export

```typescript
export(): Promise<Operation<ExportBundle>>
```

Export every file, to take anywhere: a zip holding each one at its key (under
`buckets/<name>/files/`), with `index.jsonl` listing each key's content type and metadata. A
key that can't be a path in a zip (an empty, `.` or `..` part) is kept under `renamed/`, and the
index says which. `wait()` resolves to an `ExportBundle`: the zip at `url`, valid 7 days.

Returns: An operation whose `wait()` gives an `ExportBundle`: the zip at `url`, valid 7 days.

### Bucket.delete

```typescript
delete(options?: { force?: boolean }): Promise<TrashItem>
```

Delete the bucket: it goes to the trash, restorable for 30 days (its files stored, and billed,
until it's purged). It must be empty unless `force` (which takes its files too), and in no
agent's tools. Returns its `TrashItem`.

Parameters:

- `options.force` (`boolean`)

Returns: Its `TrashItem`: `restore()` puts it back, files and all.

## BucketObject

```typescript
interface BucketObject
```

A file in a bucket. In a listing with a `delimiter`, an entry with `isFolder` stands for
every key under that prefix, and only its `key` is set.

| Attribute | Type | Description |
| --- | --- | --- |
| `key` | `string` |  |
| `size` | `number | null` |  |
| `contentType` | `string | null` |  |
| `etag` | `string | null` | Changes whenever the content does. |
| `metadata` | `Record<string, string>` |  |
| `updatedAt` | `Date | null` |  |
| `isFolder` | `boolean` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## ObjectVersion

```typescript
interface ObjectVersion
```

What a file held before a write through NoClick replaced it (`op` `changed`) or removed it
(`deleted`), kept 30 days. An upload through a signed link or S3 credentials keeps none.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` |  |
| `key` | `string` |  |
| `op` | `"changed" | "deleted"` |  |
| `size` | `number | null` |  |
| `replacedAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## BucketOperations

```typescript
class BucketOperations
```

Some of a bucket's operations as an agent's tools (`bucket.only(...)`), with the arguments `bind(...)` fixed.

| Attribute | Type | Description |
| --- | --- | --- |
| `bucket` | `Bucket` |  |
| `operations` | `BucketTool[]` |  |
| `bindings` | `JsonObject` | The arguments NoClick fills on every call, out of the model's reach. |

Types:

```typescript
type BucketTool = (typeof BUCKET_TOOLS)[number];

type JsonObject = { [key: string]: unknown };
```

### BucketOperations.bind

```typescript
bind(args: JsonObject): BucketOperations
```

Fix arguments of these operations, as `ConnectionOperations.bind` does. `prefix` is the one to
bind here: every key the tools take and return is then under it, so one bucket holds a folder
per user.

    uploads.only("objects", "put", "signed_url").bind({ prefix: "users/{{user.id}}/" })

Parameters:

- `args` (`JsonObject`, required)

Returns: A new ref with these arguments bound on top of any bound before.

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## BucketUpload

```typescript
interface BucketUpload
```

A file being uploaded in parts (`bucket.startUpload`): its `key` and `uploadId`, which the other upload calls take,
its `contentType`, and the parts it takes: each `minPartBytes` (5 MiB) to `maxPartBytes` (5 GiB), every part but the
last the same size, up to `maxParts` (10,000).

| Attribute | Type | Description |
| --- | --- | --- |
| `key` | `string` |  |
| `uploadId` | `string` |  |
| `contentType` | `string | null` |  |
| `minPartBytes` | `number` |  |
| `maxPartBytes` | `number` |  |
| `maxParts` | `number` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## S3Credentials

```typescript
interface S3Credentials
```

Short-lived keys for the bucket's S3-compatible endpoint (rclone, the AWS CLI, an S3
library). `bucket` is its name on that endpoint, not its NoClick name. Keys are a person's: an app's deployed code
gets none, and uploads a file of any size in parts (`bucket.startUpload`) instead.

| Attribute | Type | Description |
| --- | --- | --- |
| `endpoint` | `string` |  |
| `bucket` | `string` |  |
| `accessKeyId` | `string` |  |
| `secretAccessKey` | `string` |  |
| `sessionToken` | `string | null` |  |
| `region` | `string` |  |
| `readOnly` | `boolean` |  |
| `expiresAt` | `Date | null` |  |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```
