@teamkeel/functions-runtime 0.428.2 → 0.429.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.
package/dist/index.d.cts CHANGED
@@ -157,6 +157,115 @@ declare class ModelAPI {
157
157
  where(where: any): QueryBuilder;
158
158
  }
159
159
 
160
+ /**
161
+ * TaskAPI provides methods for creating tasks via the HTTP API.
162
+ */
163
+ declare class TaskAPI {
164
+ /**
165
+ * @param {string} taskName The name of the task/topic
166
+ * @param {Object|null} identity Optional identity object for authentication
167
+ * @param {string|null} authToken Optional auth token for authentication
168
+ */
169
+ constructor(taskName: string, identity?: Object | null, authToken?: string | null);
170
+ _taskName: string;
171
+ _identity: Object | null;
172
+ _authToken: string | null;
173
+ /**
174
+ * Returns a new TaskAPI instance that will use the given identity for authentication.
175
+ * @param {Object} identity The identity object
176
+ * @returns {TaskAPI} A new TaskAPI instance with the identity set
177
+ */
178
+ withIdentity(identity: Object): TaskAPI;
179
+ /**
180
+ * Returns a new TaskAPI instance that will use the given auth token for authentication.
181
+ * @param {string} token The auth token to use
182
+ * @returns {TaskAPI} A new TaskAPI instance with the auth token set
183
+ */
184
+ withAuthToken(token: string): TaskAPI;
185
+ /**
186
+ * Creates a new task with the given data by calling the tasks API.
187
+ * @param {Object} data The task data fields
188
+ * @param {Object} options Optional settings like deferredUntil
189
+ * @returns {Promise<Task>} The created task
190
+ */
191
+ create(data?: Object, options?: Object): Promise<Task$1>;
192
+ }
193
+ /**
194
+ * Task represents a task instance with action methods.
195
+ */
196
+ declare class Task$1 {
197
+ /**
198
+ * @param {Object} data The task data from the API
199
+ * @param {string} taskName The name of the task/topic
200
+ * @param {Object|null} identity Optional identity object for authentication
201
+ * @param {string|null} authToken Optional auth token for authentication
202
+ */
203
+ constructor(data: Object, taskName: string, identity?: Object | null, authToken?: string | null);
204
+ id: any;
205
+ topic: any;
206
+ status: any;
207
+ deferredUntil: Date | undefined;
208
+ createdAt: Date;
209
+ updatedAt: Date;
210
+ assignedTo: any;
211
+ assignedAt: Date | undefined;
212
+ resolvedAt: Date | undefined;
213
+ flowRunId: any;
214
+ _taskName: string;
215
+ _identity: Object | null;
216
+ _authToken: string | null;
217
+ /**
218
+ * Returns a new Task instance that will use the given identity for authentication.
219
+ * @param {Object} identity The identity object
220
+ * @returns {Task} A new Task instance with the identity set
221
+ */
222
+ withIdentity(identity: Object): Task$1;
223
+ /**
224
+ * Returns a new Task instance that will use the given auth token for authentication.
225
+ * @param {string} token The auth token to use
226
+ * @returns {Task} A new Task instance with the auth token set
227
+ */
228
+ withAuthToken(token: string): Task$1;
229
+ /**
230
+ * Converts the task back to API data format for creating new instances.
231
+ * @returns {Object} The task data in API format
232
+ */
233
+ _toApiData(): Object;
234
+ /**
235
+ * Assigns the task to an identity.
236
+ * @param {Object} options Options containing identityId
237
+ * @param {string} options.identityId The ID of the identity to assign the task to
238
+ * @returns {Promise<Task>} The updated task
239
+ */
240
+ assign({ identityId }: {
241
+ identityId: string;
242
+ }): Promise<Task$1>;
243
+ /**
244
+ * Starts the task, creating and running the associated flow.
245
+ * @returns {Promise<Task>} The updated task with flowRunId
246
+ */
247
+ start(): Promise<Task$1>;
248
+ /**
249
+ * Completes the task.
250
+ * @returns {Promise<Task>} The updated task
251
+ */
252
+ complete(): Promise<Task$1>;
253
+ /**
254
+ * Defers the task until a specified date.
255
+ * @param {Object} options Options containing deferUntil
256
+ * @param {Date} options.deferUntil The date to defer the task until
257
+ * @returns {Promise<Task>} The updated task
258
+ */
259
+ defer({ deferUntil }: {
260
+ deferUntil: Date;
261
+ }): Promise<Task$1>;
262
+ /**
263
+ * Cancels the task.
264
+ * @returns {Promise<Task>} The updated task
265
+ */
266
+ cancel(): Promise<Task$1>;
267
+ }
268
+
160
269
  interface RequestHeadersMap {
161
270
  [key: string]: string;
162
271
  }
@@ -1266,5 +1375,21 @@ type RelativeDateString = "now" | "today" | "tomorrow" | "yesterday" | `this ${u
1266
1375
  type dateDuration = `${number}Y${number}M${number}D` | `${number}Y${number}M` | `${number}Y${number}D` | `${number}M${number}D` | `${number}Y` | `${number}M` | `${number}D`;
1267
1376
  type timeDuration = `${number}H${number}M${number}S` | `${number}H${number}M` | `${number}M${number}S` | `${number}H${number}S` | `${number}H` | `${number}M` | `${number}S`;
1268
1377
  type DurationString = `P${dateDuration}T${timeDuration}` | `P${dateDuration}` | `PT${timeDuration}`;
1378
+ type TaskStatus = "NEW" | "ASSIGNED" | "STARTED" | "COMPLETED" | "CANCELLED" | "DEFERRED";
1379
+ type Task = {
1380
+ id: string;
1381
+ topic: string;
1382
+ status: TaskStatus;
1383
+ deferredUntil?: Date;
1384
+ createdAt: Date;
1385
+ updatedAt: Date;
1386
+ assignedTo?: string;
1387
+ assignedAt?: Date;
1388
+ resolvedAt?: Date;
1389
+ flowRunId?: string;
1390
+ };
1391
+ type TaskCreateOptions = {
1392
+ deferredUntil?: Date;
1393
+ };
1269
1394
 
1270
- export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, ModelAPI, NonRetriableError, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, Permissions, type Printer, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type TimestampQueryInput, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, ksuid, tracing, useDatabase };
1395
+ export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, ModelAPI, NonRetriableError, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, Permissions, type Printer, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type Task, TaskAPI, type TaskCreateOptions, type TaskStatus, type TimestampQueryInput, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, ksuid, tracing, useDatabase };
package/dist/index.d.ts CHANGED
@@ -157,6 +157,115 @@ declare class ModelAPI {
157
157
  where(where: any): QueryBuilder;
158
158
  }
159
159
 
160
+ /**
161
+ * TaskAPI provides methods for creating tasks via the HTTP API.
162
+ */
163
+ declare class TaskAPI {
164
+ /**
165
+ * @param {string} taskName The name of the task/topic
166
+ * @param {Object|null} identity Optional identity object for authentication
167
+ * @param {string|null} authToken Optional auth token for authentication
168
+ */
169
+ constructor(taskName: string, identity?: Object | null, authToken?: string | null);
170
+ _taskName: string;
171
+ _identity: Object | null;
172
+ _authToken: string | null;
173
+ /**
174
+ * Returns a new TaskAPI instance that will use the given identity for authentication.
175
+ * @param {Object} identity The identity object
176
+ * @returns {TaskAPI} A new TaskAPI instance with the identity set
177
+ */
178
+ withIdentity(identity: Object): TaskAPI;
179
+ /**
180
+ * Returns a new TaskAPI instance that will use the given auth token for authentication.
181
+ * @param {string} token The auth token to use
182
+ * @returns {TaskAPI} A new TaskAPI instance with the auth token set
183
+ */
184
+ withAuthToken(token: string): TaskAPI;
185
+ /**
186
+ * Creates a new task with the given data by calling the tasks API.
187
+ * @param {Object} data The task data fields
188
+ * @param {Object} options Optional settings like deferredUntil
189
+ * @returns {Promise<Task>} The created task
190
+ */
191
+ create(data?: Object, options?: Object): Promise<Task$1>;
192
+ }
193
+ /**
194
+ * Task represents a task instance with action methods.
195
+ */
196
+ declare class Task$1 {
197
+ /**
198
+ * @param {Object} data The task data from the API
199
+ * @param {string} taskName The name of the task/topic
200
+ * @param {Object|null} identity Optional identity object for authentication
201
+ * @param {string|null} authToken Optional auth token for authentication
202
+ */
203
+ constructor(data: Object, taskName: string, identity?: Object | null, authToken?: string | null);
204
+ id: any;
205
+ topic: any;
206
+ status: any;
207
+ deferredUntil: Date | undefined;
208
+ createdAt: Date;
209
+ updatedAt: Date;
210
+ assignedTo: any;
211
+ assignedAt: Date | undefined;
212
+ resolvedAt: Date | undefined;
213
+ flowRunId: any;
214
+ _taskName: string;
215
+ _identity: Object | null;
216
+ _authToken: string | null;
217
+ /**
218
+ * Returns a new Task instance that will use the given identity for authentication.
219
+ * @param {Object} identity The identity object
220
+ * @returns {Task} A new Task instance with the identity set
221
+ */
222
+ withIdentity(identity: Object): Task$1;
223
+ /**
224
+ * Returns a new Task instance that will use the given auth token for authentication.
225
+ * @param {string} token The auth token to use
226
+ * @returns {Task} A new Task instance with the auth token set
227
+ */
228
+ withAuthToken(token: string): Task$1;
229
+ /**
230
+ * Converts the task back to API data format for creating new instances.
231
+ * @returns {Object} The task data in API format
232
+ */
233
+ _toApiData(): Object;
234
+ /**
235
+ * Assigns the task to an identity.
236
+ * @param {Object} options Options containing identityId
237
+ * @param {string} options.identityId The ID of the identity to assign the task to
238
+ * @returns {Promise<Task>} The updated task
239
+ */
240
+ assign({ identityId }: {
241
+ identityId: string;
242
+ }): Promise<Task$1>;
243
+ /**
244
+ * Starts the task, creating and running the associated flow.
245
+ * @returns {Promise<Task>} The updated task with flowRunId
246
+ */
247
+ start(): Promise<Task$1>;
248
+ /**
249
+ * Completes the task.
250
+ * @returns {Promise<Task>} The updated task
251
+ */
252
+ complete(): Promise<Task$1>;
253
+ /**
254
+ * Defers the task until a specified date.
255
+ * @param {Object} options Options containing deferUntil
256
+ * @param {Date} options.deferUntil The date to defer the task until
257
+ * @returns {Promise<Task>} The updated task
258
+ */
259
+ defer({ deferUntil }: {
260
+ deferUntil: Date;
261
+ }): Promise<Task$1>;
262
+ /**
263
+ * Cancels the task.
264
+ * @returns {Promise<Task>} The updated task
265
+ */
266
+ cancel(): Promise<Task$1>;
267
+ }
268
+
160
269
  interface RequestHeadersMap {
161
270
  [key: string]: string;
162
271
  }
@@ -1266,5 +1375,21 @@ type RelativeDateString = "now" | "today" | "tomorrow" | "yesterday" | `this ${u
1266
1375
  type dateDuration = `${number}Y${number}M${number}D` | `${number}Y${number}M` | `${number}Y${number}D` | `${number}M${number}D` | `${number}Y` | `${number}M` | `${number}D`;
1267
1376
  type timeDuration = `${number}H${number}M${number}S` | `${number}H${number}M` | `${number}M${number}S` | `${number}H${number}S` | `${number}H` | `${number}M` | `${number}S`;
1268
1377
  type DurationString = `P${dateDuration}T${timeDuration}` | `P${dateDuration}` | `PT${timeDuration}`;
1378
+ type TaskStatus = "NEW" | "ASSIGNED" | "STARTED" | "COMPLETED" | "CANCELLED" | "DEFERRED";
1379
+ type Task = {
1380
+ id: string;
1381
+ topic: string;
1382
+ status: TaskStatus;
1383
+ deferredUntil?: Date;
1384
+ createdAt: Date;
1385
+ updatedAt: Date;
1386
+ assignedTo?: string;
1387
+ assignedAt?: Date;
1388
+ resolvedAt?: Date;
1389
+ flowRunId?: string;
1390
+ };
1391
+ type TaskCreateOptions = {
1392
+ deferredUntil?: Date;
1393
+ };
1269
1394
 
1270
- export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, ModelAPI, NonRetriableError, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, Permissions, type Printer, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type TimestampQueryInput, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, ksuid, tracing, useDatabase };
1395
+ export { type BooleanArrayQueryWhereCondition, type BooleanArrayWhereCondition, type BooleanWhereCondition, type ContextAPI, type DateArrayQueryWhereCondition, type DateArrayWhereCondition, type DateQueryInput, type DateWhereCondition, Duration, type DurationString, type DurationWhereCondition, ErrorPresets, type Errors, type ExtractStageKeys, File, type FlowConfig, type FlowConfigAPI, type FlowContext, type FlowFunction, type FuncWithConfig, type FunctionConfig, type Hardware, type IDWhereCondition, InlineFile, ModelAPI, NonRetriableError, type NullableHardware, type NumberArrayQueryWhereCondition, type NumberArrayWhereCondition, type NumberWhereCondition, PERMISSION_STATE, type PageInfo, Permissions, type Printer, type RelativeDateString, RequestHeaders, type Response, RetryBackoffExponential, RetryBackoffLinear, RetryConstant, STEP_STATUS, STEP_TYPE, type SortDirection, type Step, type StringArrayQueryWhereCondition, type StringArrayWhereCondition, type StringWhereCondition, type Task, TaskAPI, type TaskCreateOptions, type TaskStatus, type TimestampQueryInput, type UI, type UIApiResponses, checkBuiltInPermissions, createFlowContext, handleFlow, handleJob, handleRequest, handleRoute, handleSubscriber, ksuid, tracing, useDatabase };
package/dist/index.js CHANGED
@@ -798,24 +798,34 @@ async function storeFile(contents, key, filename, contentType, size, expires) {
798
798
  __name(storeFile, "storeFile");
799
799
 
800
800
  // src/parsing.js
801
+ var dateFormat = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)?$/;
801
802
  function parseInputs(inputs) {
802
803
  if (inputs != null && typeof inputs === "object") {
803
804
  for (const k of Object.keys(inputs)) {
804
- if (inputs[k] !== null && typeof inputs[k] === "object") {
805
- if (Array.isArray(inputs[k])) {
806
- inputs[k] = inputs[k].map((item) => {
805
+ const value = inputs[k];
806
+ if (value === null) {
807
+ continue;
808
+ }
809
+ if (typeof value === "string" && dateFormat.test(value)) {
810
+ inputs[k] = new Date(value);
811
+ } else if (typeof value === "object") {
812
+ if (Array.isArray(value)) {
813
+ inputs[k] = value.map((item) => {
807
814
  if (item && typeof item === "object") {
808
815
  if ("__typename" in item) {
809
816
  return parseComplexInputType(item);
810
817
  }
811
818
  return parseInputs(item);
812
819
  }
820
+ if (typeof item === "string" && dateFormat.test(item)) {
821
+ return new Date(item);
822
+ }
813
823
  return item;
814
824
  });
815
- } else if ("__typename" in inputs[k]) {
816
- inputs[k] = parseComplexInputType(inputs[k]);
825
+ } else if ("__typename" in value) {
826
+ inputs[k] = parseComplexInputType(value);
817
827
  } else {
818
- inputs[k] = parseInputs(inputs[k]);
828
+ inputs[k] = parseInputs(value);
819
829
  }
820
830
  }
821
831
  }
@@ -1750,6 +1760,284 @@ async function create(conn, tableName, tableConfigs, values) {
1750
1760
  }
1751
1761
  __name(create, "create");
1752
1762
 
1763
+ // src/TaskAPI.js
1764
+ import jwt from "jsonwebtoken";
1765
+ function buildHeaders(identity, authToken) {
1766
+ const headers = { "Content-Type": "application/json" };
1767
+ if (identity !== null) {
1768
+ const base64pk = process.env.KEEL_PRIVATE_KEY;
1769
+ let privateKey = void 0;
1770
+ if (base64pk) {
1771
+ privateKey = Buffer.from(base64pk, "base64").toString("utf8");
1772
+ }
1773
+ headers["Authorization"] = "Bearer " + jwt.sign({}, privateKey, {
1774
+ algorithm: privateKey ? "RS256" : "none",
1775
+ expiresIn: 60 * 60 * 24,
1776
+ subject: identity.id,
1777
+ issuer: "https://keel.so"
1778
+ });
1779
+ }
1780
+ if (authToken !== null) {
1781
+ headers["Authorization"] = "Bearer " + authToken;
1782
+ }
1783
+ return headers;
1784
+ }
1785
+ __name(buildHeaders, "buildHeaders");
1786
+ function getApiUrl() {
1787
+ const apiUrl = process.env.KEEL_API_URL;
1788
+ if (!apiUrl) {
1789
+ throw new Error("KEEL_API_URL environment variable is not set");
1790
+ }
1791
+ return apiUrl;
1792
+ }
1793
+ __name(getApiUrl, "getApiUrl");
1794
+ var Task = class _Task {
1795
+ static {
1796
+ __name(this, "Task");
1797
+ }
1798
+ /**
1799
+ * @param {Object} data The task data from the API
1800
+ * @param {string} taskName The name of the task/topic
1801
+ * @param {Object|null} identity Optional identity object for authentication
1802
+ * @param {string|null} authToken Optional auth token for authentication
1803
+ */
1804
+ constructor(data, taskName, identity = null, authToken = null) {
1805
+ this.id = data.id;
1806
+ this.topic = data.name;
1807
+ this.status = data.status;
1808
+ this.deferredUntil = data.deferredUntil ? new Date(data.deferredUntil) : void 0;
1809
+ this.createdAt = new Date(data.createdAt);
1810
+ this.updatedAt = new Date(data.updatedAt);
1811
+ this.assignedTo = data.assignedTo;
1812
+ this.assignedAt = data.assignedAt ? new Date(data.assignedAt) : void 0;
1813
+ this.resolvedAt = data.resolvedAt ? new Date(data.resolvedAt) : void 0;
1814
+ this.flowRunId = data.flowRunId;
1815
+ this._taskName = taskName;
1816
+ this._identity = identity;
1817
+ this._authToken = authToken;
1818
+ }
1819
+ /**
1820
+ * Returns a new Task instance that will use the given identity for authentication.
1821
+ * @param {Object} identity The identity object
1822
+ * @returns {Task} A new Task instance with the identity set
1823
+ */
1824
+ withIdentity(identity) {
1825
+ const data = this._toApiData();
1826
+ return new _Task(data, this._taskName, identity, null);
1827
+ }
1828
+ /**
1829
+ * Returns a new Task instance that will use the given auth token for authentication.
1830
+ * @param {string} token The auth token to use
1831
+ * @returns {Task} A new Task instance with the auth token set
1832
+ */
1833
+ withAuthToken(token) {
1834
+ const data = this._toApiData();
1835
+ return new _Task(data, this._taskName, null, token);
1836
+ }
1837
+ /**
1838
+ * Converts the task back to API data format for creating new instances.
1839
+ * @returns {Object} The task data in API format
1840
+ */
1841
+ _toApiData() {
1842
+ return {
1843
+ id: this.id,
1844
+ name: this.topic,
1845
+ status: this.status,
1846
+ deferredUntil: this.deferredUntil?.toISOString(),
1847
+ createdAt: this.createdAt.toISOString(),
1848
+ updatedAt: this.updatedAt.toISOString(),
1849
+ assignedTo: this.assignedTo,
1850
+ assignedAt: this.assignedAt?.toISOString(),
1851
+ resolvedAt: this.resolvedAt?.toISOString(),
1852
+ flowRunId: this.flowRunId
1853
+ };
1854
+ }
1855
+ /**
1856
+ * Assigns the task to an identity.
1857
+ * @param {Object} options Options containing identityId
1858
+ * @param {string} options.identityId The ID of the identity to assign the task to
1859
+ * @returns {Promise<Task>} The updated task
1860
+ */
1861
+ async assign({ identityId }) {
1862
+ const name = spanNameForModelAPI(this._taskName, "assign");
1863
+ return withSpan(name, async () => {
1864
+ const apiUrl = getApiUrl();
1865
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/assign`;
1866
+ const response = await fetch(url, {
1867
+ method: "PUT",
1868
+ headers: buildHeaders(this._identity, this._authToken),
1869
+ body: JSON.stringify({ assigned_to: identityId })
1870
+ });
1871
+ if (!response.ok) {
1872
+ const errorBody = await response.json().catch(() => ({}));
1873
+ throw new Error(
1874
+ `Failed to assign task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
1875
+ );
1876
+ }
1877
+ const result = await response.json();
1878
+ return new _Task(result, this._taskName, this._identity, this._authToken);
1879
+ });
1880
+ }
1881
+ /**
1882
+ * Starts the task, creating and running the associated flow.
1883
+ * @returns {Promise<Task>} The updated task with flowRunId
1884
+ */
1885
+ async start() {
1886
+ const name = spanNameForModelAPI(this._taskName, "start");
1887
+ return withSpan(name, async () => {
1888
+ const apiUrl = getApiUrl();
1889
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/start`;
1890
+ const response = await fetch(url, {
1891
+ method: "PUT",
1892
+ headers: buildHeaders(this._identity, this._authToken)
1893
+ });
1894
+ if (!response.ok) {
1895
+ const errorBody = await response.json().catch(() => ({}));
1896
+ throw new Error(
1897
+ `Failed to start task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
1898
+ );
1899
+ }
1900
+ const result = await response.json();
1901
+ return new _Task(result, this._taskName, this._identity, this._authToken);
1902
+ });
1903
+ }
1904
+ /**
1905
+ * Completes the task.
1906
+ * @returns {Promise<Task>} The updated task
1907
+ */
1908
+ async complete() {
1909
+ const name = spanNameForModelAPI(this._taskName, "complete");
1910
+ return withSpan(name, async () => {
1911
+ const apiUrl = getApiUrl();
1912
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/complete`;
1913
+ const response = await fetch(url, {
1914
+ method: "PUT",
1915
+ headers: buildHeaders(this._identity, this._authToken)
1916
+ });
1917
+ if (!response.ok) {
1918
+ const errorBody = await response.json().catch(() => ({}));
1919
+ throw new Error(
1920
+ `Failed to complete task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
1921
+ );
1922
+ }
1923
+ const result = await response.json();
1924
+ return new _Task(result, this._taskName, this._identity, this._authToken);
1925
+ });
1926
+ }
1927
+ /**
1928
+ * Defers the task until a specified date.
1929
+ * @param {Object} options Options containing deferUntil
1930
+ * @param {Date} options.deferUntil The date to defer the task until
1931
+ * @returns {Promise<Task>} The updated task
1932
+ */
1933
+ async defer({ deferUntil }) {
1934
+ const name = spanNameForModelAPI(this._taskName, "defer");
1935
+ return withSpan(name, async () => {
1936
+ const apiUrl = getApiUrl();
1937
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/defer`;
1938
+ const response = await fetch(url, {
1939
+ method: "PUT",
1940
+ headers: buildHeaders(this._identity, this._authToken),
1941
+ body: JSON.stringify({ defer_until: deferUntil.toISOString() })
1942
+ });
1943
+ if (!response.ok) {
1944
+ const errorBody = await response.json().catch(() => ({}));
1945
+ throw new Error(
1946
+ `Failed to defer task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
1947
+ );
1948
+ }
1949
+ const result = await response.json();
1950
+ return new _Task(result, this._taskName, this._identity, this._authToken);
1951
+ });
1952
+ }
1953
+ /**
1954
+ * Cancels the task.
1955
+ * @returns {Promise<Task>} The updated task
1956
+ */
1957
+ async cancel() {
1958
+ const name = spanNameForModelAPI(this._taskName, "cancel");
1959
+ return withSpan(name, async () => {
1960
+ const apiUrl = getApiUrl();
1961
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks/${this.id}/cancel`;
1962
+ const response = await fetch(url, {
1963
+ method: "PUT",
1964
+ headers: buildHeaders(this._identity, this._authToken)
1965
+ });
1966
+ if (!response.ok) {
1967
+ const errorBody = await response.json().catch(() => ({}));
1968
+ throw new Error(
1969
+ `Failed to cancel task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
1970
+ );
1971
+ }
1972
+ const result = await response.json();
1973
+ return new _Task(result, this._taskName, this._identity, this._authToken);
1974
+ });
1975
+ }
1976
+ };
1977
+ var TaskAPI = class _TaskAPI {
1978
+ static {
1979
+ __name(this, "TaskAPI");
1980
+ }
1981
+ /**
1982
+ * @param {string} taskName The name of the task/topic
1983
+ * @param {Object|null} identity Optional identity object for authentication
1984
+ * @param {string|null} authToken Optional auth token for authentication
1985
+ */
1986
+ constructor(taskName, identity = null, authToken = null) {
1987
+ this._taskName = taskName;
1988
+ this._identity = identity;
1989
+ this._authToken = authToken;
1990
+ }
1991
+ /**
1992
+ * Returns a new TaskAPI instance that will use the given identity for authentication.
1993
+ * @param {Object} identity The identity object
1994
+ * @returns {TaskAPI} A new TaskAPI instance with the identity set
1995
+ */
1996
+ withIdentity(identity) {
1997
+ return new _TaskAPI(this._taskName, identity, null);
1998
+ }
1999
+ /**
2000
+ * Returns a new TaskAPI instance that will use the given auth token for authentication.
2001
+ * @param {string} token The auth token to use
2002
+ * @returns {TaskAPI} A new TaskAPI instance with the auth token set
2003
+ */
2004
+ withAuthToken(token) {
2005
+ return new _TaskAPI(this._taskName, null, token);
2006
+ }
2007
+ /**
2008
+ * Creates a new task with the given data by calling the tasks API.
2009
+ * @param {Object} data The task data fields
2010
+ * @param {Object} options Optional settings like deferredUntil
2011
+ * @returns {Promise<Task>} The created task
2012
+ */
2013
+ async create(data = {}, options = {}) {
2014
+ const name = spanNameForModelAPI(this._taskName, "create");
2015
+ return withSpan(name, async () => {
2016
+ const apiUrl = getApiUrl();
2017
+ const url = `${apiUrl}/topics/json/${this._taskName}/tasks`;
2018
+ const body = {
2019
+ data
2020
+ };
2021
+ if (options.deferredUntil) {
2022
+ body.defer_until = options.deferredUntil.toISOString();
2023
+ }
2024
+ const response = await fetch(url, {
2025
+ method: "POST",
2026
+ headers: buildHeaders(this._identity, this._authToken),
2027
+ body: JSON.stringify(body)
2028
+ });
2029
+ if (!response.ok) {
2030
+ const errorBody = await response.json().catch(() => ({}));
2031
+ throw new Error(
2032
+ `Failed to create task: ${response.status} ${response.statusText} - ${errorBody.message || JSON.stringify(errorBody)}`
2033
+ );
2034
+ }
2035
+ const result = await response.json();
2036
+ return new Task(result, this._taskName, this._identity, this._authToken);
2037
+ });
2038
+ }
2039
+ };
2040
+
1753
2041
  // src/RequestHeaders.ts
1754
2042
  var RequestHeaders = class {
1755
2043
  /**
@@ -3561,6 +3849,7 @@ export {
3561
3849
  RetryConstant,
3562
3850
  STEP_STATUS,
3563
3851
  STEP_TYPE,
3852
+ TaskAPI,
3564
3853
  checkBuiltInPermissions,
3565
3854
  createFlowContext,
3566
3855
  handleFlow,