@calmlens/sdk 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,210 @@
1
+ import { $ as SearchAssetsOptions, A as DeleteAssetContentOptions, B as Lens, C as CdnAssetUrlOptions, Ct as EventSeverity, D as CreateAssetSignedUrlOptions, Dt as LensType, E as ConnectionOptions, Et as Page, F as IdempotencyOptions, Ft as ImageData, G as ModerateTextOptions, H as ListAssetChildrenOptions, I as ImageTransform, It as MetadataItem, J as MultipartUploadOptions, K as MoveAssetOptions, L as ImageTransformOptions, Lt as PreviewImage, M as EnsureLensOptions, Mt as AssetSafetyHoldReason, N as EnsureLensesOptions, Nt as DocumentData, O as CreateFolderOptions, Ot as AssetSearchMatchField, P as FolderIdOptions, Pt as ExtractedText, Q as RetryAssetOptions, R as IterateAssetChildrenOptions, Rt as ProcessingOptions, S as CalmLensServerClientOptions, St as EventFacts, T as CdnTransform, Tt as Order, U as ListAssetsOptions, V as LensTransform, W as ListEventsOptions, X as RequestOptions, Y as MultipartUploadPartOptions, Z as RetrieveAssetOptions, _ as AssetSearchResult, _t as EventAsset, a as ClassificationLabel, at as UpdateFolderOptions, b as AssetVisibility, bt as EventFact, c as ClassificationReport, ct as UploadedAsset, d as Asset, dt as WebhookHeadersInput, et as SignUploadTokenOptions, f as AssetChecksums, ft as WebhookPayloadInput, g as AssetSearchResponse, h as AssetPage, ht as Folder, i as ClassificationCategoryReport, it as UpdateAssetOptions, j as DeleteAssetOptions, jt as AssetSafetyHold, k as CreateMultipartUploadPartOptions, kt as AssetSearchQuery, l as Likelihood, lt as VerifyWebhookSignatureOptions, m as AssetContentOptions, mt as PostAssetSignedUrlResponse, n as ClassificationCategories, nt as SignedUrl, o as ClassificationNotEvaluatedReason, ot as UploadAssetPartOptions, p as AssetChildrenPage, pt as GetEventsResponse, q as MoveFolderOptions, r as ClassificationCategory, rt as SubmitAssetOptions, s as ClassificationQualifierResults, st as UploadPresetSubmitAssetOptions, t as WebhookEventPayload, tt as SignedUploadToken, u as ModerationQualifier, ut as WaitForAssetDecisionOptions, v as AssetStatus, vt as TypedEvent, w as CdnServeOptions, wt as EventType, x as CalmLensAppClientOptions, xt as EventFactValues, y as AssetType, yt as EventCategory, z as IterateAssetsOptions } from "./WebhookPayload-B7CgSmI5.js";
2
+ import { _ as ProcessingFeatureStage, a as CalmLensErrorDetails, c as ApiErrorCode, d as AgeRange, f as BoundingBox, g as ProcessingFeatureResults, h as ProcessingFeatureId, i as CalmLensErrorCode, l as FlaggedContentAction, m as DetectedPerson, n as CALMLENS_ERROR_CODES, o as CalmLensErrorOptions, p as DetectedFace, r as CalmLensError, s as SdkErrorCode, t as SDK_VERSION, u as FlaggedContentPolicy, v as ProcessingFeatures } from "./index-BywTQbRq.js";
3
+ //#region src/client/CalmLensServerClient.d.ts
4
+ interface LensCache {
5
+ readonly ensuredLenses: Map<string, Lens>;
6
+ readonly pendingEnsureLenses: Map<string, Promise<void>>;
7
+ }
8
+ declare const inspectSymbol: unique symbol;
9
+ /**
10
+ * The CalmLens API client for your server, authenticated with a project API key. Create one per
11
+ * project and reuse it; it holds no connections. Every method takes one options object and
12
+ * throws `CalmLensError` on failure. Browsers and apps upload with `CalmLensAppClient` instead.
13
+ */
14
+ declare class CalmLensServerClient {
15
+ #private;
16
+ /**
17
+ * Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
18
+ * `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
19
+ * more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
20
+ * Also exported as `verifyWebhookSignature`; `parseWebhookEvent` verifies and parses.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const payload = await request.text();
25
+ * const isValid = await CalmLensServerClient.verifyWebhookSignature({
26
+ * payload,
27
+ * headers: request.headers,
28
+ * secret: process.env.CALMLENS_WEBHOOK_SECRET!,
29
+ * });
30
+ * ```
31
+ */
32
+ static verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean>;
33
+ constructor(options: CalmLensServerClientOptions, lenses?: LensCache);
34
+ /**
35
+ * A client with different cancellation, deadlines or retries for the calls made through it,
36
+ * sharing this client's credentials and lens cache. This client is unchanged.
37
+ */
38
+ withRequestOptions(options: RequestOptions): CalmLensServerClient;
39
+ /** Keeps the API key out of `console.log`, `util.inspect` and `JSON.stringify`. */
40
+ [inspectSymbol](): string;
41
+ toJSON(): {
42
+ projectId: string;
43
+ baseUrl: string;
44
+ cdnBaseUrl: string;
45
+ };
46
+ private get projectPath();
47
+ private request;
48
+ private submitAsset;
49
+ get cdn(): {
50
+ /**
51
+ * Builds a CDN URL for asset content or a preview, without a request. Private assets
52
+ * need a signed URL (`assets.createSignedUrl`) or an authenticated request.
53
+ */
54
+ getAssetUrl: ({ assetIdentifier, ...options }: CdnAssetUrlOptions) => string;
55
+ /**
56
+ * Fetches asset content or a preview from the CDN with the client's API key, and returns
57
+ * the `Response` as soon as headers arrive, so the body streams. Non-2xx responses are
58
+ * returned, not thrown; `timeoutMs` covers only the wait for headers.
59
+ */
60
+ serve: ({ assetIdentifier, init, ...urlOptions }: CdnServeOptions) => Promise<Response>;
61
+ };
62
+ get text(): {
63
+ /**
64
+ * Moderates text and waits for the decision. Sends `text` as `text/plain` content named
65
+ * `text` unless you pass `name`.
66
+ */
67
+ moderate: (options: ModerateTextOptions) => Promise<Asset>;
68
+ };
69
+ /** Assets: uploads, moderation and management. */
70
+ get assets(): {
71
+ /** Searches accessible assets by keyword or a natural-language description. */
72
+ search: (options: Partial<AssetSearchQuery> & {
73
+ query: string;
74
+ }) => Promise<AssetSearchResponse>;
75
+ /** Lists one page of the project's assets, with optional filter and ordering. */
76
+ list: (options?: ListAssetsOptions) => Promise<AssetPage>;
77
+ /**
78
+ * Yields every asset matching `options`, fetching pages as needed. Assets created or
79
+ * deleted while iterating can shift pages, so an asset may be skipped or repeated.
80
+ */
81
+ iterate: (options?: IterateAssetsOptions) => AsyncGenerator<Asset, void, undefined>;
82
+ /** Retrieves an asset with its status and moderation report. */
83
+ retrieve: ({ assetId }: RetrieveAssetOptions) => Promise<Asset>;
84
+ /** Updates an asset's editable fields. */
85
+ update: ({ assetId, ...body }: UpdateAssetOptions) => Promise<Asset>;
86
+ /** Lists one page of the assets extracted from a website or multimedia document. */
87
+ listChildren: ({ assetId, ...options }?: ListAssetChildrenOptions) => Promise<AssetChildrenPage>;
88
+ /** Yields every child of an asset, fetching pages as needed. */
89
+ iterateChildren: (options: IterateAssetChildrenOptions) => AsyncGenerator<Asset, void, undefined>;
90
+ /**
91
+ * Uploads an asset and queues it for moderation, returning immediately with status
92
+ * `pending` (or `uploading` for the first multipart part). Retried safely with an
93
+ * `Idempotency-Key`.
94
+ */
95
+ create: (options: SubmitAssetOptions) => Promise<Asset>;
96
+ /**
97
+ * Uploads an asset and waits for its moderation decision. Audio and video still finish
98
+ * in the background. Retried safely with an `Idempotency-Key`.
99
+ */
100
+ moderate: (options: SubmitAssetOptions) => Promise<Asset>;
101
+ /**
102
+ * Uploads the next part of a multipart upload. The upload's queue mode, chosen when it
103
+ * started, applies when the final part arrives; pass `queue` to override it.
104
+ */
105
+ uploadPart: ({ assetId, ...options }: UploadAssetPartOptions) => Promise<Asset>;
106
+ /**
107
+ * Creates a short-lived signed CDN URL, so browsers can load private content without
108
+ * an API key.
109
+ */
110
+ createSignedUrl: ({ assetId, ...options }: CreateAssetSignedUrlOptions) => Promise<PostAssetSignedUrlResponse>;
111
+ /** Moves an asset into a folder, or to the project root with `folderId: null`. */
112
+ move: ({ assetId, folderId }: MoveAssetOptions) => Promise<Asset>;
113
+ /**
114
+ * Processes an asset that failed (status `error`) again. It returns to `pending` and is
115
+ * moderated like a new upload; its content must still be stored.
116
+ */
117
+ retry: ({ assetId }: RetryAssetOptions) => Promise<Asset>;
118
+ /**
119
+ * Waits for an asset's moderation decision (`approved`, `rejected` or `error`) and returns
120
+ * the decided asset, checking every few seconds. Rejects with `sdk/timeout` if there is no
121
+ * decision within `timeoutMs` (default 60000). Webhooks report decisions without polling.
122
+ */
123
+ waitForDecision: ({ assetId, ...options }: WaitForAssetDecisionOptions) => Promise<Asset>;
124
+ /**
125
+ * Removes an asset's stored content (source, preview and retained extracted text) while
126
+ * keeping the asset record, metadata and moderation report. The returned asset has
127
+ * `storageDeletedAt` set; the CDN no longer serves it.
128
+ */
129
+ deleteContent: ({ assetId }: DeleteAssetContentOptions) => Promise<Asset>;
130
+ /** Deletes an asset record together with its stored content. */
131
+ delete: ({ assetId }: DeleteAssetOptions) => Promise<void>;
132
+ };
133
+ /**
134
+ * Signs upload tokens on your server, so a browser or app can upload through an upload preset
135
+ * that requires one. Signing happens locally with your API key: it makes no request.
136
+ */
137
+ get uploadTokens(): {
138
+ /**
139
+ * Signs a single-use token for one upload through `uploadPresetId`. Give `token` to the
140
+ * browser or app, which passes it to `CalmLensAppClient` as `token`.
141
+ */
142
+ sign: (options: SignUploadTokenOptions) => Promise<SignedUploadToken>;
143
+ };
144
+ private buildAssets;
145
+ get events(): {
146
+ /**
147
+ * Lists project events after a cursor, oldest first. Call without `after` to get a cursor
148
+ * for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
149
+ * reshaped as `{ id, type, createdAt, projectId, data }`.
150
+ */
151
+ list: (options?: ListEventsOptions) => Promise<GetEventsResponse>;
152
+ /**
153
+ * Yields pages of events after `after` until no more are waiting. Save each page's
154
+ * `cursor` to resume later. Without `after`, yields one empty page whose cursor is "now".
155
+ */
156
+ pages: (options?: ListEventsOptions) => AsyncGenerator<GetEventsResponse, void, undefined>;
157
+ };
158
+ private iterateEventPages;
159
+ private iteratePages;
160
+ get folders(): {
161
+ /** Lists every folder in the project. */
162
+ list: () => Promise<Folder[]>;
163
+ retrieve: ({ folderId }: FolderIdOptions) => Promise<Folder>;
164
+ /** Creates a folder at the project root or inside `parentId`. */
165
+ create: (options: CreateFolderOptions) => Promise<Folder>;
166
+ update: ({ folderId, ...body }: UpdateFolderOptions) => Promise<Folder>;
167
+ /** Deletes an empty folder; throws `folder/not-empty` otherwise. */
168
+ delete: ({ folderId }: FolderIdOptions) => Promise<void>;
169
+ /** Moves a folder under `parentId`, or to the project root with `parentId: null`. */
170
+ move: ({ folderId, parentId }: MoveFolderOptions) => Promise<Folder>;
171
+ };
172
+ /**
173
+ * Create a named lens at any positive version, or update it with a greater version.
174
+ * Supplying the same definition and version is idempotent.
175
+ */
176
+ ensureLens(options: EnsureLensOptions): Promise<Lens>;
177
+ /**
178
+ * Create or update several named lenses. New definitions are sent in one API request, or in
179
+ * consecutive requests of at most {@link ENSURE_LENSES_MAX_PER_REQUEST} definitions, in order.
180
+ * Each lens follows the same versioning and idempotency rules as ensureLens().
181
+ */
182
+ ensureLenses({ lenses }: EnsureLensesOptions): Promise<Lens[]>;
183
+ private submitEnsureLenses;
184
+ private submitEnsureLensesChunk;
185
+ }
186
+ //#endregion
187
+ //#region src/client/CalmLensWebhooks.d.ts
188
+ export declare const WEBHOOK_DELIVERY_HEADER = "x-calmlens-delivery";
189
+ export declare const WEBHOOK_TIMESTAMP_HEADER = "x-calmlens-timestamp";
190
+ export declare const WEBHOOK_SIGNATURE_HEADER = "x-calmlens-signature";
191
+ /** Deliveries whose timestamp is further than this from the receiver's clock are rejected. */
192
+ export declare const WEBHOOK_SIGNATURE_TOLERANCE_SECONDS = 300;
193
+ /**
194
+ * Verifies a webhook delivery: `x-calmlens-signature` must contain a `v1=` HMAC-SHA256 of
195
+ * `"<x-calmlens-timestamp>.<raw body>"`, and the timestamp must be within `toleranceSeconds`
196
+ * (default 300) of now. Returns `false` for anything missing, malformed or stale, and throws
197
+ * `sdk/invalid-argument` when `payload` is not a raw body (for example, parsed JSON).
198
+ */
199
+ export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean>;
200
+ /**
201
+ * Verifies a webhook delivery and parses its body. Throws `sdk/invalid-webhook-signature`
202
+ * when the signature or timestamp does not verify, and `sdk/invalid-webhook-payload` when a
203
+ * verified body is not a webhook event. Narrow the result on `type` for typed `data.facts`.
204
+ *
205
+ * Event types and fact keys added to CalmLens after this SDK version are returned as they are,
206
+ * so keep a default branch when you switch on `type`.
207
+ */
208
+ export declare function parseWebhookEvent(options: VerifyWebhookSignatureOptions): Promise<WebhookEventPayload>;
209
+ //#endregion
210
+ export { type AgeRange, type ApiErrorCode, type Asset, type AssetChecksums, type AssetChildrenPage, type AssetContentOptions, type AssetPage, type AssetSafetyHold, type AssetSafetyHoldReason, type AssetSearchMatchField, type AssetSearchQuery, type AssetSearchResponse, type AssetSearchResult, type AssetStatus, type AssetType, type AssetVisibility, type BoundingBox, CALMLENS_ERROR_CODES, type CalmLensAppClientOptions, CalmLensError, type CalmLensErrorCode, type CalmLensErrorDetails, type CalmLensErrorOptions, CalmLensServerClient, type CalmLensServerClientOptions, type CdnAssetUrlOptions, type CdnServeOptions, type CdnTransform, type ClassificationCategories, type ClassificationCategory, type ClassificationCategoryReport, type ClassificationLabel, type ClassificationNotEvaluatedReason, type ClassificationQualifierResults, type ClassificationReport, type ConnectionOptions, type CreateAssetSignedUrlOptions, type CreateFolderOptions, type CreateMultipartUploadPartOptions, type DeleteAssetContentOptions, type DeleteAssetOptions, type DetectedFace, type DetectedPerson, type DocumentData, type EnsureLensOptions, type EnsureLensesOptions, type EventAsset, type EventCategory, type EventFact, type EventFactValues, type EventFacts, type EventSeverity, type EventType, type GetEventsResponse as EventsPage, type ExtractedText, type FlaggedContentAction, type FlaggedContentPolicy, type Folder, type FolderIdOptions, type IdempotencyOptions, type ImageData, type ImageTransform, type ImageTransformOptions, type IterateAssetChildrenOptions, type IterateAssetsOptions, type Lens, type LensTransform, type LensType, type Likelihood, type ListAssetChildrenOptions, type ListAssetsOptions, type ListEventsOptions, type MetadataItem, type ModerateTextOptions, type ModerationQualifier, type MoveAssetOptions, type MoveFolderOptions, type MultipartUploadOptions, type MultipartUploadPartOptions, type Order, type Page, type PreviewImage, type ProcessingFeatureId, type ProcessingFeatureResults, type ProcessingFeatureStage, type ProcessingFeatures, type ProcessingOptions, type RequestOptions, type RetrieveAssetOptions, type RetryAssetOptions, SDK_VERSION, type SdkErrorCode, type SearchAssetsOptions, type SignUploadTokenOptions, type SignedUploadToken, type SignedUrl, type SubmitAssetOptions, type TypedEvent, type UpdateAssetOptions, type UpdateFolderOptions, type UploadAssetPartOptions, type UploadPresetSubmitAssetOptions, type UploadedAsset, type VerifyWebhookSignatureOptions, type WaitForAssetDecisionOptions, type WebhookEventPayload, type WebhookHeadersInput, type WebhookPayloadInput };
package/esm/server.js ADDED
@@ -0,0 +1,374 @@
1
+ import { a as CALMLENS_ERROR_CODES, c as invalidArgument, i as isReactNativeRuntime, l as invalidConfig, o as CalmLensError, r as isBrowserRuntime, s as SDK_ERROR_CODES, t as SDK_VERSION } from "./CalmLensVersion-DK4BMEST.js";
2
+ import "./index.js";
3
+ import { a as parseWebhookEvent, i as WEBHOOK_TIMESTAMP_HEADER, l as stringifyJsonCanonical, n as WEBHOOK_SIGNATURE_HEADER, o as verifyWebhookSignature, r as WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, s as signUploadTokenWithApiKey, t as WEBHOOK_DELIVERY_HEADER } from "./CalmLensWebhooks-DyCoEvpf.js";
4
+ import { f as sleep, l as validateRequestOptions, n as encodePathSegment, o as toTextAssetOptions, r as pollForDecision, s as transformSelector, t as appendCdnSelector, u as validateServerClientOptions } from "./CalmLensUtils-B4i3Z2He.js";
5
+ import { a as newIdempotencyKey, i as invalidPayload, n as expectAsset, o as prepareSubmitAssetOptions, s as resolveConnectionOptions, t as CalmLensConnection } from "./CalmLensConnection-D8VsTdsA.js";
6
+ const getEnsureLensCacheKey = (options) => stringifyJsonCanonical({
7
+ identifier: options.identifier,
8
+ name: options.name,
9
+ description: options.description ?? null,
10
+ type: options.type,
11
+ active: options.active,
12
+ transforms: options.transforms ?? null,
13
+ version: options.version
14
+ });
15
+ const requireId = (value, name) => encodePathSegment(value, name);
16
+ const inspectSymbol = Symbol.for("nodejs.util.inspect.custom");
17
+ /**
18
+ * The CalmLens API client for your server, authenticated with a project API key. Create one per
19
+ * project and reuse it; it holds no connections. Every method takes one options object and
20
+ * throws `CalmLensError` on failure. Browsers and apps upload with `CalmLensAppClient` instead.
21
+ */
22
+ var CalmLensServerClient = class CalmLensServerClient {
23
+ #apiKey;
24
+ #settings;
25
+ #lenses;
26
+ #connection;
27
+ /**
28
+ * Verifies that a webhook delivery came from CalmLens: checks the `v1=` HMAC-SHA256 in
29
+ * `x-calmlens-signature` over `"<x-calmlens-timestamp>.<raw body>"` and rejects timestamps
30
+ * more than `toleranceSeconds` (default 300) from now, which stops replayed deliveries.
31
+ * Also exported as `verifyWebhookSignature`; `parseWebhookEvent` verifies and parses.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const payload = await request.text();
36
+ * const isValid = await CalmLensServerClient.verifyWebhookSignature({
37
+ * payload,
38
+ * headers: request.headers,
39
+ * secret: process.env.CALMLENS_WEBHOOK_SECRET!,
40
+ * });
41
+ * ```
42
+ */
43
+ static async verifyWebhookSignature(options) {
44
+ return verifyWebhookSignature(options);
45
+ }
46
+ constructor(options, lenses) {
47
+ validateServerClientOptions(options);
48
+ if ((isBrowserRuntime() || isReactNativeRuntime()) && !options.dangerouslyAllowBrowser) throw invalidConfig("CalmLensServerClient is running in a browser or app, where anyone could read the API key. Call CalmLens from your server, upload from the browser or app with CalmLensAppClient, or set dangerouslyAllowBrowser: true for trusted internal tools.");
49
+ const { apiKey, ...rest } = options;
50
+ this.#apiKey = apiKey;
51
+ this.#settings = {
52
+ ...resolveConnectionOptions(rest),
53
+ cdnBaseUrl: (rest.cdnBaseUrl ?? `https://cdn.calmlens.com/v1`).replace(/\/+$/, "")
54
+ };
55
+ this.#lenses = lenses ?? {
56
+ ensuredLenses: /* @__PURE__ */ new Map(),
57
+ pendingEnsureLenses: /* @__PURE__ */ new Map()
58
+ };
59
+ this.#connection = new CalmLensConnection(this.#settings, apiKey);
60
+ }
61
+ /**
62
+ * A client with different cancellation, deadlines or retries for the calls made through it,
63
+ * sharing this client's credentials and lens cache. This client is unchanged.
64
+ */
65
+ withRequestOptions(options) {
66
+ validateRequestOptions(options);
67
+ return new CalmLensServerClient({
68
+ ...this.#settings,
69
+ ...options,
70
+ apiKey: this.#apiKey
71
+ }, this.#lenses);
72
+ }
73
+ /** Keeps the API key out of `console.log`, `util.inspect` and `JSON.stringify`. */
74
+ [inspectSymbol]() {
75
+ const { projectId, baseUrl } = this.#settings;
76
+ return `CalmLensServerClient { projectId: ${JSON.stringify(projectId)}, baseUrl: ${JSON.stringify(baseUrl)} }`;
77
+ }
78
+ toJSON() {
79
+ const { projectId, baseUrl, cdnBaseUrl } = this.#settings;
80
+ return {
81
+ projectId,
82
+ baseUrl,
83
+ cdnBaseUrl
84
+ };
85
+ }
86
+ get projectPath() {
87
+ return `/projects/${encodeURIComponent(this.#settings.projectId)}`;
88
+ }
89
+ request(method, path, options = {}) {
90
+ return this.#connection.json(method, path, options);
91
+ }
92
+ async submitAsset(options, queue) {
93
+ const body = prepareSubmitAssetOptions(options);
94
+ const uploadsPath = `${this.projectPath}/assets`;
95
+ if ("content" in body || "part" in body) return expectAsset(await this.#connection.submitRawUpload(uploadsPath, body, queue));
96
+ const { idempotencyKey, ...fields } = body;
97
+ const data = await this.#connection.json("POST", uploadsPath, {
98
+ query: { queue },
99
+ body: fields,
100
+ idempotencyKey: idempotencyKey ?? newIdempotencyKey()
101
+ });
102
+ return expectAsset(data);
103
+ }
104
+ get cdn() {
105
+ return {
106
+ /**
107
+ * Builds a CDN URL for asset content or a preview, without a request. Private assets
108
+ * need a signed URL (`assets.createSignedUrl`) or an authenticated request.
109
+ */
110
+ getAssetUrl: ({ assetIdentifier, ...options }) => {
111
+ const resource = options.resource ?? "content";
112
+ const { projectId } = this.#settings;
113
+ const url = `${this.#settings.cdnBaseUrl}/assets/${encodeURIComponent(projectId)}/${requireId(assetIdentifier, "Asset identifier")}/${resource}`;
114
+ return appendCdnSelector(url, options);
115
+ },
116
+ /**
117
+ * Fetches asset content or a preview from the CDN with the client's API key, and returns
118
+ * the `Response` as soon as headers arrive, so the body streams. Non-2xx responses are
119
+ * returned, not thrown; `timeoutMs` covers only the wait for headers.
120
+ */
121
+ serve: async ({ assetIdentifier, init, ...urlOptions }) => {
122
+ const url = this.cdn.getAssetUrl({
123
+ assetIdentifier,
124
+ ...urlOptions
125
+ });
126
+ const method = init?.method?.toUpperCase() ?? "GET";
127
+ const { response } = await this.#connection.transport.send({
128
+ method,
129
+ url,
130
+ init,
131
+ timeoutMs: this.#connection.timeoutMs,
132
+ deadline: "headers",
133
+ fetch: this.#settings.cdnFetch
134
+ }, { allowHttpErrors: true });
135
+ return response;
136
+ }
137
+ };
138
+ }
139
+ get text() {
140
+ return {
141
+ /**
142
+ * Moderates text and waits for the decision. Sends `text` as `text/plain` content named
143
+ * `text` unless you pass `name`.
144
+ */
145
+ moderate: async (options) => this.buildAssets().moderate(toTextAssetOptions(options)) };
146
+ }
147
+ /** Assets: uploads, moderation and management. */
148
+ get assets() {
149
+ return this.buildAssets();
150
+ }
151
+ /**
152
+ * Signs upload tokens on your server, so a browser or app can upload through an upload preset
153
+ * that requires one. Signing happens locally with your API key: it makes no request.
154
+ */
155
+ get uploadTokens() {
156
+ return {
157
+ /**
158
+ * Signs a single-use token for one upload through `uploadPresetId`. Give `token` to the
159
+ * browser or app, which passes it to `CalmLensAppClient` as `token`.
160
+ */
161
+ sign: async (options) => {
162
+ return signUploadTokenWithApiKey(this.#apiKey, options);
163
+ } };
164
+ }
165
+ buildAssets() {
166
+ return {
167
+ /** Searches accessible assets by keyword or a natural-language description. */
168
+ search: async (options) => this.request("GET", `${this.projectPath}/assets/search`, { query: options }),
169
+ /** Lists one page of the project's assets, with optional filter and ordering. */
170
+ list: async (options = {}) => this.request("GET", `${this.projectPath}/assets/page`, { query: {
171
+ ...options,
172
+ pageIndex: options.pageIndex ?? 0
173
+ } }),
174
+ /**
175
+ * Yields every asset matching `options`, fetching pages as needed. Assets created or
176
+ * deleted while iterating can shift pages, so an asset may be skipped or repeated.
177
+ */
178
+ iterate: (options = {}) => this.iteratePages((pageIndex) => this.buildAssets().list({
179
+ ...options,
180
+ pageIndex
181
+ })),
182
+ /** Retrieves an asset with its status and moderation report. */
183
+ retrieve: async ({ assetId }) => this.request("GET", `/assets/${requireId(assetId, "Asset ID")}`),
184
+ /** Updates an asset's editable fields. */
185
+ update: async ({ assetId, ...body }) => this.request("PATCH", `/assets/${requireId(assetId, "Asset ID")}`, { body }),
186
+ /** Lists one page of the assets extracted from a website or multimedia document. */
187
+ listChildren: async ({ assetId, ...options } = {}) => this.request("GET", `/assets/${requireId(assetId, "Asset ID")}/children`, { query: {
188
+ ...options,
189
+ pageIndex: options.pageIndex ?? 0
190
+ } }),
191
+ /** Yields every child of an asset, fetching pages as needed. */
192
+ iterateChildren: (options) => {
193
+ requireId(options?.assetId, "Asset ID");
194
+ return this.iteratePages((pageIndex) => this.buildAssets().listChildren({
195
+ ...options,
196
+ pageIndex
197
+ }));
198
+ },
199
+ /**
200
+ * Uploads an asset and queues it for moderation, returning immediately with status
201
+ * `pending` (or `uploading` for the first multipart part). Retried safely with an
202
+ * `Idempotency-Key`.
203
+ */
204
+ create: async (options) => this.submitAsset(options, true),
205
+ /**
206
+ * Uploads an asset and waits for its moderation decision. Audio and video still finish
207
+ * in the background. Retried safely with an `Idempotency-Key`.
208
+ */
209
+ moderate: async (options) => {
210
+ if (options && "content" in options && "plainText" in options.content && (typeof options.content.plainText !== "string" || !options.content.plainText.trim())) throw invalidPayload("Text to moderate must be a non-empty string");
211
+ return this.submitAsset(options, false);
212
+ },
213
+ /**
214
+ * Uploads the next part of a multipart upload. The upload's queue mode, chosen when it
215
+ * started, applies when the final part arrives; pass `queue` to override it.
216
+ */
217
+ uploadPart: async ({ assetId, ...options }) => {
218
+ const encodedAssetId = requireId(assetId, "Asset ID");
219
+ return expectAsset(await this.#connection.uploadPart(`/assets/${encodedAssetId}/part`, options));
220
+ },
221
+ /**
222
+ * Creates a short-lived signed CDN URL, so browsers can load private content without
223
+ * an API key.
224
+ */
225
+ createSignedUrl: async ({ assetId, ...options }) => {
226
+ const encodedAssetId = requireId(assetId, "Asset ID");
227
+ if (options.lens && options.transform) throw invalidArgument("Specify either a lens or a transform, not both");
228
+ return this.request("POST", `/assets/${encodedAssetId}/signed-url`, { body: {
229
+ resource: options.resource ?? "content",
230
+ expiresInSeconds: options.expiresInSeconds ?? 900,
231
+ lens: options.lens,
232
+ transform: transformSelector(options.transform)
233
+ } });
234
+ },
235
+ /** Moves an asset into a folder, or to the project root with `folderId: null`. */
236
+ move: async ({ assetId, folderId }) => this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/move`, { body: { folderId } }),
237
+ /**
238
+ * Processes an asset that failed (status `error`) again. It returns to `pending` and is
239
+ * moderated like a new upload; its content must still be stored.
240
+ */
241
+ retry: async ({ assetId }) => this.request("POST", `/assets/${requireId(assetId, "Asset ID")}/retry`),
242
+ /**
243
+ * Waits for an asset's moderation decision (`approved`, `rejected` or `error`) and returns
244
+ * the decided asset, checking every few seconds. Rejects with `sdk/timeout` if there is no
245
+ * decision within `timeoutMs` (default 60000). Webhooks report decisions without polling.
246
+ */
247
+ waitForDecision: async ({ assetId, ...options }) => {
248
+ requireId(assetId, "Asset ID");
249
+ const client = options.signal ? this.withRequestOptions({ signal: options.signal }) : this;
250
+ return pollForDecision(() => client.assets.retrieve({ assetId }), options, sleep);
251
+ },
252
+ /**
253
+ * Removes an asset's stored content (source, preview and retained extracted text) while
254
+ * keeping the asset record, metadata and moderation report. The returned asset has
255
+ * `storageDeletedAt` set; the CDN no longer serves it.
256
+ */
257
+ deleteContent: async ({ assetId }) => this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}/content`),
258
+ /** Deletes an asset record together with its stored content. */
259
+ delete: async ({ assetId }) => {
260
+ await this.request("DELETE", `/assets/${requireId(assetId, "Asset ID")}`);
261
+ }
262
+ };
263
+ }
264
+ get events() {
265
+ return {
266
+ /**
267
+ * Lists project events after a cursor, oldest first. Call without `after` to get a cursor
268
+ * for "now", then poll with the returned `cursor`. Webhook deliveries carry the same events
269
+ * reshaped as `{ id, type, createdAt, projectId, data }`.
270
+ */
271
+ list: async (options = {}) => this.request("GET", `${this.projectPath}/events`, { query: { ...options } }),
272
+ /**
273
+ * Yields pages of events after `after` until no more are waiting. Save each page's
274
+ * `cursor` to resume later. Without `after`, yields one empty page whose cursor is "now".
275
+ */
276
+ pages: (options = {}) => this.iterateEventPages(options)
277
+ };
278
+ }
279
+ async *iterateEventPages(options) {
280
+ let after = options.after;
281
+ for (;;) {
282
+ const page = await this.events.list({
283
+ ...options,
284
+ after
285
+ });
286
+ yield page;
287
+ if (!page.hasMore || page.cursor === after) return;
288
+ after = page.cursor;
289
+ }
290
+ }
291
+ async *iteratePages(listPage) {
292
+ for (let pageIndex = 0;; pageIndex++) {
293
+ const page = await listPage(pageIndex);
294
+ yield* page.items;
295
+ if (!page.hasMore || page.items.length === 0) return;
296
+ }
297
+ }
298
+ get folders() {
299
+ return {
300
+ /** Lists every folder in the project. */
301
+ list: async () => (await this.request("GET", `${this.projectPath}/folders`)).folders,
302
+ retrieve: async ({ folderId }) => this.request("GET", `/folders/${requireId(folderId, "Folder ID")}`),
303
+ /** Creates a folder at the project root or inside `parentId`. */
304
+ create: async (options) => this.request("POST", `${this.projectPath}/folders`, { body: options }),
305
+ update: async ({ folderId, ...body }) => this.request("PATCH", `/folders/${requireId(folderId, "Folder ID")}`, { body }),
306
+ /** Deletes an empty folder; throws `folder/not-empty` otherwise. */
307
+ delete: async ({ folderId }) => {
308
+ await this.request("DELETE", `/folders/${requireId(folderId, "Folder ID")}`);
309
+ },
310
+ /** Moves a folder under `parentId`, or to the project root with `parentId: null`. */
311
+ move: async ({ folderId, parentId }) => this.request("POST", `/folders/${requireId(folderId, "Folder ID")}/move`, { body: { parentId } })
312
+ };
313
+ }
314
+ /**
315
+ * Create a named lens at any positive version, or update it with a greater version.
316
+ * Supplying the same definition and version is idempotent.
317
+ */
318
+ async ensureLens(options) {
319
+ if (!options?.identifier) throw invalidArgument("Lens identifier is required");
320
+ const [lens] = await this.ensureLenses({ lenses: [options] });
321
+ return lens;
322
+ }
323
+ /**
324
+ * Create or update several named lenses. New definitions are sent in one API request, or in
325
+ * consecutive requests of at most {@link ENSURE_LENSES_MAX_PER_REQUEST} definitions, in order.
326
+ * Each lens follows the same versioning and idempotency rules as ensureLens().
327
+ */
328
+ async ensureLenses({ lenses }) {
329
+ if (!Array.isArray(lenses) || lenses.length === 0) throw invalidArgument("At least one lens is required");
330
+ if (lenses.some((option) => !option?.identifier)) throw invalidArgument("Lens identifier is required");
331
+ const { ensuredLenses, pendingEnsureLenses } = this.#lenses;
332
+ const missingOptions = [];
333
+ const missingKeys = /* @__PURE__ */ new Set();
334
+ for (const option of lenses) {
335
+ const cacheKey = getEnsureLensCacheKey(option);
336
+ if (!ensuredLenses.has(cacheKey) && !missingKeys.has(cacheKey)) {
337
+ missingKeys.add(cacheKey);
338
+ missingOptions.push(option);
339
+ }
340
+ }
341
+ if (missingOptions.length > 0) {
342
+ const batchCacheKey = JSON.stringify([...missingKeys].sort());
343
+ let pending = pendingEnsureLenses.get(batchCacheKey);
344
+ if (!pending) {
345
+ pending = this.submitEnsureLenses(missingOptions);
346
+ pendingEnsureLenses.set(batchCacheKey, pending);
347
+ pending.then(() => pendingEnsureLenses.delete(batchCacheKey), () => pendingEnsureLenses.delete(batchCacheKey));
348
+ }
349
+ await pending;
350
+ }
351
+ return lenses.map((option) => {
352
+ const lens = ensuredLenses.get(getEnsureLensCacheKey(option));
353
+ if (!lens) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, { message: `CalmLens did not return lens "${option.identifier}"` });
354
+ return lens;
355
+ });
356
+ }
357
+ async submitEnsureLenses(options) {
358
+ for (let start = 0; start < options.length; start += 100) await this.submitEnsureLensesChunk(options.slice(start, start + 100));
359
+ }
360
+ async submitEnsureLensesChunk(options) {
361
+ const result = await this.request("PUT", `${this.projectPath}/lenses`, { body: { lenses: options } });
362
+ const returned = Array.isArray(result?.lenses) ? result.lenses : [];
363
+ if (returned.length !== options.length) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, { message: `Expected ${options.length} lenses but CalmLens returned ${returned.length}` });
364
+ const { ensuredLenses } = this.#lenses;
365
+ for (const [index, lens] of returned.entries()) {
366
+ const optionsForLens = options[index];
367
+ if (lens?.identifier !== optionsForLens.identifier) throw new CalmLensError(SDK_ERROR_CODES.INVALID_RESPONSE, { message: `Expected lens "${optionsForLens.identifier}" at position ${index}` });
368
+ for (const [cacheKey, cachedLens] of ensuredLenses) if (cachedLens.identifier === optionsForLens.identifier) ensuredLenses.delete(cacheKey);
369
+ ensuredLenses.set(getEnsureLensCacheKey(optionsForLens), lens);
370
+ }
371
+ }
372
+ };
373
+ //#endregion
374
+ export { CALMLENS_ERROR_CODES, CalmLensError, CalmLensServerClient, SDK_VERSION, WEBHOOK_DELIVERY_HEADER, WEBHOOK_SIGNATURE_HEADER, WEBHOOK_SIGNATURE_TOLERANCE_SECONDS, WEBHOOK_TIMESTAMP_HEADER, parseWebhookEvent, verifyWebhookSignature };