@simple-ai-lab/sdk 0.4.0 → 0.6.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.
Files changed (74) hide show
  1. package/README.md +54 -1
  2. package/dist/actions.cjs +438 -0
  3. package/dist/actions.d.cts +336 -0
  4. package/dist/actions.d.ts +336 -0
  5. package/dist/actions.js +429 -0
  6. package/dist/agents.cjs +1054 -0
  7. package/dist/agents.d.cts +1016 -0
  8. package/dist/agents.d.ts +1016 -0
  9. package/dist/agents.js +1044 -0
  10. package/dist/built-in-actions.cjs +356 -0
  11. package/dist/built-in-actions.d.cts +41 -0
  12. package/dist/built-in-actions.d.ts +41 -0
  13. package/dist/built-in-actions.js +353 -0
  14. package/dist/client.cjs +29 -0
  15. package/dist/client.d.cts +15 -0
  16. package/dist/client.d.ts +15 -0
  17. package/dist/client.js +25 -0
  18. package/dist/code-action/defaults.cjs +11 -0
  19. package/dist/code-action/defaults.d.cts +7 -0
  20. package/dist/code-action/defaults.d.ts +7 -0
  21. package/dist/code-action/defaults.js +8 -0
  22. package/dist/code-action/define-action.cjs +74 -0
  23. package/dist/code-action/define-action.d.cts +94 -0
  24. package/dist/code-action/define-action.d.ts +94 -0
  25. package/dist/code-action/define-action.js +69 -0
  26. package/dist/code-action/index.cjs +11 -0
  27. package/dist/code-action/index.d.cts +4 -0
  28. package/dist/code-action/index.d.ts +4 -0
  29. package/dist/code-action/index.js +3 -0
  30. package/dist/code-action/types.cjs +13 -0
  31. package/dist/code-action/types.d.cts +13 -0
  32. package/dist/code-action/types.d.ts +13 -0
  33. package/dist/code-action/types.js +10 -0
  34. package/dist/code-action/workflow.cjs +29 -0
  35. package/dist/code-action/workflow.d.cts +53 -0
  36. package/dist/code-action/workflow.d.ts +53 -0
  37. package/dist/code-action/workflow.js +26 -0
  38. package/dist/data.cjs +98 -0
  39. package/dist/data.d.cts +44 -0
  40. package/dist/data.d.ts +44 -0
  41. package/dist/data.js +94 -0
  42. package/dist/http.cjs +65 -0
  43. package/dist/http.d.cts +14 -0
  44. package/dist/http.d.ts +14 -0
  45. package/dist/http.js +62 -0
  46. package/dist/index.cjs +68 -1597
  47. package/dist/index.d.cts +12 -780
  48. package/dist/index.d.ts +12 -780
  49. package/dist/index.js +10 -1311
  50. package/dist/projects.cjs +234 -0
  51. package/dist/projects.d.cts +24 -0
  52. package/dist/projects.d.ts +24 -0
  53. package/dist/projects.js +228 -0
  54. package/dist/schemas.cjs +50 -0
  55. package/dist/schemas.d.cts +81 -0
  56. package/dist/schemas.d.ts +81 -0
  57. package/dist/schemas.js +47 -0
  58. package/dist/shared/errors.cjs +31 -0
  59. package/dist/shared/errors.d.cts +22 -0
  60. package/dist/shared/errors.d.ts +22 -0
  61. package/dist/shared/errors.js +26 -0
  62. package/package.json +27 -31
  63. package/dist/chunk-V4E5PSKB.js +0 -267
  64. package/dist/chunk-V4E5PSKB.js.map +0 -1
  65. package/dist/code-action-CDt77m7I.d.cts +0 -191
  66. package/dist/code-action-CDt77m7I.d.ts +0 -191
  67. package/dist/code-action.cjs +0 -282
  68. package/dist/code-action.cjs.map +0 -1
  69. package/dist/code-action.d.cts +0 -2
  70. package/dist/code-action.d.ts +0 -2
  71. package/dist/code-action.js +0 -9
  72. package/dist/code-action.js.map +0 -1
  73. package/dist/index.cjs.map +0 -1
  74. package/dist/index.js.map +0 -1
@@ -1,191 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
4
- type HttpClient = {
5
- request: (args: {
6
- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
7
- path: string;
8
- query?: Record<string, string>;
9
- body?: unknown;
10
- }) => Promise<unknown>;
11
- };
12
-
13
- /**
14
- * Request wire schemas for the Simple AI public REST API (`/api/v1`).
15
- *
16
- * These deliberately mirror the server's own schemas (see
17
- * `projects/server-v2/src/domains/data/query-schemas.ts` and
18
- * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two
19
- * in sync. Responses are typed but not strictly validated, so additive server
20
- * changes never break deployed SDK consumers.
21
- */
22
- /** Hard cap on hits a single query may return. */
23
- declare const MAX_QUERY_SIZE = 50;
24
- /** Maximum rows accepted by a single batch-upsert chunk. */
25
- declare const MAX_BATCH_ROWS = 1000;
26
- declare const tableNameSchema: z.ZodString;
27
- declare const dataColumnPathSchema: z.ZodString;
28
- declare const dataFilterSchema: z.ZodObject<{
29
- column: z.ZodString;
30
- values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
31
- }, z.core.$strip>;
32
- type DataFilter = z.infer<typeof dataFilterSchema>;
33
- declare const queryInputSchema: z.ZodObject<{
34
- tableName: z.ZodString;
35
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
36
- column: z.ZodString;
37
- values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
38
- }, z.core.$strip>>>;
39
- text: z.ZodOptional<z.ZodString>;
40
- size: z.ZodOptional<z.ZodNumber>;
41
- from: z.ZodOptional<z.ZodNumber>;
42
- }, z.core.$strip>;
43
- type QueryInput = z.input<typeof queryInputSchema>;
44
- declare const listOptionsSchema: z.ZodObject<{
45
- page: z.ZodOptional<z.ZodNumber>;
46
- perPage: z.ZodOptional<z.ZodNumber>;
47
- orderBy: z.ZodOptional<z.ZodString>;
48
- orderDirection: z.ZodOptional<z.ZodEnum<{
49
- asc: "asc";
50
- desc: "desc";
51
- }>>;
52
- filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
- }, z.core.$strip>;
54
- type ListOptions = z.input<typeof listOptionsSchema>;
55
- declare const recordPayloadSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
56
- type RecordPayload = z.infer<typeof recordPayloadSchema>;
57
- declare const batchUpsertRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
58
- type DataRecord = Record<string, unknown>;
59
- type QueryResult = {
60
- records: DataRecord[];
61
- total: number;
62
- };
63
- type ListResult = {
64
- records: DataRecord[];
65
- total_count: number;
66
- page: number;
67
- per_page: number;
68
- };
69
- type RecordResult = {
70
- record: DataRecord;
71
- };
72
- type DeleteResult = {
73
- success: boolean;
74
- message: string;
75
- };
76
- type BatchUpsertResult = {
77
- ingestBatchId: string;
78
- status: string;
79
- };
80
- type IngestBatchStatus = {
81
- id: string;
82
- tableName: string;
83
- status: string;
84
- rowCount: number;
85
- upsertedCount: number | null;
86
- errorMessage: string | null;
87
- createdAt: string;
88
- startedAt: string | null;
89
- finishedAt: string | null;
90
- };
91
- type FacetsResult = Record<string, unknown>;
92
-
93
- /**
94
- * Custom data tables — query, read, and write your organization's records.
95
- * Wraps the `/api/v1/data` REST endpoints.
96
- */
97
- declare class DataClient {
98
- #private;
99
- constructor(http: HttpClient);
100
- /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
101
- query<TRecord extends DataRecord = DataRecord>(input: QueryInput): Promise<{
102
- records: TRecord[];
103
- total: number;
104
- }>;
105
- /** Facet values for an indexed table. */
106
- facets(tableName: string): Promise<FacetsResult>;
107
- /** Paginated listing straight from the relational store. */
108
- list<TRecord extends DataRecord = DataRecord>(tableName: string, options?: ListOptions): Promise<{
109
- records: TRecord[];
110
- total_count: number;
111
- page: number;
112
- per_page: number;
113
- }>;
114
- get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{
115
- record: TRecord;
116
- }>;
117
- create<TRecord extends DataRecord = DataRecord>(tableName: string, payload: RecordPayload): Promise<{
118
- record: TRecord;
119
- }>;
120
- update<TRecord extends DataRecord = DataRecord>(tableName: string, id: number, payload: RecordPayload): Promise<{
121
- record: TRecord;
122
- }>;
123
- delete(tableName: string, id: number): Promise<DeleteResult>;
124
- /** Deletes every record in the table. Irreversible. */
125
- deleteAll(tableName: string): Promise<DeleteResult>;
126
- /**
127
- * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
128
- * REPLACE on key conflict — omitted columns are cleared, not preserved.
129
- * Returns a batch handle; poll `getBatch` for completion.
130
- */
131
- batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult>;
132
- /** Status of an async upsert batch created by `batchUpsert`. */
133
- getBatch(ingestBatchId: string): Promise<IngestBatchStatus>;
134
- }
135
-
136
- type SimpleAIOptions = {
137
- /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */
138
- apiKey?: string;
139
- /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */
140
- baseUrl?: string;
141
- /** Custom fetch implementation (for testing or instrumentation). */
142
- fetch?: FetchLike;
143
- };
144
- declare class SimpleAI {
145
- /** Custom data tables — query, read, and write records. */
146
- readonly data: DataClient;
147
- constructor(options?: SimpleAIOptions);
148
- }
149
-
150
- /**
151
- * Brand the code-action runner uses to recognize `defineAction` handlers. The
152
- * runner calls the default export with `{ inputs, config }` either way; the
153
- * wrapper adds the authenticated `client` to the handler's context.
154
- */
155
- declare const SIMPLE_ACTION_BRAND: unique symbol;
156
- declare const SIMPLE_ACTION_RUNTIME: unique symbol;
157
- type ActionRuntime = {
158
- apiKey: string;
159
- baseUrl: string;
160
- };
161
- type ActionContext<TInputs = Record<string, unknown>> = {
162
- /** The Action's declared inputs, already validated against its input schema. */
163
- inputs: TInputs;
164
- /** Your organization's configuration variables. */
165
- config: Record<string, string>;
166
- /** The Simple AI SDK, authenticated for your organization. */
167
- client: SimpleAI;
168
- };
169
- type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {
170
- inputs: TInputs;
171
- config: Record<string, string>;
172
- [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;
173
- }) => Promise<TResult>) & {
174
- [SIMPLE_ACTION_BRAND]: true;
175
- };
176
- /**
177
- * Define a code action with a typed context and an org-authenticated SDK
178
- * client. The returned value must be your module's default export.
179
- *
180
- * ```ts
181
- * import { defineAction } from '@simple-ai-lab/sdk';
182
- *
183
- * export default defineAction(async ({ inputs, config, client }) => {
184
- * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });
185
- * return { found: records.length > 0 };
186
- * });
187
- * ```
188
- */
189
- declare function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult): ActionHandler<TInputs, TResult>;
190
-
191
- export { type ActionContext as A, type BatchUpsertResult as B, DataClient as D, type FacetsResult as F, type IngestBatchStatus as I, type ListOptions as L, MAX_BATCH_ROWS as M, type QueryInput as Q, type RecordPayload as R, SIMPLE_ACTION_BRAND as S, type ActionHandler as a, type DataFilter as b, type DataRecord as c, type DeleteResult as d, type ListResult as e, MAX_QUERY_SIZE as f, type QueryResult as g, type RecordResult as h, SimpleAI as i, type SimpleAIOptions as j, batchUpsertRowsSchema as k, dataColumnPathSchema as l, dataFilterSchema as m, defineAction as n, listOptionsSchema as o, queryInputSchema as q, recordPayloadSchema as r, tableNameSchema as t };
@@ -1,191 +0,0 @@
1
- import { z } from 'zod';
2
-
3
- type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
4
- type HttpClient = {
5
- request: (args: {
6
- method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
7
- path: string;
8
- query?: Record<string, string>;
9
- body?: unknown;
10
- }) => Promise<unknown>;
11
- };
12
-
13
- /**
14
- * Request wire schemas for the Simple AI public REST API (`/api/v1`).
15
- *
16
- * These deliberately mirror the server's own schemas (see
17
- * `projects/server-v2/src/domains/data/query-schemas.ts` and
18
- * `domains/data/public/types.ts`); a contract test in server-v2 keeps the two
19
- * in sync. Responses are typed but not strictly validated, so additive server
20
- * changes never break deployed SDK consumers.
21
- */
22
- /** Hard cap on hits a single query may return. */
23
- declare const MAX_QUERY_SIZE = 50;
24
- /** Maximum rows accepted by a single batch-upsert chunk. */
25
- declare const MAX_BATCH_ROWS = 1000;
26
- declare const tableNameSchema: z.ZodString;
27
- declare const dataColumnPathSchema: z.ZodString;
28
- declare const dataFilterSchema: z.ZodObject<{
29
- column: z.ZodString;
30
- values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
31
- }, z.core.$strip>;
32
- type DataFilter = z.infer<typeof dataFilterSchema>;
33
- declare const queryInputSchema: z.ZodObject<{
34
- tableName: z.ZodString;
35
- filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
36
- column: z.ZodString;
37
- values: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>;
38
- }, z.core.$strip>>>;
39
- text: z.ZodOptional<z.ZodString>;
40
- size: z.ZodOptional<z.ZodNumber>;
41
- from: z.ZodOptional<z.ZodNumber>;
42
- }, z.core.$strip>;
43
- type QueryInput = z.input<typeof queryInputSchema>;
44
- declare const listOptionsSchema: z.ZodObject<{
45
- page: z.ZodOptional<z.ZodNumber>;
46
- perPage: z.ZodOptional<z.ZodNumber>;
47
- orderBy: z.ZodOptional<z.ZodString>;
48
- orderDirection: z.ZodOptional<z.ZodEnum<{
49
- asc: "asc";
50
- desc: "desc";
51
- }>>;
52
- filters: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
53
- }, z.core.$strip>;
54
- type ListOptions = z.input<typeof listOptionsSchema>;
55
- declare const recordPayloadSchema: z.ZodRecord<z.ZodString, z.ZodUnknown>;
56
- type RecordPayload = z.infer<typeof recordPayloadSchema>;
57
- declare const batchUpsertRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
58
- type DataRecord = Record<string, unknown>;
59
- type QueryResult = {
60
- records: DataRecord[];
61
- total: number;
62
- };
63
- type ListResult = {
64
- records: DataRecord[];
65
- total_count: number;
66
- page: number;
67
- per_page: number;
68
- };
69
- type RecordResult = {
70
- record: DataRecord;
71
- };
72
- type DeleteResult = {
73
- success: boolean;
74
- message: string;
75
- };
76
- type BatchUpsertResult = {
77
- ingestBatchId: string;
78
- status: string;
79
- };
80
- type IngestBatchStatus = {
81
- id: string;
82
- tableName: string;
83
- status: string;
84
- rowCount: number;
85
- upsertedCount: number | null;
86
- errorMessage: string | null;
87
- createdAt: string;
88
- startedAt: string | null;
89
- finishedAt: string | null;
90
- };
91
- type FacetsResult = Record<string, unknown>;
92
-
93
- /**
94
- * Custom data tables — query, read, and write your organization's records.
95
- * Wraps the `/api/v1/data` REST endpoints.
96
- */
97
- declare class DataClient {
98
- #private;
99
- constructor(http: HttpClient);
100
- /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
101
- query<TRecord extends DataRecord = DataRecord>(input: QueryInput): Promise<{
102
- records: TRecord[];
103
- total: number;
104
- }>;
105
- /** Facet values for an indexed table. */
106
- facets(tableName: string): Promise<FacetsResult>;
107
- /** Paginated listing straight from the relational store. */
108
- list<TRecord extends DataRecord = DataRecord>(tableName: string, options?: ListOptions): Promise<{
109
- records: TRecord[];
110
- total_count: number;
111
- page: number;
112
- per_page: number;
113
- }>;
114
- get<TRecord extends DataRecord = DataRecord>(tableName: string, id: number): Promise<{
115
- record: TRecord;
116
- }>;
117
- create<TRecord extends DataRecord = DataRecord>(tableName: string, payload: RecordPayload): Promise<{
118
- record: TRecord;
119
- }>;
120
- update<TRecord extends DataRecord = DataRecord>(tableName: string, id: number, payload: RecordPayload): Promise<{
121
- record: TRecord;
122
- }>;
123
- delete(tableName: string, id: number): Promise<DeleteResult>;
124
- /** Deletes every record in the table. Irreversible. */
125
- deleteAll(tableName: string): Promise<DeleteResult>;
126
- /**
127
- * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
128
- * REPLACE on key conflict — omitted columns are cleared, not preserved.
129
- * Returns a batch handle; poll `getBatch` for completion.
130
- */
131
- batchUpsert(tableName: string, rows: RecordPayload[]): Promise<BatchUpsertResult>;
132
- /** Status of an async upsert batch created by `batchUpsert`. */
133
- getBatch(ingestBatchId: string): Promise<IngestBatchStatus>;
134
- }
135
-
136
- type SimpleAIOptions = {
137
- /** API key (dashboard: Settings → API Keys). Defaults to SIMPLE_API_KEY — inside code actions this is injected automatically. */
138
- apiKey?: string;
139
- /** API base URL. Defaults to SIMPLE_BASE_URL, then the production API. */
140
- baseUrl?: string;
141
- /** Custom fetch implementation (for testing or instrumentation). */
142
- fetch?: FetchLike;
143
- };
144
- declare class SimpleAI {
145
- /** Custom data tables — query, read, and write records. */
146
- readonly data: DataClient;
147
- constructor(options?: SimpleAIOptions);
148
- }
149
-
150
- /**
151
- * Brand the code-action runner uses to recognize `defineAction` handlers. The
152
- * runner calls the default export with `{ inputs, config }` either way; the
153
- * wrapper adds the authenticated `client` to the handler's context.
154
- */
155
- declare const SIMPLE_ACTION_BRAND: unique symbol;
156
- declare const SIMPLE_ACTION_RUNTIME: unique symbol;
157
- type ActionRuntime = {
158
- apiKey: string;
159
- baseUrl: string;
160
- };
161
- type ActionContext<TInputs = Record<string, unknown>> = {
162
- /** The Action's declared inputs, already validated against its input schema. */
163
- inputs: TInputs;
164
- /** Your organization's configuration variables. */
165
- config: Record<string, string>;
166
- /** The Simple AI SDK, authenticated for your organization. */
167
- client: SimpleAI;
168
- };
169
- type ActionHandler<TInputs = Record<string, unknown>, TResult = unknown> = ((args: {
170
- inputs: TInputs;
171
- config: Record<string, string>;
172
- [SIMPLE_ACTION_RUNTIME]?: ActionRuntime;
173
- }) => Promise<TResult>) & {
174
- [SIMPLE_ACTION_BRAND]: true;
175
- };
176
- /**
177
- * Define a code action with a typed context and an org-authenticated SDK
178
- * client. The returned value must be your module's default export.
179
- *
180
- * ```ts
181
- * import { defineAction } from '@simple-ai-lab/sdk';
182
- *
183
- * export default defineAction(async ({ inputs, config, client }) => {
184
- * const { records } = await client.data.query({ tableName: 'customers', text: inputs.email });
185
- * return { found: records.length > 0 };
186
- * });
187
- * ```
188
- */
189
- declare function defineAction<TInputs = Record<string, unknown>, TResult = unknown>(handler: (context: ActionContext<TInputs>) => Promise<TResult> | TResult): ActionHandler<TInputs, TResult>;
190
-
191
- export { type ActionContext as A, type BatchUpsertResult as B, DataClient as D, type FacetsResult as F, type IngestBatchStatus as I, type ListOptions as L, MAX_BATCH_ROWS as M, type QueryInput as Q, type RecordPayload as R, SIMPLE_ACTION_BRAND as S, type ActionHandler as a, type DataFilter as b, type DataRecord as c, type DeleteResult as d, type ListResult as e, MAX_QUERY_SIZE as f, type QueryResult as g, type RecordResult as h, SimpleAI as i, type SimpleAIOptions as j, batchUpsertRowsSchema as k, dataColumnPathSchema as l, dataFilterSchema as m, defineAction as n, listOptionsSchema as o, queryInputSchema as q, recordPayloadSchema as r, tableNameSchema as t };
@@ -1,282 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/code-action.ts
21
- var code_action_exports = {};
22
- __export(code_action_exports, {
23
- SIMPLE_ACTION_BRAND: () => SIMPLE_ACTION_BRAND,
24
- defineAction: () => defineAction
25
- });
26
- module.exports = __toCommonJS(code_action_exports);
27
-
28
- // src/schemas.ts
29
- var import_zod = require("zod");
30
- var MAX_QUERY_SIZE = 50;
31
- var MAX_BATCH_ROWS = 1e3;
32
- var tableNameSchema = import_zod.z.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
33
- var filterValueSchema = import_zod.z.union([import_zod.z.string(), import_zod.z.number(), import_zod.z.boolean()]);
34
- var dataColumnPathSchema = import_zod.z.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
35
- message: "Must be a dot-separated column path with no empty segments"
36
- });
37
- var dataFilterSchema = import_zod.z.object({
38
- column: dataColumnPathSchema,
39
- values: import_zod.z.array(filterValueSchema)
40
- });
41
- var queryInputSchema = import_zod.z.object({
42
- tableName: tableNameSchema,
43
- filters: import_zod.z.array(dataFilterSchema).optional(),
44
- text: import_zod.z.string().max(5e3).optional(),
45
- size: import_zod.z.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
46
- from: import_zod.z.number().int().min(0).optional()
47
- });
48
- var listOptionsSchema = import_zod.z.object({
49
- page: import_zod.z.number().int().min(1).optional(),
50
- perPage: import_zod.z.number().int().min(1).max(200).optional(),
51
- orderBy: import_zod.z.string().optional(),
52
- orderDirection: import_zod.z.enum(["asc", "desc"]).optional(),
53
- /** Column-name → value equality filters applied server-side. */
54
- filters: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional()
55
- });
56
- var recordPayloadSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
57
- var batchUpsertRowsSchema = import_zod.z.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
58
-
59
- // src/data.ts
60
- function encodeTable(tableName) {
61
- return encodeURIComponent(tableNameSchema.parse(tableName));
62
- }
63
- var DataClient = class {
64
- #http;
65
- constructor(http) {
66
- this.#http = http;
67
- }
68
- /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
69
- async query(input) {
70
- const parsed = queryInputSchema.parse(input);
71
- const result = await this.#http.request({ method: "POST", path: "/data/query", body: parsed });
72
- return result;
73
- }
74
- /** Facet values for an indexed table. */
75
- async facets(tableName) {
76
- const result = await this.#http.request({ method: "GET", path: `/data/facets/${encodeTable(tableName)}` });
77
- return result;
78
- }
79
- /** Paginated listing straight from the relational store. */
80
- async list(tableName, options = {}) {
81
- const parsed = listOptionsSchema.parse(options);
82
- const query = { ...parsed.filters ?? {} };
83
- if (parsed.page !== void 0) {
84
- query.page = String(parsed.page);
85
- }
86
- if (parsed.perPage !== void 0) {
87
- query.per_page = String(parsed.perPage);
88
- }
89
- if (parsed.orderBy !== void 0) {
90
- query.order_by = parsed.orderBy;
91
- }
92
- if (parsed.orderDirection !== void 0) {
93
- query.order_direction = parsed.orderDirection;
94
- }
95
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}`, query });
96
- return result;
97
- }
98
- async get(tableName, id) {
99
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}/${id}` });
100
- return result;
101
- }
102
- async create(tableName, payload) {
103
- const result = await this.#http.request({
104
- method: "PUT",
105
- path: `/data/${encodeTable(tableName)}`,
106
- body: recordPayloadSchema.parse(payload)
107
- });
108
- return result;
109
- }
110
- async update(tableName, id, payload) {
111
- const result = await this.#http.request({
112
- method: "PATCH",
113
- path: `/data/${encodeTable(tableName)}/${id}`,
114
- body: recordPayloadSchema.parse(payload)
115
- });
116
- return result;
117
- }
118
- async delete(tableName, id) {
119
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}/${id}` });
120
- return result;
121
- }
122
- /** Deletes every record in the table. Irreversible. */
123
- async deleteAll(tableName) {
124
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}` });
125
- return result;
126
- }
127
- /**
128
- * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
129
- * REPLACE on key conflict — omitted columns are cleared, not preserved.
130
- * Returns a batch handle; poll `getBatch` for completion.
131
- */
132
- async batchUpsert(tableName, rows) {
133
- const result = await this.#http.request({
134
- method: "PUT",
135
- path: `/data/${encodeTable(tableName)}/batch`,
136
- body: { rows: batchUpsertRowsSchema.parse(rows) }
137
- });
138
- return result;
139
- }
140
- /** Status of an async upsert batch created by `batchUpsert`. */
141
- async getBatch(ingestBatchId) {
142
- const result = await this.#http.request({
143
- method: "GET",
144
- path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`
145
- });
146
- return result;
147
- }
148
- };
149
-
150
- // src/errors.ts
151
- var SimpleAIError = class extends Error {
152
- /** HTTP status code, or 0 when the request never reached the API. */
153
- status;
154
- /** Machine-readable error code from the API body, when present. */
155
- code;
156
- /** The parsed response body (JSON when possible, otherwise raw text). */
157
- body;
158
- constructor({
159
- message,
160
- status,
161
- code,
162
- body,
163
- cause
164
- }) {
165
- super(message, cause === void 0 ? void 0 : { cause });
166
- this.name = "SimpleAIError";
167
- this.status = status;
168
- this.code = code;
169
- this.body = body;
170
- }
171
- };
172
-
173
- // src/http.ts
174
- function parseBody(text) {
175
- if (text.length === 0) {
176
- return null;
177
- }
178
- try {
179
- return JSON.parse(text);
180
- } catch {
181
- return text;
182
- }
183
- }
184
- function errorDetails(body) {
185
- if (body !== null && typeof body === "object") {
186
- const record = body;
187
- const code = typeof record.code === "string" ? record.code : null;
188
- const message = typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : null;
189
- return { code, message };
190
- }
191
- return { code: null, message: typeof body === "string" && body.length > 0 ? body : null };
192
- }
193
- function createHttpClient({
194
- baseUrl,
195
- apiKey,
196
- fetchImplementation
197
- }) {
198
- const normalizedBase = baseUrl.replace(/\/+$/, "");
199
- return {
200
- request: async ({ method, path, query, body }) => {
201
- const queryString = query === void 0 || Object.keys(query).length === 0 ? "" : `?${new URLSearchParams(query).toString()}`;
202
- const url = `${normalizedBase}${path}${queryString}`;
203
- let response;
204
- try {
205
- response = await fetchImplementation(url, {
206
- method,
207
- headers: {
208
- authorization: `Bearer ${apiKey}`,
209
- "content-type": "application/json",
210
- accept: "application/json"
211
- },
212
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
213
- });
214
- } catch (e) {
215
- throw new SimpleAIError({
216
- message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
217
- status: 0,
218
- code: "network_error",
219
- body: null,
220
- cause: e
221
- });
222
- }
223
- const parsed = parseBody(await response.text());
224
- if (!response.ok) {
225
- const { code, message } = errorDetails(parsed);
226
- throw new SimpleAIError({
227
- message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,
228
- status: response.status,
229
- code,
230
- body: parsed
231
- });
232
- }
233
- return parsed;
234
- }
235
- };
236
- }
237
-
238
- // src/client.ts
239
- var DEFAULT_BASE_URL = "https://api.prod.usesimple.ai/api/v1";
240
- function envVar(name) {
241
- if (typeof process === "undefined" || process.env === void 0) {
242
- return void 0;
243
- }
244
- const value = process.env[name];
245
- return value === void 0 || value === "" ? void 0 : value;
246
- }
247
- var SimpleAI = class {
248
- /** Custom data tables — query, read, and write records. */
249
- data;
250
- constructor(options = {}) {
251
- const apiKey = options.apiKey ?? envVar("SIMPLE_API_KEY");
252
- if (apiKey === void 0) {
253
- throw new Error(
254
- "Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. Inside Simple AI code actions the key is injected automatically."
255
- );
256
- }
257
- const baseUrl = options.baseUrl ?? envVar("SIMPLE_BASE_URL") ?? DEFAULT_BASE_URL;
258
- const fetchImplementation = options.fetch ?? ((url, init) => fetch(url, init));
259
- const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });
260
- this.data = new DataClient(http);
261
- }
262
- };
263
-
264
- // src/define-action.ts
265
- var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
266
- var SIMPLE_ACTION_RUNTIME = /* @__PURE__ */ Symbol.for("simple-ai.action-runtime");
267
- function defineAction(handler) {
268
- const wrapped = async (invocation) => {
269
- const { inputs, config } = invocation;
270
- const runtime = invocation[SIMPLE_ACTION_RUNTIME];
271
- const client = runtime === void 0 ? new SimpleAI() : new SimpleAI(runtime);
272
- return handler({ inputs, config, client });
273
- };
274
- const brand = { [SIMPLE_ACTION_BRAND]: true };
275
- return Object.assign(wrapped, brand);
276
- }
277
- // Annotate the CommonJS export names for ESM import in node:
278
- 0 && (module.exports = {
279
- SIMPLE_ACTION_BRAND,
280
- defineAction
281
- });
282
- //# sourceMappingURL=code-action.cjs.map