@limai.io/cli 0.1.1 → 0.4.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.ts CHANGED
@@ -53,6 +53,46 @@ type JobStatus = {
53
53
  confidenceStageStatus?: StageStatus;
54
54
  bboxStageStatus?: StageStatus;
55
55
  };
56
+ type IncludeOption = "confidence" | "boundingBoxes" | "validations";
57
+ type CellConfidence = {
58
+ overall: number | null;
59
+ llm: number | null;
60
+ layout: number | null;
61
+ consensus: number | null;
62
+ };
63
+ type CellBoundingBox = {
64
+ page: string;
65
+ bbox: [number, number, number, number];
66
+ };
67
+ type CellValidation = {
68
+ checkKey: string | null;
69
+ source: "RULE" | "SCRIPT" | "AGENT";
70
+ passed: boolean;
71
+ message: string | null;
72
+ expected: string | null;
73
+ actual: string | null;
74
+ amended: boolean;
75
+ };
76
+ type FileValidationCheck = {
77
+ key: string;
78
+ name: string;
79
+ source: "STATIC" | "AGENT";
80
+ status: "PENDING" | "RUNNING" | "PASSED" | "FAILED" | "RESEND_PASSED" | "RESEND_FAILED" | "ERROR";
81
+ behavior: "SURFACE" | "RESEND";
82
+ findings: unknown[] | null;
83
+ errorMessage: string | null;
84
+ startedAt: string | null;
85
+ completedAt: string | null;
86
+ };
87
+ type FileValidations = {
88
+ failCount: number | null;
89
+ checks: FileValidationCheck[];
90
+ rules: {
91
+ crossField: unknown[];
92
+ row: unknown[];
93
+ document: unknown[];
94
+ } | null;
95
+ };
56
96
  type CellValue = {
57
97
  value: string | number | boolean | null;
58
98
  columnId: string;
@@ -60,7 +100,11 @@ type CellValue = {
60
100
  id: string;
61
101
  type: string;
62
102
  description?: string;
103
+ slug?: string | null;
63
104
  };
105
+ confidence?: CellConfidence;
106
+ boundingBoxes?: CellBoundingBox[] | null;
107
+ validations?: CellValidation[];
64
108
  };
65
109
  type Row = {
66
110
  id: string;
@@ -72,6 +116,7 @@ type Row = {
72
116
  type Column = {
73
117
  id: string;
74
118
  name: string;
119
+ slug?: string | null;
75
120
  type: string;
76
121
  description?: string;
77
122
  sharedColumnId?: string;
@@ -79,6 +124,7 @@ type Column = {
79
124
  type TableData = {
80
125
  id: string;
81
126
  name: string;
127
+ slug?: string | null;
82
128
  columns: Column[];
83
129
  rows: Row[];
84
130
  };
@@ -96,6 +142,81 @@ type FileData = {
96
142
  data?: {
97
143
  tables: Record<string, TableData>;
98
144
  };
145
+ validations?: FileValidations;
146
+ error?: string;
147
+ };
148
+ type BulkFileResult = {
149
+ status: "COMPLETED" | "PROCESSING" | "FAILED" | "CLASSIFYING" | "NOT_FOUND";
150
+ fileId: string;
151
+ extractionSchemaId?: string;
152
+ deployment?: {
153
+ id: string;
154
+ name: string;
155
+ };
156
+ jobId?: string;
157
+ errorMessage?: string;
158
+ data?: {
159
+ tables: Record<string, TableData>;
160
+ };
161
+ validations?: FileValidations;
162
+ };
163
+ type BulkGetFilesDataResponse = {
164
+ results: Record<string, BulkFileResult>;
165
+ summary: {
166
+ completed: number;
167
+ processing: number;
168
+ failed: number;
169
+ classifying: number;
170
+ not_found: number;
171
+ total: number;
172
+ };
173
+ };
174
+ type FlatCellValidation = {
175
+ check: string | null;
176
+ source: "RULE" | "SCRIPT" | "AGENT";
177
+ passed: boolean;
178
+ message: string | null;
179
+ };
180
+ type FlatCellData = {
181
+ value: string | number | boolean | null;
182
+ confidence?: number | null;
183
+ boundingBoxes?: CellBoundingBox[] | null;
184
+ validations?: FlatCellValidation[];
185
+ };
186
+ type FlatRow = {
187
+ $id: string;
188
+ $index: string;
189
+ } & Record<string, unknown>;
190
+ type FlatFileValidations = {
191
+ failCount: number | null;
192
+ checks: {
193
+ key: string;
194
+ source: "STATIC" | "AGENT";
195
+ status: string;
196
+ passed: boolean | null;
197
+ message: string | null;
198
+ }[];
199
+ };
200
+ type FlatDocumentDataResponse = {
201
+ fileId?: string;
202
+ status?: "COMPLETED" | "PROCESSING" | "FAILED";
203
+ jobId?: string;
204
+ errorMessage?: string;
205
+ data?: Record<string, FlatRow[]>;
206
+ validations?: FlatFileValidations;
207
+ error?: string;
208
+ };
209
+ type FlatDocumentEntry = {
210
+ fileId: string;
211
+ status: "COMPLETED" | "PROCESSING" | "FAILED";
212
+ jobId?: string;
213
+ errorMessage?: string;
214
+ data?: Record<string, FlatRow[]>;
215
+ validations?: FlatFileValidations;
216
+ };
217
+ type BulkFlatDocumentDataResponse = {
218
+ documents?: FlatDocumentEntry[];
219
+ missing?: string[];
99
220
  error?: string;
100
221
  };
101
222
  type OffsetPagination = {
@@ -238,6 +359,7 @@ type ProcessOptions = {
238
359
  type Table = {
239
360
  id: string;
240
361
  name: string;
362
+ slug?: string | null;
241
363
  deploymentId: string;
242
364
  parentTableId?: string;
243
365
  columns: Column[];
@@ -256,6 +378,7 @@ type ExtractionSchema = {
256
378
  type JobContextColumn = {
257
379
  id: string;
258
380
  name: string;
381
+ slug?: string | null;
259
382
  type: string;
260
383
  description?: string;
261
384
  isList: boolean;
@@ -263,6 +386,7 @@ type JobContextColumn = {
263
386
  type JobContextTable = {
264
387
  id: string;
265
388
  name: string;
389
+ slug?: string | null;
266
390
  instructions?: string;
267
391
  isPrimary: boolean;
268
392
  columns: JobContextColumn[];
@@ -482,8 +606,10 @@ declare class DocumentsResource {
482
606
  processSync(extractionSchemaId: string, fileId: string, opts?: ProcessOptions): Promise<FileData>;
483
607
  processAsync(extractionSchemaId: string, fileId: string, opts?: ProcessOptions): Promise<ProcessFileAsyncResponse>;
484
608
  processFilesAsync(extractionSchemaId: string, fileIds: string[], opts?: ProcessOptions): Promise<BulkProcessResponse>;
485
- getFileData(fileId: string, extractionSchemaId?: string): Promise<FileData>;
486
- getFilesData(fileIds: string[], extractionSchemaId: string): Promise<FileData[]>;
609
+ getFileData(fileId: string, extractionSchemaId?: string, include?: IncludeOption[]): Promise<FileData>;
610
+ getFilesData(fileIds: string[], include?: IncludeOption[]): Promise<BulkGetFilesDataResponse>;
611
+ getDocumentData(deploymentId: string, fileId: string, include?: IncludeOption[]): Promise<FlatDocumentDataResponse>;
612
+ getDocumentsData(deploymentId: string, fileIds: string[], include?: IncludeOption[]): Promise<BulkFlatDocumentDataResponse>;
487
613
  submitCorrections(extractionSchemaId: string, fileId: string, corrections: unknown): Promise<unknown>;
488
614
  }
489
615
 
@@ -608,6 +734,11 @@ declare class TablesResource {
608
734
  createRows(tableId: string, request: CreateRowsRequest): Promise<CreateRowsResponse>;
609
735
  deleteRows(tableId: string, request: DeleteRowsRequest): Promise<DeleteRowsResponse>;
610
736
  createTable(deploymentId: string, body: unknown): Promise<unknown>;
737
+ update(tableId: string, body: {
738
+ instructions?: string;
739
+ name?: string;
740
+ parentTableId?: string | null;
741
+ }): Promise<Table>;
611
742
  }
612
743
 
613
744
  type OffsetFetcher<T> = (limit: number, offset: number) => Promise<{
@@ -840,6 +971,35 @@ declare class AgentsResource {
840
971
  met: boolean;
841
972
  }>;
842
973
  }>;
974
+ createSteps(projectId: string, agentId: string, runId: string, steps: Array<{
975
+ type: string;
976
+ title: string;
977
+ description?: string;
978
+ postReviewAction?: string;
979
+ data?: Record<string, unknown>;
980
+ order: number;
981
+ conditions?: Array<{
982
+ type: string;
983
+ entityId: string;
984
+ label?: string;
985
+ }>;
986
+ }>): Promise<{
987
+ steps: Array<{
988
+ id: string;
989
+ type: string;
990
+ title: string;
991
+ status: string;
992
+ order: number;
993
+ createdAt: string;
994
+ conditions?: Array<{
995
+ id: string;
996
+ type: string;
997
+ entityId: string;
998
+ label: string | null;
999
+ met: boolean;
1000
+ }>;
1001
+ }>;
1002
+ }>;
843
1003
  updateRun(projectId: string, agentId: string, runId: string, body: {
844
1004
  status?: string;
845
1005
  metadata?: Record<string, unknown>;
@@ -924,6 +1084,7 @@ type VisionAskBody = {
924
1084
  prompt: string;
925
1085
  files: VisionFile[];
926
1086
  schema?: Record<string, unknown>;
1087
+ fast?: boolean;
927
1088
  };
928
1089
  type VisionAskResponse = {
929
1090
  text: string;
@@ -936,6 +1097,18 @@ declare class VisionResource {
936
1097
  ask(projectId: string, body: VisionAskBody): Promise<VisionAskResponse>;
937
1098
  }
938
1099
 
1100
+ declare class ValidationsResource {
1101
+ private http;
1102
+ constructor(http: HttpClient);
1103
+ submit(extractionSchemaId: string, fileId: string, body: {
1104
+ findings: unknown;
1105
+ cellChanges?: unknown;
1106
+ breakdown?: unknown;
1107
+ newRows?: unknown;
1108
+ strict?: boolean;
1109
+ }): Promise<unknown>;
1110
+ }
1111
+
939
1112
  type LabelListResponse = {
940
1113
  labels: string[];
941
1114
  };
@@ -990,6 +1163,7 @@ declare class LimaiClient {
990
1163
  readonly buckets: BucketsResource;
991
1164
  readonly agents: AgentsResource;
992
1165
  readonly vision: VisionResource;
1166
+ readonly validations: ValidationsResource;
993
1167
  readonly labels: LabelsResource;
994
1168
  constructor(config: LimaiClientConfig);
995
1169
  uploadFile(extractionSchemaId: string, filePath: string, onProgress?: (uploaded: number, total: number) => void): Promise<UploadResult>;
@@ -1116,4 +1290,4 @@ declare class UploadError extends LimaiError {
1116
1290
  }
1117
1291
  declare function mapHttpError(status: number, message: string, details?: unknown): LimaiError;
1118
1292
 
1119
- export { type Agent, type AgentDeploymentRoute, type AgentDetail, type AgentFile, type AgentIntegrationConfig, type AgentRowData, type AgentRun, type AgentRunConversation, type AgentRunDetail, type AgentRunStatus, type AgentSkill, type AgentSkillLinkedFile, type AgentStatus, type AgentStep, type AgentStepType, type AgentSubmission, type AgentTriggerType, AuthError, type Bucket, type BucketFile, type BulkProcessResponse, type BulkProcessResult, type BulkUploadFileStatus, type BulkUploadResult, type CellValue, type ClassificationAsyncResponse, type ClassificationResult, type ClassificationStatus, type Column, ConflictError, type CreateRowInput, type CreateRowsRequest, type CreateRowsResponse, type DeleteRowsRequest, type DeleteRowsResponse, type Deployment, type DeploymentConfig, type DeploymentStatus, type DeploymentType, type Document, type ExtractionRow, type ExtractionSchema, type ExtractionsResponse, type FileData, type FileStatus, ForbiddenError, type GetUrlResponse, HttpClient, type JobContext, type JobContextColumn, type JobContextTable, JobPoller, type JobStatus, type JobStatusValue, LimaiClient, type LimaiClientConfig, type LimaiConfig, LimaiError, NotFoundError, type OffsetPaginatedResponse, type OffsetPagination, type PagePaginatedResponse, type PagePagination, type PaginationOptions, type PollOptions, type ProcessFileAsyncResponse, type ProcessOptions, type Project, RateLimitError, type Row, SSEClient, ServerError, type SplitAsyncResponse, type SplitResult, type SplitSegment, type SplitStatus, type StageStatus, type Table, type TableData, TimeoutError, type UpdateStatusRequest, type UpdateStatusResponse, UploadError, type UploadResult, ValidationError, type ValidationResult, collectAll, getDeploymentId, getFileId, getJobId, loadConfig, loadJobContext, mapHttpError, paginateOffset, paginatePage, requireConfig, saveConfig, validateSubmission };
1293
+ export { type Agent, type AgentDeploymentRoute, type AgentDetail, type AgentFile, type AgentIntegrationConfig, type AgentRowData, type AgentRun, type AgentRunConversation, type AgentRunDetail, type AgentRunStatus, type AgentSkill, type AgentSkillLinkedFile, type AgentStatus, type AgentStep, type AgentStepType, type AgentSubmission, type AgentTriggerType, AuthError, type Bucket, type BucketFile, type BulkFileResult, type BulkFlatDocumentDataResponse, type BulkGetFilesDataResponse, type BulkProcessResponse, type BulkProcessResult, type BulkUploadFileStatus, type BulkUploadResult, type CellBoundingBox, type CellConfidence, type CellValidation, type CellValue, type ClassificationAsyncResponse, type ClassificationResult, type ClassificationStatus, type Column, ConflictError, type CreateRowInput, type CreateRowsRequest, type CreateRowsResponse, type DeleteRowsRequest, type DeleteRowsResponse, type Deployment, type DeploymentConfig, type DeploymentStatus, type DeploymentType, type Document, type ExtractionRow, type ExtractionSchema, type ExtractionsResponse, type FileData, type FileStatus, type FileValidationCheck, type FileValidations, type FlatCellData, type FlatCellValidation, type FlatDocumentDataResponse, type FlatDocumentEntry, type FlatFileValidations, type FlatRow, ForbiddenError, type GetUrlResponse, HttpClient, type IncludeOption, type JobContext, type JobContextColumn, type JobContextTable, JobPoller, type JobStatus, type JobStatusValue, LimaiClient, type LimaiClientConfig, type LimaiConfig, LimaiError, NotFoundError, type OffsetPaginatedResponse, type OffsetPagination, type PagePaginatedResponse, type PagePagination, type PaginationOptions, type PollOptions, type ProcessFileAsyncResponse, type ProcessOptions, type Project, RateLimitError, type Row, SSEClient, ServerError, type SplitAsyncResponse, type SplitResult, type SplitSegment, type SplitStatus, type StageStatus, type Table, type TableData, TimeoutError, type UpdateStatusRequest, type UpdateStatusResponse, UploadError, type UploadResult, ValidationError, type ValidationResult, collectAll, getDeploymentId, getFileId, getJobId, loadConfig, loadJobContext, mapHttpError, paginateOffset, paginatePage, requireConfig, saveConfig, validateSubmission };
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var je=Object.create;var ot=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var Le=Object.getPrototypeOf,_e=Object.prototype.hasOwnProperty;var Ne=(n,t)=>{for(var e in t)ot(n,e,{get:t[e],enumerable:!0})},te=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of De(t))!_e.call(n,i)&&i!==e&&ot(n,i,{get:()=>t[i],enumerable:!(s=Ue(t,i))||s.enumerable});return n};var $=(n,t,e)=>(e=n!=null?je(Le(n)):{},te(t||!n||!n.__esModule?ot(e,"default",{value:n,enumerable:!0}):e,n)),Fe=n=>te(ot({},"__esModule",{value:!0}),n);var as={};Ne(as,{AuthError:()=>at,ConflictError:()=>pt,ForbiddenError:()=>ct,HttpClient:()=>M,JobPoller:()=>q,LimaiClient:()=>It,LimaiError:()=>R,NotFoundError:()=>lt,RateLimitError:()=>ut,SSEClient:()=>Lt,ServerError:()=>dt,TimeoutError:()=>D,UploadError:()=>k,ValidationError:()=>A,collectAll:()=>bt,getDeploymentId:()=>Te,getFileId:()=>Ee,getJobId:()=>$e,loadConfig:()=>Ht,loadJobContext:()=>rt,mapHttpError:()=>Nt,paginateOffset:()=>oe,paginatePage:()=>yt,requireConfig:()=>be,saveConfig:()=>ye,validateSubmission:()=>Ae});module.exports=Fe(as);var ne=require("fs"),ie=require("fs/promises"),re=require("stream");var R=class extends Error{code;statusCode;exitCode;details;constructor(t,e){super(t),this.name="LimaiError",this.code=e.code,this.statusCode=e.statusCode,this.exitCode=e.exitCode??1,this.details=e.details}},at=class extends R{constructor(t,e){super(t,{code:"AUTH_ERROR",statusCode:401,exitCode:2,details:e}),this.name="AuthError"}},ct=class extends R{constructor(t,e){super(t,{code:"FORBIDDEN",statusCode:403,exitCode:2,details:e}),this.name="ForbiddenError"}},lt=class extends R{constructor(t,e){super(t,{code:"NOT_FOUND",statusCode:404,exitCode:3,details:e}),this.name="NotFoundError"}},A=class extends R{constructor(t,e){super(t,{code:"VALIDATION_ERROR",statusCode:400,exitCode:4,details:e}),this.name="ValidationError"}},pt=class extends R{constructor(t,e){super(t,{code:"CONFLICT",statusCode:409,exitCode:4,details:e}),this.name="ConflictError"}},ut=class extends R{retryAfterMs;constructor(t,e){super(t,{code:"RATE_LIMITED",statusCode:429,exitCode:5}),this.name="RateLimitError",this.retryAfterMs=e}},dt=class extends R{constructor(t,e=500,s){super(t,{code:"SERVER_ERROR",statusCode:e,exitCode:6,details:s}),this.name="ServerError"}},D=class extends R{constructor(t){super(t,{code:"TIMEOUT",exitCode:7}),this.name="TimeoutError"}},k=class extends R{constructor(t,e){super(t,{code:"UPLOAD_ERROR",exitCode:8,details:e}),this.name="UploadError"}};function Nt(n,t,e){switch(n){case 400:return new A(t,e);case 401:return new at(t,e);case 403:return new ct(t,e);case 404:return new lt(t,e);case 409:return new pt(t,e);case 429:return new ut(t);default:return n>=500?new dt(t,n,e):new R(t,{code:"HTTP_ERROR",statusCode:n,details:e})}}var Me=3e4,Ft=3,ee=1e3,se=2;function Be(){return process.env.LIMAI_DEBUG==="1"}function Y(...n){Be()&&console.error("[limai:http]",...n)}var M=class{baseUrl;token;constructor(t){this.baseUrl=t.apiUrl.replace(/\/$/,""),this.token=t.token}buildUrl(t,e){let s=new URL(`/api/v1${t}`,this.baseUrl);if(e)for(let[i,r]of Object.entries(e))r!=null&&s.searchParams.set(i,r);return s.toString()}authHeaders(){let t={Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},e=process.env.VERCEL_BYPASS;return e&&(t["x-vercel-protection-bypass"]=e),t}async parseErrorBody(t){try{let e=await t.json();return{message:typeof e.error=="string"?e.error:`HTTP ${t.status}`,details:e.details}}catch{return{message:await t.text().catch(()=>"")||`HTTP ${t.status}`}}}shouldRetry(t){return t===429||t>=500}getRetryDelay(t,e){let s=t.headers.get("Retry-After");if(s){let i=parseInt(s,10);if(!isNaN(i))return i*1e3}return ee*Math.pow(se,e)}async request(t,e,s={}){let i=this.buildUrl(e,s.params),r=s.timeoutMs??Me;for(let a=0;a<=Ft;a++){let p=new AbortController,u=setTimeout(()=>p.abort(),r);s.signal&&s.signal.addEventListener("abort",()=>p.abort());try{Y(`${t} ${i}${a>0?` (retry ${a})`:""}`);let c=await fetch(i,{method:t,headers:this.authHeaders(),body:s.body?JSON.stringify(s.body):void 0,signal:p.signal});if(clearTimeout(u),c.ok){let m=await c.text();return m?JSON.parse(m):{}}if(this.shouldRetry(c.status)&&a<Ft){let m=this.getRetryDelay(c,a);Y(`Retrying in ${m}ms (status ${c.status})`),await new Promise(S=>setTimeout(S,m));continue}let{message:g,details:y}=await this.parseErrorBody(c);throw Nt(c.status,g,y)}catch(c){if(clearTimeout(u),c instanceof R)throw c;if(c instanceof DOMException&&c.name==="AbortError"){if(a<Ft){let g=ee*Math.pow(se,a);Y(`Timeout, retrying in ${g}ms`),await new Promise(y=>setTimeout(y,g));continue}throw new D(`Request timed out after ${r}ms: ${t} ${e}`)}throw new R(c instanceof Error?c.message:"Unknown network error",{code:"NETWORK_ERROR",exitCode:1})}}throw new R("Max retries exceeded",{code:"MAX_RETRIES",exitCode:1})}async get(t,e,s){return this.request("GET",t,{params:e,timeoutMs:s})}async post(t,e,s){return this.request("POST",t,{body:e,timeoutMs:s})}async patch(t,e){return this.request("PATCH",t,{body:e})}async del(t,e){return this.request("DELETE",t,{body:e})}async putRaw(t,e,s,i){let r=e instanceof Blob?e.size:e.length;Y(`PUT ${t} (${r} bytes)`);let a=await fetch(t,{method:"PUT",headers:{"Content-Type":s},body:e});if(i&&i(r,r),!a.ok)throw new k(`Upload failed: HTTP ${a.status}`)}async putFile(t,e,s,i){let r=(await(0,ie.stat)(e)).size;Y(`PUT ${t} (${r} bytes, streamed from ${e})`);let a=(0,ne.createReadStream)(e),p=a;if(i){let c=0,g=new re.Transform({transform(y,m,S){c+=y.byteLength,i(c,r),S(null,y)}});p=a.pipe(g)}let u=await fetch(t,{method:"PUT",headers:{"Content-Type":s,"Content-Length":String(r)},body:p,duplex:"half"});if(i&&i(r,r),!u.ok)throw new k(`Upload failed: HTTP ${u.status}`);return r}};var gt=class{constructor(t){this.http=t}http;async getUploadUrl(t,e,s){let i={filename:e,contentHash:s};return this.http.get(`/document/${t}/get-url`,i)}async processSync(t,e,s){return this.http.post(`/document/${t}/process-file/${e}`,s,18e4)}async processAsync(t,e,s){return this.http.post(`/document/${t}/process-file-async/${e}`,s)}async processFilesAsync(t,e,s){return this.http.post(`/document/${t}/process-files-async`,{fileIds:e,...s})}async getFileData(t,e){let s={fileId:t,extractionSchemaId:e};return this.http.get("/document/get-file-data",s)}async getFilesData(t,e){return this.http.get("/document/get-files-data",{fileIds:t.join(","),extractionSchemaId:e})}async submitCorrections(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-corrections`,s)}};var mt=class{constructor(t){this.http=t}http;async list(){let t=await this.http.get("/projects");return Array.isArray(t)?t:t.data}async create(t){return this.http.post("/projects",t)}async getSchema(t){return this.http.get(`/projects/${t}/schema`)}async getSharedColumnIds(t){return this.http.get(`/projects/${t}/shared-column-ids`)}async listDeployments(t){return this.http.get(`/projects/${t}/deployments`)}async listBenchmarks(t){return this.http.get(`/projects/${t}/benchmarks`)}async listNotificationRoutes(t){return this.http.get(`/projects/${t}/notifications`)}async createNotificationRoute(t,e){return this.http.post(`/projects/${t}/notifications`,e)}async updateNotificationRoute(t,e,s){return this.http.patch(`/projects/${t}/notifications/${e}`,s)}async deleteNotificationRoute(t,e){return this.http.del(`/projects/${t}/notifications/${e}`)}async listNotificationIntegrations(t,e){return this.http.get(`/projects/${t}/notifications/integrations`,{provider:e})}async listNotificationSlackChannels(t,e){return this.http.get(`/projects/${t}/notifications/integrations/slack/channels`,{connectionId:e})}async listNotificationTeamsTeams(t,e){return this.http.get(`/projects/${t}/notifications/integrations/teams/teams`,{connectionId:e})}async listNotificationTeamsChannels(t,e,s){return this.http.get(`/projects/${t}/notifications/integrations/teams/channels`,{connectionId:e,teamId:s})}};var ht=class{constructor(t){this.http=t}http;async list(t,e){let s={status:e?.status,type:e?.type},i=await this.http.get(`/projects/${t}/deployments`,s);return Array.isArray(i)?i:i.data}async create(t,e){return this.http.post(`/projects/${t}/deployments`,e)}async getConfig(t){return this.http.get(`/deployments/${t}/configuration`)}async updateConfig(t,e){await this.http.patch(`/deployment/${t}/configuration`,e)}async listDocuments(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/deployments/${t}/documents`,s)}async getDocument(t,e){return this.http.get(`/deployments/${t}/documents/${e}`)}async deleteDocument(t,e){await this.http.del(`/deployments/${t}/documents/${e}`)}async bulkDelete(t,e){await this.http.del(`/deployments/${t}/documents/bulk-delete`,{fileIds:e})}};var ft=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/tables/${t}`)}async listColumns(t){let e=await this.http.get(`/tables/${t}/columns`);return Array.isArray(e)?e:e.data}async listRows(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/tables/${t}/rows`,s)}async createRows(t,e){return this.http.post(`/tables/${t}/rows`,e,6e4)}async deleteRows(t,e){return this.http.del(`/tables/${t}/rows`,e)}async createTable(t,e){return this.http.post(`/deployments/${t}/tables`,e)}};async function*oe(n,t={}){let e=Math.min(t.pageSize??100,500),s=0,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(r,s),p=a.data;if(p.length===0||(yield p,i+=p.length,s+=p.length,s>=a.pagination.total)||t.maxItems&&i>=t.maxItems)break}}async function*yt(n,t={}){let e=Math.min(t.pageSize??100,500),s=1,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(s,r),p=a.data;if(p.length===0||(yield p,i+=p.length,s++,s>a.pagination.totalPages)||t.maxItems&&i>=t.maxItems)break}}async function bt(n){let t=[];for await(let e of n)t.push(...e);return t}var Rt=class{constructor(t){this.http=t}http;async getRows(t,e){let s={page:e?.page?.toString(),limit:e?.limit?.toString(),order:e?.order,status:e?.status};return this.http.get(`/extractions/${t}`,s)}async*getAllRows(t,e){yield*yt(async(s,i)=>this.http.get(`/extractions/${t}`,{page:s.toString(),limit:i.toString(),order:e?.order,status:e?.status}),e)}async collectAllRows(t,e){return bt(this.getAllRows(t,e))}};var wt=class{constructor(t){this.http=t}http;async getStatus(t){return this.http.get(`/queue/${t}/status`)}async cancel(t){await this.http.post("/queue/cancel",{jobId:t})}async updateStatus(t,e){return this.http.patch(`/queue/${t}/status`,e)}};var Ct=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/classify",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/classify/${t}/get-url`,{filename:e})}async classify(t,e){return this.http.post(`/classify/${t}`,{fileId:e})}async classifyAsync(t,e){return this.http.post(`/classify/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/classify/${t}`,{classificationId:e})}async createClassifier(t){return this.http.post("/classify",t)}async createRoute(t,e){return this.http.post(`/classify/${t}/routes`,e)}};var vt=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/split",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/split/${t}/get-url`,{filename:e})}async split(t,e){return this.http.post(`/split/${t}`,{fileId:e})}async splitAsync(t,e){return this.http.post(`/split/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/split/${t}`,{splitId:e})}async listSplits(t){return this.http.get(`/split/${t}/splits`)}async createSplitter(t){return this.http.post("/split",t)}};var St=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/extraction-schema/${t}`)}async update(t,e){await this.http.patch(`/extraction-schema/${t}`,e)}async getAllData(t){return this.http.get("/extraction-schema/get-all-data",{extractionSchemaId:t})}};var xt=class{constructor(t){this.http=t}http;async list(t){return this.http.get(`/projects/${t}/buckets`)}async get(t){return this.http.get(`/buckets/${t}`)}async create(t,e,s){return this.http.post(`/projects/${t}/buckets`,{name:e,description:s})}async delete(t){await this.http.del(`/buckets/${t}`)}async getUploadUrl(t,e){return this.http.get(`/buckets/${t}/get-url`,{filename:e})}async confirmUpload(t,e,s){await this.http.patch(`/buckets/${t}/files/${e}/status`,{status:"UPLOADED",...s!==void 0&&{sizeBytes:s}})}async listFiles(t,e){let s={};return e&&e.length>0&&(s.labels=e.join(",")),this.http.get(`/buckets/${t}/files`,s)}async getDownloadUrl(t,e){return this.http.get(`/buckets/${t}/files/${e}/download`)}async updateLabels(t,e,s){return this.http.patch(`/buckets/${t}/files/${e}`,{labels:s})}async deleteFile(t,e){await this.http.del(`/buckets/${t}/files/${e}`)}async sendTo(t,e,s,i){return this.http.post(`/buckets/${t}/files/${e}/send-to`,{targetType:s,targetId:i})}};var Pt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.status&&(s.status=e.status),this.http.get(`/projects/${t}/agents`,s)}async get(t,e){return this.http.get(`/projects/${t}/agents/${e}`)}async create(t,e){return this.http.post(`/projects/${t}/agents`,e)}async update(t,e,s){return this.http.patch(`/projects/${t}/agents/${e}`,s)}async delete(t,e){await this.http.del(`/projects/${t}/agents/${e}`)}async getFileUploadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/get-url`,{filename:s})}async deleteFile(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/files/${s}`)}async updateFileMetadata(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/files/${s}`,i)}async getFileDownloadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/${s}/download`)}async listSkills(t,e){return this.http.get(`/projects/${t}/agents/${e}/skills`)}async createSkill(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/skills`,s)}async updateSkill(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/skills/${s}`,i)}async deleteSkill(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}`)}async linkFileToSkill(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/skills/${s}/files`,{fileId:i})}async unlinkFileFromSkill(t,e,s,i){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}/files/${i}`)}async listRuns(t,e,s){let i={};return s?.limit&&(i.limit=String(s.limit)),s?.status&&(i.status=s.status),this.http.get(`/projects/${t}/agents/${e}/runs`,i)}async getRun(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/runs/${s}`)}async getRunConversation(t,e,s,i){let r={};return i?.stepId&&(r.stepId=i.stepId),this.http.get(`/projects/${t}/agents/${e}/runs/${s}/conversation`,r)}async createRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs`,s)}async createStep(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,i)}async updateRun(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}`,i)}async updateStep(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,r)}async updateStepConditions(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,{conditions:r})}async pauseRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/pause`,{})}async submitStepAction(t,e,s,i,r){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}/action`,r)}async sendEmail(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/send-email`,s)}async completeExecution(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/executions/complete`,s)}async getSharePointToken(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/sharepoint-token`,s)}async getArtifactUploadUrl(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/upload-artifact/get-url`,s)}};var $t=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var Et=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),this.http.get(`/projects/${t}/labels`,s)}async addRemove(t,e,s,i,r){return this.http.post(`/projects/${t}/labels`,{entityType:e,entityId:s,add:i,remove:r})}async search(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),e?.labels&&(s.labels=e.labels),e?.key&&(s.key=e.key),this.http.get(`/projects/${t}/labels/search`,s)}};var Tt=$(require("fs")),B=$(require("path"));var ae=$(require("fs")),ce=$(require("crypto"));async function le(n){return new Promise((t,e)=>{let s=ce.createHash("sha256"),i=ae.createReadStream(n);i.on("data",r=>s.update(r)),i.on("end",()=>t(s.digest("hex"))),i.on("error",e)})}var He={".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".tiff":"image/tiff",".tif":"image/tiff",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xls":"application/vnd.ms-excel",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};function Je(n){let t=B.extname(n).toLowerCase();return He[t]||"application/octet-stream"}async function At(n,t,e,s,i){let r=B.resolve(s),a=B.basename(r);if(!Tt.existsSync(r))throw new k(`File not found: ${r}`);if(!Tt.statSync(r).isFile())throw new k(`Not a file: ${r}`);let u=await le(r),c=await t.getUploadUrl(e,a,u);if(c.isDuplicate)return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!0,bytesUploaded:0};let g=Je(r),y=await n.putFile(c.url,r,g,i);return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!1,bytesUploaded:y}}var H=$(require("fs")),J=$(require("path"));var ue=$(require("path"));var pe=250,qe=5,Mt=class{constructor(t){this.max=t}max;queue=[];current=0;async acquire(){if(this.current<this.max){this.current++;return}return new Promise(t=>{this.queue.push(t)})}release(){this.current--;let t=this.queue.shift();t&&(this.current++,t())}};async function de(n,t,e,s,i){let r=Math.min(i?.concurrency??qe,10),a=new Mt(r),p=s.map(m=>({path:m,filename:ue.basename(m),status:"pending"})),u=p.map(async(m,S)=>{await a.acquire();try{m.status="uploading",i?.onFileStatus?.(m);let f=await At(n,t,e,m.path);m.fileId=f.fileId,m.status="uploaded",i?.onFileStatus?.(m)}catch(f){m.status="failed",m.error=f instanceof Error?f.message:String(f),i?.onFileStatus?.(m)}finally{a.release()}});if(await Promise.all(u),i?.process){let S=p.filter(f=>f.status==="uploaded"&&f.fileId).map(f=>f.fileId);for(let f=0;f<S.length;f+=pe){let I=S.slice(f,f+pe);try{let T=await t.processFilesAsync(e,I,i.processOptions);for(let[l,o]of Object.entries(T.results)){let d=p.find(C=>C.fileId===l);d&&(o.status==="queued"?(d.status="queued",d.jobId=o.jobId):(d.status="failed",d.error=o.error),i?.onFileStatus?.(d))}}catch(T){for(let l of I){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=T instanceof Error?T.message:String(T),i?.onFileStatus?.(o))}}}}let c=p.filter(m=>m.status==="uploaded"||m.status==="queued").length,g=p.filter(m=>m.status==="queued").length,y=p.filter(m=>m.status==="failed").length;return{total:s.length,uploaded:c,queued:g,failed:y,files:p}}var Ge=new Set([".pdf",".png",".jpg",".jpeg",".tiff",".tif",".xlsx",".xls",".csv",".docx",".doc"]);function ge(n,t){let e=[],s=H.readdirSync(n,{withFileTypes:!0});for(let i of s){let r=J.join(n,i.name);if(!i.name.startsWith(".")){if(i.isDirectory())e.push(...ge(r,t));else if(i.isFile()){let a=J.extname(i.name).toLowerCase();if(!Ge.has(a)||t&&!Ve(i.name,t))continue;e.push(r)}}}return e.sort()}function Ve(n,t){let e=t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`,"i").test(n)}async function me(n,t,e,s,i){let r=J.resolve(s);if(!H.existsSync(r))throw new Error(`Directory not found: ${r}`);if(!H.statSync(r).isDirectory())throw new Error(`Not a directory: ${r}`);let p=ge(r,i?.globPattern);return p.length===0?{total:0,uploaded:0,queued:0,failed:0,files:[]}:de(n,t,e,p,{concurrency:i?.concurrency,process:i?.process,processOptions:i?.processOptions,onFileStatus:i?.onFileStatus})}var We=1e3,ze=1e4,Xe=1.5,Ke=3e5,Ye=["COMPLETED","FAILED","STALLED"],q=class{constructor(t){this.queue=t}queue;async*poll(t,e){let s=e?.intervalMs??We,i=e?.maxIntervalMs??ze,r=e?.backoffMultiplier??Xe,a=e?.timeoutMs??Ke,p=s,u=Date.now(),c;for(;;){if(Date.now()-u>a)throw new D(`Polling timed out after ${Math.round(a/1e3)}s for job ${t}`);let g=await this.queue.getStatus(t);if(g.status!==c&&(c=g.status,e?.onStatus?.(g),yield g),Ye.includes(g.status))return;await new Promise(y=>setTimeout(y,p)),p=Math.min(p*r,i)}}async waitForCompletion(t,e){let s;for await(let i of this.poll(t,e))s=i;if(!s)throw new Error(`No status received for job ${t}`);return s}};var It=class{http;documents;projects;deployments;tables;extractions;queue;classify;split;schema;buckets;agents;vision;labels;constructor(t){this.http=new M({apiUrl:t.apiUrl,token:t.token}),this.documents=new gt(this.http),this.projects=new mt(this.http),this.deployments=new ht(this.http),this.tables=new ft(this.http),this.extractions=new Rt(this.http),this.queue=new wt(this.http),this.classify=new Ct(this.http),this.split=new vt(this.http),this.schema=new St(this.http),this.buckets=new xt(this.http),this.agents=new Pt(this.http),this.vision=new $t(this.http),this.labels=new Et(this.http)}async uploadFile(t,e,s){return At(this.http,this.documents,t,e,s)}async uploadFolder(t,e,s){return me(this.http,this.documents,t,e,s)}async processAndWait(t,e,s){let i=await this.documents.processAsync(t,e,s?.processOptions),r=new q(this.queue),a;for await(let p of r.poll(i.jobId,s?.pollOptions))a=p;if(!a||a.status==="FAILED")throw new Error(`Extraction failed for file ${e}${a?`: ${a.status}`:""}`);return this.documents.getFileData(e,t)}async*downloadAll(t,e){yield*this.extractions.getAllRows(t,e)}};var x=$(require("fs")),Z=$(require("path")),he=$(require("os")),kt=require("child_process"),Bt=Z.join(he.homedir(),".limai"),Q=Z.join(Bt,"config.json"),Qe=".limai.token",G;function fe(){if(G!==void 0)return G;try{let n=(0,kt.execSync)("git rev-parse --show-toplevel",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!x.existsSync(Z.join(n,"packages","cli")))return G=null,null;let t=(0,kt.execSync)("git rev-parse --git-common-dir",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),e="";if(t!==".git"){let s=(0,kt.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(s){let i=s.replace(/[/\\]/g,"-").replace(/[^a-zA-Z0-9._-]/g,"").replace(/^-+|-+$/g,"");i&&(e=`${i}.`)}}return G={root:n,apiUrl:`http://${e}tables.localhost:1355`,sseUrl:`http://${e}ws.localhost:1355`},G}catch{return G=null,null}}function Ze(){let n=fe();if(!n)return;let t=Z.join(n.root,Qe);if(x.existsSync(t))return x.readFileSync(t,"utf-8").trim()}function Ht(){let n=process.env.LIMAI_API_TOKEN,t=process.env.LIMAI_API_URL,e=process.env.LIMAI_SSE_URL,s={};if(x.existsSync(Q))try{let u=x.readFileSync(Q,"utf-8"),c=JSON.parse(u);c&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}let i=fe(),r=n||Ze()||s.token,a=t||s.apiUrl||i?.apiUrl||process.env.LIMAI_BUILD_URL||void 0,p=e||s.sseUrl||i?.sseUrl||void 0;return!r||!a?null:{token:r,apiUrl:a,sseUrl:p,defaultProjectId:s.defaultProjectId,defaultDeploymentId:s.defaultDeploymentId}}function ye(n){let t={};if(x.existsSync(Q))try{let s=x.readFileSync(Q,"utf-8");t=JSON.parse(s)}catch{t={}}let e={...t,...n};x.existsSync(Bt)||x.mkdirSync(Bt,{recursive:!0,mode:448}),x.writeFileSync(Q,JSON.stringify(e,null,2),{mode:384})}function be(){let n=Ht();return n||(console.error("Not authenticated. Run `npm run cli:setup` or set LIMAI_API_TOKEN environment variable."),process.exit(1)),n}var Ot=class extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}},Re=10,ts=13,L=32;function Jt(n){}function ve(n){if(typeof n=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Jt,onError:e=Jt,onRetry:s=Jt,onComment:i}=n,r=[],a=!0,p,u="",c=0,g;function y(l){if(a&&(a=!1,l.charCodeAt(0)===239&&l.charCodeAt(1)===187&&l.charCodeAt(2)===191&&(l=l.slice(3))),r.length===0){let C=m(l);C!==""&&r.push(C);return}if(l.indexOf(`
1
+ "use strict";var De=Object.create;var ot=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ne=(n,t)=>{for(var e in t)ot(n,e,{get:t[e],enumerable:!0})},ee=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Le(t))!Fe.call(n,i)&&i!==e&&ot(n,i,{get:()=>t[i],enumerable:!(s=Ue(t,i))||s.enumerable});return n};var $=(n,t,e)=>(e=n!=null?De(_e(n)):{},ee(t||!n||!n.__esModule?ot(e,"default",{value:n,enumerable:!0}):e,n)),Me=n=>ee(ot({},"__esModule",{value:!0}),n);var cs={};Ne(cs,{AuthError:()=>at,ConflictError:()=>pt,ForbiddenError:()=>ct,HttpClient:()=>M,JobPoller:()=>G,LimaiClient:()=>kt,LimaiError:()=>R,NotFoundError:()=>lt,RateLimitError:()=>ut,SSEClient:()=>_t,ServerError:()=>dt,TimeoutError:()=>U,UploadError:()=>k,ValidationError:()=>A,collectAll:()=>bt,getDeploymentId:()=>Ae,getFileId:()=>Te,getJobId:()=>Ee,loadConfig:()=>Jt,loadJobContext:()=>rt,mapHttpError:()=>Nt,paginateOffset:()=>ae,paginatePage:()=>yt,requireConfig:()=>Re,saveConfig:()=>be,validateSubmission:()=>Ie});module.exports=Me(cs);var ie=require("fs"),re=require("fs/promises"),oe=require("stream");var R=class extends Error{code;statusCode;exitCode;details;constructor(t,e){super(t),this.name="LimaiError",this.code=e.code,this.statusCode=e.statusCode,this.exitCode=e.exitCode??1,this.details=e.details}},at=class extends R{constructor(t,e){super(t,{code:"AUTH_ERROR",statusCode:401,exitCode:2,details:e}),this.name="AuthError"}},ct=class extends R{constructor(t,e){super(t,{code:"FORBIDDEN",statusCode:403,exitCode:2,details:e}),this.name="ForbiddenError"}},lt=class extends R{constructor(t,e){super(t,{code:"NOT_FOUND",statusCode:404,exitCode:3,details:e}),this.name="NotFoundError"}},A=class extends R{constructor(t,e){super(t,{code:"VALIDATION_ERROR",statusCode:400,exitCode:4,details:e}),this.name="ValidationError"}},pt=class extends R{constructor(t,e){super(t,{code:"CONFLICT",statusCode:409,exitCode:4,details:e}),this.name="ConflictError"}},ut=class extends R{retryAfterMs;constructor(t,e){super(t,{code:"RATE_LIMITED",statusCode:429,exitCode:5}),this.name="RateLimitError",this.retryAfterMs=e}},dt=class extends R{constructor(t,e=500,s){super(t,{code:"SERVER_ERROR",statusCode:e,exitCode:6,details:s}),this.name="ServerError"}},U=class extends R{constructor(t){super(t,{code:"TIMEOUT",exitCode:7}),this.name="TimeoutError"}},k=class extends R{constructor(t,e){super(t,{code:"UPLOAD_ERROR",exitCode:8,details:e}),this.name="UploadError"}};function Nt(n,t,e){switch(n){case 400:return new A(t,e);case 401:return new at(t,e);case 403:return new ct(t,e);case 404:return new lt(t,e);case 409:return new pt(t,e);case 429:return new ut(t);default:return n>=500?new dt(t,n,e):new R(t,{code:"HTTP_ERROR",statusCode:n,details:e})}}var Be=3e4,Mt=3,se=1e3,ne=2;function He(){return process.env.LIMAI_DEBUG==="1"}function Y(...n){He()&&console.error("[limai:http]",...n)}var M=class{baseUrl;token;constructor(t){this.baseUrl=t.apiUrl.replace(/\/$/,""),this.token=t.token}buildUrl(t,e){let s=new URL(`/api/v1${t}`,this.baseUrl);if(e)for(let[i,r]of Object.entries(e))r!=null&&s.searchParams.set(i,r);return s.toString()}authHeaders(){let t={Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},e=process.env.VERCEL_BYPASS;return e&&(t["x-vercel-protection-bypass"]=e),t}async parseErrorBody(t){try{let e=await t.json();return{message:typeof e.error=="string"?e.error:`HTTP ${t.status}`,details:e.details}}catch{return{message:await t.text().catch(()=>"")||`HTTP ${t.status}`}}}shouldRetry(t){return t===429||t>=500}getRetryDelay(t,e){let s=t.headers.get("Retry-After");if(s){let i=parseInt(s,10);if(!isNaN(i))return i*1e3}return se*Math.pow(ne,e)}async request(t,e,s={}){let i=this.buildUrl(e,s.params),r=s.timeoutMs??Be;for(let a=0;a<=Mt;a++){let p=new AbortController,u=setTimeout(()=>p.abort(),r);s.signal&&s.signal.addEventListener("abort",()=>p.abort());try{Y(`${t} ${i}${a>0?` (retry ${a})`:""}`);let c=await fetch(i,{method:t,headers:this.authHeaders(),body:s.body?JSON.stringify(s.body):void 0,signal:p.signal});if(clearTimeout(u),c.ok){let m=await c.text();return m?JSON.parse(m):{}}if(this.shouldRetry(c.status)&&a<Mt){let m=this.getRetryDelay(c,a);Y(`Retrying in ${m}ms (status ${c.status})`),await new Promise(S=>setTimeout(S,m));continue}let{message:g,details:y}=await this.parseErrorBody(c);throw Nt(c.status,g,y)}catch(c){if(clearTimeout(u),c instanceof R)throw c;if(c instanceof DOMException&&c.name==="AbortError"){if(a<Mt){let g=se*Math.pow(ne,a);Y(`Timeout, retrying in ${g}ms`),await new Promise(y=>setTimeout(y,g));continue}throw new U(`Request timed out after ${r}ms: ${t} ${e}`)}throw new R(c instanceof Error?c.message:"Unknown network error",{code:"NETWORK_ERROR",exitCode:1})}}throw new R("Max retries exceeded",{code:"MAX_RETRIES",exitCode:1})}async get(t,e,s){return this.request("GET",t,{params:e,timeoutMs:s})}async post(t,e,s){return this.request("POST",t,{body:e,timeoutMs:s})}async patch(t,e){return this.request("PATCH",t,{body:e})}async del(t,e){return this.request("DELETE",t,{body:e})}async putRaw(t,e,s,i){let r=e instanceof Blob?e.size:e.length;Y(`PUT ${t} (${r} bytes)`);let a=await fetch(t,{method:"PUT",headers:{"Content-Type":s},body:e});if(i&&i(r,r),!a.ok)throw new k(`Upload failed: HTTP ${a.status}`)}async putFile(t,e,s,i){let r=(await(0,re.stat)(e)).size;Y(`PUT ${t} (${r} bytes, streamed from ${e})`);let a=(0,ie.createReadStream)(e),p=a;if(i){let c=0,g=new oe.Transform({transform(y,m,S){c+=y.byteLength,i(c,r),S(null,y)}});p=a.pipe(g)}let u=await fetch(t,{method:"PUT",headers:{"Content-Type":s,"Content-Length":String(r)},body:p,duplex:"half"});if(i&&i(r,r),!u.ok)throw new k(`Upload failed: HTTP ${u.status}`);return r}};var gt=class{constructor(t){this.http=t}http;async getUploadUrl(t,e,s){let i={filename:e,contentHash:s};return this.http.get(`/document/${t}/get-url`,i)}async processSync(t,e,s){return this.http.post(`/document/${t}/process-file/${e}`,s,18e4)}async processAsync(t,e,s){return this.http.post(`/document/${t}/process-file-async/${e}`,s)}async processFilesAsync(t,e,s){return this.http.post(`/document/${t}/process-files-async`,{fileIds:e,...s})}async getFileData(t,e,s){let i={fileId:t,extractionSchemaId:e,include:s?.length?s.join(","):void 0};return this.http.get("/document/get-file-data",i)}async getFilesData(t,e){return this.http.post("/document/get-files-data",{fileIds:t,...e?.length?{include:e}:{}})}async getDocumentData(t,e,s){let i={include:s?.length?s.join(","):void 0};return this.http.get(`/deployments/${t}/documents/${e}/data`,i)}async getDocumentsData(t,e,s){return this.http.post(`/deployments/${t}/documents/data`,{fileIds:e,...s?.length?{include:s}:{}})}async submitCorrections(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-corrections`,s)}};var mt=class{constructor(t){this.http=t}http;async list(){let t=await this.http.get("/projects");return Array.isArray(t)?t:t.data}async create(t){return this.http.post("/projects",t)}async getSchema(t){return this.http.get(`/projects/${t}/schema`)}async getSharedColumnIds(t){return this.http.get(`/projects/${t}/shared-column-ids`)}async listDeployments(t){return this.http.get(`/projects/${t}/deployments`)}async listBenchmarks(t){return this.http.get(`/projects/${t}/benchmarks`)}async listNotificationRoutes(t){return this.http.get(`/projects/${t}/notifications`)}async createNotificationRoute(t,e){return this.http.post(`/projects/${t}/notifications`,e)}async updateNotificationRoute(t,e,s){return this.http.patch(`/projects/${t}/notifications/${e}`,s)}async deleteNotificationRoute(t,e){return this.http.del(`/projects/${t}/notifications/${e}`)}async listNotificationIntegrations(t,e){return this.http.get(`/projects/${t}/notifications/integrations`,{provider:e})}async listNotificationSlackChannels(t,e){return this.http.get(`/projects/${t}/notifications/integrations/slack/channels`,{connectionId:e})}async listNotificationTeamsTeams(t,e){return this.http.get(`/projects/${t}/notifications/integrations/teams/teams`,{connectionId:e})}async listNotificationTeamsChannels(t,e,s){return this.http.get(`/projects/${t}/notifications/integrations/teams/channels`,{connectionId:e,teamId:s})}};var ht=class{constructor(t){this.http=t}http;async list(t,e){let s={status:e?.status,type:e?.type},i=await this.http.get(`/projects/${t}/deployments`,s);return Array.isArray(i)?i:i.data}async create(t,e){return this.http.post(`/projects/${t}/deployments`,e)}async getConfig(t){return this.http.get(`/deployments/${t}/configuration`)}async updateConfig(t,e){await this.http.patch(`/deployment/${t}/configuration`,e)}async listDocuments(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/deployments/${t}/documents`,s)}async getDocument(t,e){return this.http.get(`/deployments/${t}/documents/${e}`)}async deleteDocument(t,e){await this.http.del(`/deployments/${t}/documents/${e}`)}async bulkDelete(t,e){await this.http.del(`/deployments/${t}/documents/bulk-delete`,{fileIds:e})}};var ft=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/tables/${t}`)}async listColumns(t){let e=await this.http.get(`/tables/${t}/columns`);return Array.isArray(e)?e:e.data}async listRows(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/tables/${t}/rows`,s)}async createRows(t,e){return this.http.post(`/tables/${t}/rows`,e,6e4)}async deleteRows(t,e){return this.http.del(`/tables/${t}/rows`,e)}async createTable(t,e){return this.http.post(`/deployments/${t}/tables`,e)}async update(t,e){return this.http.patch(`/tables/${t}`,e)}};async function*ae(n,t={}){let e=Math.min(t.pageSize??100,500),s=0,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(r,s),p=a.data;if(p.length===0||(yield p,i+=p.length,s+=p.length,s>=a.pagination.total)||t.maxItems&&i>=t.maxItems)break}}async function*yt(n,t={}){let e=Math.min(t.pageSize??100,500),s=1,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(s,r),p=a.data;if(p.length===0||(yield p,i+=p.length,s++,s>a.pagination.totalPages)||t.maxItems&&i>=t.maxItems)break}}async function bt(n){let t=[];for await(let e of n)t.push(...e);return t}var Rt=class{constructor(t){this.http=t}http;async getRows(t,e){let s={page:e?.page?.toString(),limit:e?.limit?.toString(),order:e?.order,status:e?.status};return this.http.get(`/extractions/${t}`,s)}async*getAllRows(t,e){yield*yt(async(s,i)=>this.http.get(`/extractions/${t}`,{page:s.toString(),limit:i.toString(),order:e?.order,status:e?.status}),e)}async collectAllRows(t,e){return bt(this.getAllRows(t,e))}};var wt=class{constructor(t){this.http=t}http;async getStatus(t){return this.http.get(`/queue/${t}/status`)}async cancel(t){await this.http.post("/queue/cancel",{jobId:t})}async updateStatus(t,e){return this.http.patch(`/queue/${t}/status`,e)}};var Ct=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/classify",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/classify/${t}/get-url`,{filename:e})}async classify(t,e){return this.http.post(`/classify/${t}`,{fileId:e})}async classifyAsync(t,e){return this.http.post(`/classify/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/classify/${t}`,{classificationId:e})}async createClassifier(t){return this.http.post("/classify",t)}async createRoute(t,e){return this.http.post(`/classify/${t}/routes`,e)}};var vt=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/split",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/split/${t}/get-url`,{filename:e})}async split(t,e){return this.http.post(`/split/${t}`,{fileId:e})}async splitAsync(t,e){return this.http.post(`/split/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/split/${t}`,{splitId:e})}async listSplits(t){return this.http.get(`/split/${t}/splits`)}async createSplitter(t){return this.http.post("/split",t)}};var St=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/extraction-schema/${t}`)}async update(t,e){await this.http.patch(`/extraction-schema/${t}`,e)}async getAllData(t){return this.http.get("/extraction-schema/get-all-data",{extractionSchemaId:t})}};var xt=class{constructor(t){this.http=t}http;async list(t){return this.http.get(`/projects/${t}/buckets`)}async get(t){return this.http.get(`/buckets/${t}`)}async create(t,e,s){return this.http.post(`/projects/${t}/buckets`,{name:e,description:s})}async delete(t){await this.http.del(`/buckets/${t}`)}async getUploadUrl(t,e){return this.http.get(`/buckets/${t}/get-url`,{filename:e})}async confirmUpload(t,e,s){await this.http.patch(`/buckets/${t}/files/${e}/status`,{status:"UPLOADED",...s!==void 0&&{sizeBytes:s}})}async listFiles(t,e){let s={};return e&&e.length>0&&(s.labels=e.join(",")),this.http.get(`/buckets/${t}/files`,s)}async getDownloadUrl(t,e){return this.http.get(`/buckets/${t}/files/${e}/download`)}async updateLabels(t,e,s){return this.http.patch(`/buckets/${t}/files/${e}`,{labels:s})}async deleteFile(t,e){await this.http.del(`/buckets/${t}/files/${e}`)}async sendTo(t,e,s,i){return this.http.post(`/buckets/${t}/files/${e}/send-to`,{targetType:s,targetId:i})}};var Pt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.status&&(s.status=e.status),this.http.get(`/projects/${t}/agents`,s)}async get(t,e){return this.http.get(`/projects/${t}/agents/${e}`)}async create(t,e){return this.http.post(`/projects/${t}/agents`,e)}async update(t,e,s){return this.http.patch(`/projects/${t}/agents/${e}`,s)}async delete(t,e){await this.http.del(`/projects/${t}/agents/${e}`)}async getFileUploadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/get-url`,{filename:s})}async deleteFile(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/files/${s}`)}async updateFileMetadata(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/files/${s}`,i)}async getFileDownloadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/${s}/download`)}async listSkills(t,e){return this.http.get(`/projects/${t}/agents/${e}/skills`)}async createSkill(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/skills`,s)}async updateSkill(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/skills/${s}`,i)}async deleteSkill(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}`)}async linkFileToSkill(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/skills/${s}/files`,{fileId:i})}async unlinkFileFromSkill(t,e,s,i){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}/files/${i}`)}async listRuns(t,e,s){let i={};return s?.limit&&(i.limit=String(s.limit)),s?.status&&(i.status=s.status),this.http.get(`/projects/${t}/agents/${e}/runs`,i)}async getRun(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/runs/${s}`)}async getRunConversation(t,e,s,i){let r={};return i?.stepId&&(r.stepId=i.stepId),this.http.get(`/projects/${t}/agents/${e}/runs/${s}/conversation`,r)}async createRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs`,s)}async createStep(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,i)}async createSteps(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,{steps:i})}async updateRun(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}`,i)}async updateStep(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,r)}async updateStepConditions(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,{conditions:r})}async pauseRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/pause`,{})}async submitStepAction(t,e,s,i,r){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}/action`,r)}async sendEmail(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/send-email`,s)}async completeExecution(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/executions/complete`,s)}async getSharePointToken(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/sharepoint-token`,s)}async getArtifactUploadUrl(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/upload-artifact/get-url`,s)}};var $t=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var Et=class{constructor(t){this.http=t}http;async submit(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-validation`,s)}};var Tt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),this.http.get(`/projects/${t}/labels`,s)}async addRemove(t,e,s,i,r){return this.http.post(`/projects/${t}/labels`,{entityType:e,entityId:s,add:i,remove:r})}async search(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),e?.labels&&(s.labels=e.labels),e?.key&&(s.key=e.key),this.http.get(`/projects/${t}/labels/search`,s)}};var At=$(require("fs")),B=$(require("path"));var ce=$(require("fs")),le=$(require("crypto"));async function pe(n){return new Promise((t,e)=>{let s=le.createHash("sha256"),i=ce.createReadStream(n);i.on("data",r=>s.update(r)),i.on("end",()=>t(s.digest("hex"))),i.on("error",e)})}var Je={".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".tiff":"image/tiff",".tif":"image/tiff",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xls":"application/vnd.ms-excel",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};function Ge(n){let t=B.extname(n).toLowerCase();return Je[t]||"application/octet-stream"}async function It(n,t,e,s,i){let r=B.resolve(s),a=B.basename(r);if(!At.existsSync(r))throw new k(`File not found: ${r}`);if(!At.statSync(r).isFile())throw new k(`Not a file: ${r}`);let u=await pe(r),c=await t.getUploadUrl(e,a,u);if(c.isDuplicate)return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!0,bytesUploaded:0};let g=Ge(r),y=await n.putFile(c.url,r,g,i);return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!1,bytesUploaded:y}}var H=$(require("fs")),J=$(require("path"));var de=$(require("path"));var ue=250,qe=5,Bt=class{constructor(t){this.max=t}max;queue=[];current=0;async acquire(){if(this.current<this.max){this.current++;return}return new Promise(t=>{this.queue.push(t)})}release(){this.current--;let t=this.queue.shift();t&&(this.current++,t())}};async function ge(n,t,e,s,i){let r=Math.min(i?.concurrency??qe,10),a=new Bt(r),p=s.map(m=>({path:m,filename:de.basename(m),status:"pending"})),u=p.map(async(m,S)=>{await a.acquire();try{m.status="uploading",i?.onFileStatus?.(m);let f=await It(n,t,e,m.path);m.fileId=f.fileId,m.status="uploaded",i?.onFileStatus?.(m)}catch(f){m.status="failed",m.error=f instanceof Error?f.message:String(f),i?.onFileStatus?.(m)}finally{a.release()}});if(await Promise.all(u),i?.process){let S=p.filter(f=>f.status==="uploaded"&&f.fileId).map(f=>f.fileId);for(let f=0;f<S.length;f+=ue){let I=S.slice(f,f+ue);try{let T=await t.processFilesAsync(e,I,i.processOptions);for(let[l,o]of Object.entries(T.results)){let d=p.find(C=>C.fileId===l);d&&(o.status==="queued"?(d.status="queued",d.jobId=o.jobId):(d.status="failed",d.error=o.error),i?.onFileStatus?.(d))}}catch(T){for(let l of I){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=T instanceof Error?T.message:String(T),i?.onFileStatus?.(o))}}}}let c=p.filter(m=>m.status==="uploaded"||m.status==="queued").length,g=p.filter(m=>m.status==="queued").length,y=p.filter(m=>m.status==="failed").length;return{total:s.length,uploaded:c,queued:g,failed:y,files:p}}var Ve=new Set([".pdf",".png",".jpg",".jpeg",".tiff",".tif",".xlsx",".xls",".csv",".docx",".doc"]);function me(n,t){let e=[],s=H.readdirSync(n,{withFileTypes:!0});for(let i of s){let r=J.join(n,i.name);if(!i.name.startsWith(".")){if(i.isDirectory())e.push(...me(r,t));else if(i.isFile()){let a=J.extname(i.name).toLowerCase();if(!Ve.has(a)||t&&!We(i.name,t))continue;e.push(r)}}}return e.sort()}function We(n,t){let e=t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`,"i").test(n)}async function he(n,t,e,s,i){let r=J.resolve(s);if(!H.existsSync(r))throw new Error(`Directory not found: ${r}`);if(!H.statSync(r).isDirectory())throw new Error(`Not a directory: ${r}`);let p=me(r,i?.globPattern);return p.length===0?{total:0,uploaded:0,queued:0,failed:0,files:[]}:ge(n,t,e,p,{concurrency:i?.concurrency,process:i?.process,processOptions:i?.processOptions,onFileStatus:i?.onFileStatus})}var ze=1e3,Xe=1e4,Ke=1.5,Ye=3e5,Qe=["COMPLETED","FAILED","STALLED"],G=class{constructor(t){this.queue=t}queue;async*poll(t,e){let s=e?.intervalMs??ze,i=e?.maxIntervalMs??Xe,r=e?.backoffMultiplier??Ke,a=e?.timeoutMs??Ye,p=s,u=Date.now(),c;for(;;){if(Date.now()-u>a)throw new U(`Polling timed out after ${Math.round(a/1e3)}s for job ${t}`);let g=await this.queue.getStatus(t);if(g.status!==c&&(c=g.status,e?.onStatus?.(g),yield g),Qe.includes(g.status))return;await new Promise(y=>setTimeout(y,p)),p=Math.min(p*r,i)}}async waitForCompletion(t,e){let s;for await(let i of this.poll(t,e))s=i;if(!s)throw new Error(`No status received for job ${t}`);return s}};var kt=class{http;documents;projects;deployments;tables;extractions;queue;classify;split;schema;buckets;agents;vision;validations;labels;constructor(t){this.http=new M({apiUrl:t.apiUrl,token:t.token}),this.documents=new gt(this.http),this.projects=new mt(this.http),this.deployments=new ht(this.http),this.tables=new ft(this.http),this.extractions=new Rt(this.http),this.queue=new wt(this.http),this.classify=new Ct(this.http),this.split=new vt(this.http),this.schema=new St(this.http),this.buckets=new xt(this.http),this.agents=new Pt(this.http),this.vision=new $t(this.http),this.validations=new Et(this.http),this.labels=new Tt(this.http)}async uploadFile(t,e,s){return It(this.http,this.documents,t,e,s)}async uploadFolder(t,e,s){return he(this.http,this.documents,t,e,s)}async processAndWait(t,e,s){let i=await this.documents.processAsync(t,e,s?.processOptions),r=new G(this.queue),a;for await(let p of r.poll(i.jobId,s?.pollOptions))a=p;if(!a||a.status==="FAILED")throw new Error(`Extraction failed for file ${e}${a?`: ${a.status}`:""}`);return this.documents.getFileData(e,t)}async*downloadAll(t,e){yield*this.extractions.getAllRows(t,e)}};var x=$(require("fs")),Z=$(require("path")),fe=$(require("os")),Ot=require("child_process"),Ht=Z.join(fe.homedir(),".limai"),Q=Z.join(Ht,"config.json"),Ze=".limai.token",q;function ye(){if(q!==void 0)return q;try{let n=(0,Ot.execSync)("git rev-parse --show-toplevel",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!x.existsSync(Z.join(n,"packages","cli")))return q=null,null;let t=(0,Ot.execSync)("git rev-parse --git-common-dir",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),e="";if(t!==".git"){let s=(0,Ot.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(s){let i=s.replace(/[/\\]/g,"-").replace(/[^a-zA-Z0-9._-]/g,"").replace(/^-+|-+$/g,"");i&&(e=`${i}.`)}}return q={root:n,apiUrl:`https://${e}tables.localhost`,sseUrl:`https://${e}ws.localhost`},q}catch{return q=null,null}}function ts(){let n=ye();if(!n)return;let t=Z.join(n.root,Ze);if(x.existsSync(t))return x.readFileSync(t,"utf-8").trim()}function Jt(){let n=process.env.LIMAI_API_TOKEN,t=process.env.LIMAI_API_URL,e=process.env.LIMAI_SSE_URL,s={};if(x.existsSync(Q))try{let u=x.readFileSync(Q,"utf-8"),c=JSON.parse(u);c&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}let i=ye(),r=n||ts()||s.token,a=t||s.apiUrl||i?.apiUrl||process.env.LIMAI_BUILD_URL||void 0,p=e||s.sseUrl||i?.sseUrl||void 0;return!r||!a?null:{token:r,apiUrl:a,sseUrl:p,defaultProjectId:s.defaultProjectId,defaultDeploymentId:s.defaultDeploymentId}}function be(n){let t={};if(x.existsSync(Q))try{let s=x.readFileSync(Q,"utf-8");t=JSON.parse(s)}catch{t={}}let e={...t,...n};x.existsSync(Ht)||x.mkdirSync(Ht,{recursive:!0,mode:448}),x.writeFileSync(Q,JSON.stringify(e,null,2),{mode:384})}function Re(){let n=Jt();return n||(console.error("Not authenticated. Run `npm run cli:setup` or set LIMAI_API_TOKEN environment variable."),process.exit(1)),n}var jt=class extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}},we=10,es=13,L=32;function Gt(n){}function Se(n){if(typeof n=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Gt,onError:e=Gt,onRetry:s=Gt,onComment:i}=n,r=[],a=!0,p,u="",c=0,g;function y(l){if(a&&(a=!1,l.charCodeAt(0)===239&&l.charCodeAt(1)===187&&l.charCodeAt(2)===191&&(l=l.slice(3))),r.length===0){let C=m(l);C!==""&&r.push(C);return}if(l.indexOf(`
2
2
  `)===-1&&l.indexOf("\r")===-1){r.push(l);return}r.push(l);let o=r.join("");r.length=0;let d=m(o);d!==""&&r.push(d)}function m(l){let o=0;if(l.indexOf("\r")===-1){let d=l.indexOf(`
3
3
  `,o);for(;d!==-1;){if(o===d){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0,o=d+1,d=l.indexOf(`
4
- `,o);continue}let C=l.charCodeAt(o);if(we(l,o,C)){let v=l.charCodeAt(o+5)===L?o+6:o+5,j=l.slice(v,d);if(c===0&&l.charCodeAt(d+1)===Re){t({id:p,event:g,data:j}),p=void 0,u="",g=void 0,o=d+2,d=l.indexOf(`
4
+ `,o);continue}let C=l.charCodeAt(o);if(Ce(l,o,C)){let v=l.charCodeAt(o+5)===L?o+6:o+5,j=l.slice(v,d);if(c===0&&l.charCodeAt(d+1)===we){t({id:p,event:g,data:j}),p=void 0,u="",g=void 0,o=d+2,d=l.indexOf(`
5
5
  `,o);continue}u=c===0?j:`${u}
6
- ${j}`,c++}else Ce(l,o,C)?g=l.slice(l.charCodeAt(o+6)===L?o+7:o+6,d)||void 0:S(l,o,d);o=d+1,d=l.indexOf(`
6
+ ${j}`,c++}else ve(l,o,C)?g=l.slice(l.charCodeAt(o+6)===L?o+7:o+6,d)||void 0:S(l,o,d);o=d+1,d=l.indexOf(`
7
7
  `,o)}return l.slice(o)}for(;o<l.length;){let d=l.indexOf("\r",o),C=l.indexOf(`
8
- `,o),v=-1;if(d!==-1&&C!==-1?v=d<C?d:C:d!==-1?d===l.length-1?v=-1:v=d:C!==-1&&(v=C),v===-1)break;S(l,o,v),o=v+1,l.charCodeAt(o-1)===ts&&l.charCodeAt(o)===Re&&o++}return l.slice(o)}function S(l,o,d){if(o===d){I();return}let C=l.charCodeAt(o);if(we(l,o,C)){let F=l.charCodeAt(o+5)===L?o+6:o+5,Zt=l.slice(F,d);u=c===0?Zt:`${u}
9
- ${Zt}`,c++;return}if(Ce(l,o,C)){g=l.slice(l.charCodeAt(o+6)===L?o+7:o+6,d)||void 0;return}if(C===105&&l.charCodeAt(o+1)===100&&l.charCodeAt(o+2)===58){let F=l.slice(l.charCodeAt(o+3)===L?o+4:o+3,d);p=F.includes("\0")?void 0:F;return}if(C===58){if(i){let F=l.slice(o,d);i(F.slice(l.charCodeAt(o+1)===L?2:1))}return}let v=l.slice(o,d),j=v.indexOf(":");if(j===-1){f(v,"",v);return}let Ie=v.slice(0,j),ke=v.charCodeAt(j+1)===L?2:1,Oe=v.slice(j+ke);f(Ie,Oe,v)}function f(l,o,d){switch(l){case"event":g=o||void 0;break;case"data":u=c===0?o:`${u}
10
- ${o}`,c++;break;case"id":p=o.includes("\0")?void 0:o;break;case"retry":/^\d+$/.test(o)?s(parseInt(o,10)):e(new Ot(`Invalid \`retry\` value: "${o}"`,{type:"invalid-retry",value:o,line:d}));break;default:e(new Ot(`Unknown field "${l.length>20?`${l.slice(0,20)}\u2026`:l}"`,{type:"unknown-field",field:l,value:o,line:d}));break}}function I(){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0}function T(l={}){if(l.consume&&r.length>0){let o=r.join("");S(o,0,o.length)}a=!0,p=void 0,u="",c=0,g=void 0,r.length=0}return{feed:y,reset:T}}function we(n,t,e){return e===100&&n.charCodeAt(t+1)===97&&n.charCodeAt(t+2)===116&&n.charCodeAt(t+3)===97&&n.charCodeAt(t+4)===58}function Ce(n,t,e){return e===101&&n.charCodeAt(t+1)===118&&n.charCodeAt(t+2)===101&&n.charCodeAt(t+3)===110&&n.charCodeAt(t+4)===116&&n.charCodeAt(t+5)===58}var Ut=class extends Event{constructor(t,e){var s,i;super(t),this.code=(s=e?.code)!=null?s:void 0,this.message=(i=e?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,e,s){return s(Se(this),e)}[Symbol.for("Deno.customInspect")](t,e){return t(Se(this),e)}};function es(n){let t=globalThis.DOMException;return typeof t=="function"?new t(n,"SyntaxError"):new SyntaxError(n)}function qt(n){return n instanceof Error?"errors"in n&&Array.isArray(n.errors)?n.errors.map(qt).join(", "):"cause"in n&&n.cause instanceof Error?`${n}: ${qt(n.cause)}`:n.message:`${n}`}function Se(n){return{type:n.type,message:n.message,code:n.code,defaultPrevented:n.defaultPrevented,cancelable:n.cancelable,timeStamp:n.timeStamp}}var Pe=n=>{throw TypeError(n)},Qt=(n,t,e)=>t.has(n)||Pe("Cannot "+e),h=(n,t,e)=>(Qt(n,t,"read from private field"),e?e.call(n):t.get(n)),w=(n,t,e)=>t.has(n)?Pe("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),b=(n,t,e,s)=>(Qt(n,t,"write to private field"),t.set(n,e),e),O=(n,t,e)=>(Qt(n,t,"access private method"),e),P,_,V,jt,Dt,st,X,nt,U,W,K,z,tt,E,Gt,Vt,Wt,xe,zt,Xt,et,Kt,Yt,N=class extends EventTarget{constructor(t,e){var s,i;super(),w(this,E),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,w(this,P),w(this,_),w(this,V),w(this,jt),w(this,Dt),w(this,st),w(this,X),w(this,nt,null),w(this,U),w(this,W),w(this,K,null),w(this,z,null),w(this,tt,null),w(this,Vt,async r=>{var a;h(this,W).reset();let{body:p,redirected:u,status:c,headers:g}=r;if(c===204){O(this,E,et).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?b(this,V,new URL(r.url)):b(this,V,void 0),c!==200){O(this,E,et).call(this,`Non-200 status code (${c})`,c);return}if(!(g.get("content-type")||"").startsWith("text/event-stream")){O(this,E,et).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(h(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let y=new Event("open");if((a=h(this,tt))==null||a.call(this,y),this.dispatchEvent(y),typeof p!="object"||!p||!("getReader"in p)){O(this,E,et).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,S=p.getReader(),f=!0;do{let{done:I,value:T}=await S.read();T&&h(this,W).feed(m.decode(T,{stream:!I})),I&&(f=!1,h(this,W).reset(),O(this,E,Kt).call(this))}while(f)}),w(this,Wt,r=>{b(this,U,void 0),!(r.name==="AbortError"||r.type==="aborted")&&O(this,E,Kt).call(this,qt(r))}),w(this,zt,r=>{typeof r.id=="string"&&b(this,nt,r.id);let a=new MessageEvent(r.event||"message",{data:r.data,origin:h(this,V)?h(this,V).origin:h(this,_).origin,lastEventId:r.id||""});h(this,z)&&(!r.event||r.event==="message")&&h(this,z).call(this,a),this.dispatchEvent(a)}),w(this,Xt,r=>{b(this,st,r)}),w(this,Yt,()=>{b(this,X,void 0),h(this,P)===this.CONNECTING&&O(this,E,Gt).call(this)});try{if(t instanceof URL)b(this,_,t);else if(typeof t=="string")b(this,_,new URL(t,ss()));else throw new Error("Invalid URL")}catch{throw es("An invalid or illegal string was specified")}b(this,W,ve({onEvent:h(this,zt),onRetry:h(this,Xt)})),b(this,P,this.CONNECTING),b(this,st,3e3),b(this,Dt,(s=e?.fetch)!=null?s:globalThis.fetch),b(this,jt,(i=e?.withCredentials)!=null?i:!1),O(this,E,Gt).call(this)}get readyState(){return h(this,P)}get url(){return h(this,_).href}get withCredentials(){return h(this,jt)}get onerror(){return h(this,K)}set onerror(t){b(this,K,t)}get onmessage(){return h(this,z)}set onmessage(t){b(this,z,t)}get onopen(){return h(this,tt)}set onopen(t){b(this,tt,t)}addEventListener(t,e,s){let i=e;super.addEventListener(t,i,s)}removeEventListener(t,e,s){let i=e;super.removeEventListener(t,i,s)}close(){h(this,X)&&clearTimeout(h(this,X)),h(this,P)!==this.CLOSED&&(h(this,U)&&h(this,U).abort(),b(this,P,this.CLOSED),b(this,U,void 0))}};P=new WeakMap,_=new WeakMap,V=new WeakMap,jt=new WeakMap,Dt=new WeakMap,st=new WeakMap,X=new WeakMap,nt=new WeakMap,U=new WeakMap,W=new WeakMap,K=new WeakMap,z=new WeakMap,tt=new WeakMap,E=new WeakSet,Gt=function(){b(this,P,this.CONNECTING),b(this,U,new AbortController),h(this,Dt)(h(this,_),O(this,E,xe).call(this)).then(h(this,Vt)).catch(h(this,Wt))},Vt=new WeakMap,Wt=new WeakMap,xe=function(){var n;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...h(this,nt)?{"Last-Event-ID":h(this,nt)}:void 0},cache:"no-store",signal:(n=h(this,U))==null?void 0:n.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},zt=new WeakMap,Xt=new WeakMap,et=function(n,t){var e;h(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s)},Kt=function(n,t){var e;if(h(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s),b(this,X,setTimeout(h(this,Yt),h(this,st)))},Yt=new WeakMap,N.CONNECTING=0,N.OPEN=1,N.CLOSED=2;function ss(){let n="document"in globalThis?globalThis.document:void 0;return n&&typeof n=="object"&&"baseURI"in n&&typeof n.baseURI=="string"?n.baseURI:void 0}var Lt=class{eventSource=null;handlers=new Map;config;reconnectAttempts=0;maxReconnectAttempts=10;baseReconnectDelay=1e3;connected=!1;constructor(t){this.config={...t,sessionId:t.sessionId??crypto.randomUUID()}}async connect(){return new Promise((t,e)=>{let s=new URL("/events",this.config.sseUrl);s.searchParams.set("sessionId",this.config.sessionId),this.eventSource=new N(s.toString(),{fetch:(i,r)=>fetch(i,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}),this.eventSource.onopen=()=>{this.connected=!0,this.reconnectAttempts=0,t()},this.eventSource.onerror=()=>{if(!this.connected){e(new Error("Failed to connect to SSE server"));return}this.handleReconnect()},this.eventSource.onmessage=i=>{try{let r=JSON.parse(i.data);this.dispatchEvent(r)}catch{}}})}async subscribe(t){if(!this.connected)throw new Error("Not connected to SSE server");let e=new URL("/subscribe",this.config.sseUrl),s=await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})});if(!s.ok)throw new Error(`Failed to subscribe to project ${t}: ${s.status}`)}async unsubscribe(t){if(!this.connected)return;let e=new URL("/unsubscribe",this.config.sseUrl);await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})})}on(t,e){let s=t;return this.handlers.has(s)||this.handlers.set(s,new Set),this.handlers.get(s).add(e),()=>{this.handlers.get(s)?.delete(e)}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.connected=!1,this.handlers.clear()}get isConnected(){return this.connected}dispatchEvent(t){let e={type:t.type,data:t.data??t,timestamp:t.timestamp??new Date().toISOString(),sequenceNumber:t.sequenceNumber},s=this.handlers.get(e.type);if(s)for(let r of s)r(e);let i=this.handlers.get("*");if(i)for(let r of i)r(e)}handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.disconnect();return}this.eventSource&&(this.eventSource.close(),this.eventSource=null);let t=this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{this.handleReconnect()})},t)}};var _t=$(require("fs")),it=$(require("path"));var ns=["JOB_CONTEXT.json",it.join(process.env.HOME||"/home/daytona","JOB_CONTEXT.json")];function rt(n){let t=n?[it.resolve(n)]:ns.map(e=>it.resolve(e));for(let e of t)if(_t.existsSync(e)){let s=_t.readFileSync(e,"utf-8"),i;try{i=JSON.parse(s)}catch{throw new A(`Invalid JSON in ${e}`)}return is(i,e),i}throw new R("JOB_CONTEXT.json not found. Searched: "+t.join(", "),{code:"JOB_CONTEXT_NOT_FOUND",exitCode:1})}function is(n,t){let e=[];if(n.jobId||e.push("jobId"),n.fileId||e.push("fileId"),n.fileName||e.push("fileName"),n.sourceFileUrl||e.push("sourceFileUrl"),n.deploymentId||e.push("deploymentId"),n.extractionSchemaId||e.push("extractionSchemaId"),e.length>0)throw new A(`JOB_CONTEXT.json (${t}) missing required fields: ${e.join(", ")}`);if(!n.schema||!Array.isArray(n.schema.tables)||n.schema.tables.length===0)throw new A(`JOB_CONTEXT.json (${t}) must have schema.tables with at least one table`);for(let s of n.schema.tables){if(!s.id||!s.name)throw new A("JOB_CONTEXT.json: table missing id or name");if(!Array.isArray(s.columns)||s.columns.length===0)throw new A(`JOB_CONTEXT.json: table "${s.name}" has no columns`)}}function $e(n){let t=process.env.LIMAI_JOB_ID;return t||rt(n).jobId}function Ee(n){let t=process.env.LIMAI_FILE_ID;return t||rt(n).fileId}function Te(n){let t=process.env.LIMAI_DEPLOYMENT_ID;return t||rt(n).deploymentId}function Ae(n,t){let e=[],s=[],i=[],r=0;if(!n||typeof n!="object")return{valid:!1,errors:["Submission must be a JSON object"],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};if(!n.tables||typeof n.tables!="object")return{valid:!1,errors:['Submission must have a "tables" object'],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};let a=new Map;for(let u of t.schema.tables)a.set(u.name,u);let p=Object.keys(n.tables);for(let u of p){let c=a.get(u);if(!c){e.push(`Table "${u}" not found in schema. Available tables: ${[...a.keys()].join(", ")}`);continue}let g=n.tables[u];if(!Array.isArray(g)){e.push(`Table "${u}": rows must be an array`);continue}let y=!c.isPrimary,m=new Set(c.columns.map(f=>f.name)),S=new Map(c.columns.map(f=>[f.name,f]));for(let f=0;f<g.length;f++){let I=g[f];rs(I,f,u,y,m,S,e,s)}i.push({name:u,rowCount:g.length,isChild:y}),r+=g.length}for(let u of t.schema.tables)p.includes(u.name)||s.push(`Schema table "${u.name}" has no data in submission`);return{valid:e.length===0,errors:e,warnings:s,summary:{tablesFound:p.length,totalRows:r,tableDetails:i}}}function rs(n,t,e,s,i,r,a,p){let u=`Table "${e}" row ${t}`;if(typeof n!="object"||n===null){a.push(`${u}: must be an object`);return}if(typeof n.index!="number"&&a.push(`${u}: missing or invalid "index" (must be a number)`),!n.cells||typeof n.cells!="object"){a.push(`${u}: missing or invalid "cells" object`);return}s&&(n.parentIndex===void 0||n.parentIndex===null)&&a.push(`${u}: child table rows must have "parentIndex"`),s&&n.parentIndex!==void 0&&typeof n.parentIndex!="number"&&a.push(`${u}: "parentIndex" must be a number`);let c=Object.keys(n.cells);if(c.length===0){a.push(`${u}: cells object is empty`);return}let g=0;for(let y of c)if(!i.has(y))p.push(`${u}: unknown column "${y}" (will be skipped by API)`);else{g++;let m=r.get(y);m&&os(n.cells[y],y,m.type,m.isList,u,p)}g===0&&a.push(`${u}: no cell keys match any schema column`)}function os(n,t,e,s,i,r){if(n!=null){if(s&&!Array.isArray(n)){r.push(`${i}: column "${t}" is a LIST but value is not an array`);return}switch(e){case"NUMBER":typeof n!="number"&&typeof n!="string"&&r.push(`${i}: column "${t}" (NUMBER) has unexpected type ${typeof n}`);break;case"BOOLEAN":typeof n!="boolean"&&r.push(`${i}: column "${t}" (BOOLEAN) has unexpected type ${typeof n}`);break;case"DATE":typeof n!="string"&&r.push(`${i}: column "${t}" (DATE) should be an ISO date string`);break;case"LIST":Array.isArray(n)||r.push(`${i}: column "${t}" (LIST) should be an array`);break}}}0&&(module.exports={AuthError,ConflictError,ForbiddenError,HttpClient,JobPoller,LimaiClient,LimaiError,NotFoundError,RateLimitError,SSEClient,ServerError,TimeoutError,UploadError,ValidationError,collectAll,getDeploymentId,getFileId,getJobId,loadConfig,loadJobContext,mapHttpError,paginateOffset,paginatePage,requireConfig,saveConfig,validateSubmission});
8
+ `,o),v=-1;if(d!==-1&&C!==-1?v=d<C?d:C:d!==-1?d===l.length-1?v=-1:v=d:C!==-1&&(v=C),v===-1)break;S(l,o,v),o=v+1,l.charCodeAt(o-1)===es&&l.charCodeAt(o)===we&&o++}return l.slice(o)}function S(l,o,d){if(o===d){I();return}let C=l.charCodeAt(o);if(Ce(l,o,C)){let N=l.charCodeAt(o+5)===L?o+6:o+5,te=l.slice(N,d);u=c===0?te:`${u}
9
+ ${te}`,c++;return}if(ve(l,o,C)){g=l.slice(l.charCodeAt(o+6)===L?o+7:o+6,d)||void 0;return}if(C===105&&l.charCodeAt(o+1)===100&&l.charCodeAt(o+2)===58){let N=l.slice(l.charCodeAt(o+3)===L?o+4:o+3,d);p=N.includes("\0")?void 0:N;return}if(C===58){if(i){let N=l.slice(o,d);i(N.slice(l.charCodeAt(o+1)===L?2:1))}return}let v=l.slice(o,d),j=v.indexOf(":");if(j===-1){f(v,"",v);return}let ke=v.slice(0,j),Oe=v.charCodeAt(j+1)===L?2:1,je=v.slice(j+Oe);f(ke,je,v)}function f(l,o,d){switch(l){case"event":g=o||void 0;break;case"data":u=c===0?o:`${u}
10
+ ${o}`,c++;break;case"id":p=o.includes("\0")?void 0:o;break;case"retry":/^\d+$/.test(o)?s(parseInt(o,10)):e(new jt(`Invalid \`retry\` value: "${o}"`,{type:"invalid-retry",value:o,line:d}));break;default:e(new jt(`Unknown field "${l.length>20?`${l.slice(0,20)}\u2026`:l}"`,{type:"unknown-field",field:l,value:o,line:d}));break}}function I(){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0}function T(l={}){if(l.consume&&r.length>0){let o=r.join("");S(o,0,o.length)}a=!0,p=void 0,u="",c=0,g=void 0,r.length=0}return{feed:y,reset:T}}function Ce(n,t,e){return e===100&&n.charCodeAt(t+1)===97&&n.charCodeAt(t+2)===116&&n.charCodeAt(t+3)===97&&n.charCodeAt(t+4)===58}function ve(n,t,e){return e===101&&n.charCodeAt(t+1)===118&&n.charCodeAt(t+2)===101&&n.charCodeAt(t+3)===110&&n.charCodeAt(t+4)===116&&n.charCodeAt(t+5)===58}var Ut=class extends Event{constructor(t,e){var s,i;super(t),this.code=(s=e?.code)!=null?s:void 0,this.message=(i=e?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,e,s){return s(xe(this),e)}[Symbol.for("Deno.customInspect")](t,e){return t(xe(this),e)}};function ss(n){let t=globalThis.DOMException;return typeof t=="function"?new t(n,"SyntaxError"):new SyntaxError(n)}function qt(n){return n instanceof Error?"errors"in n&&Array.isArray(n.errors)?n.errors.map(qt).join(", "):"cause"in n&&n.cause instanceof Error?`${n}: ${qt(n.cause)}`:n.message:`${n}`}function xe(n){return{type:n.type,message:n.message,code:n.code,defaultPrevented:n.defaultPrevented,cancelable:n.cancelable,timeStamp:n.timeStamp}}var $e=n=>{throw TypeError(n)},Zt=(n,t,e)=>t.has(n)||$e("Cannot "+e),h=(n,t,e)=>(Zt(n,t,"read from private field"),e?e.call(n):t.get(n)),w=(n,t,e)=>t.has(n)?$e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),b=(n,t,e,s)=>(Zt(n,t,"write to private field"),t.set(n,e),e),O=(n,t,e)=>(Zt(n,t,"access private method"),e),P,_,V,Dt,Lt,st,X,nt,D,W,K,z,tt,E,Vt,Wt,zt,Pe,Xt,Kt,et,Yt,Qt,F=class extends EventTarget{constructor(t,e){var s,i;super(),w(this,E),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,w(this,P),w(this,_),w(this,V),w(this,Dt),w(this,Lt),w(this,st),w(this,X),w(this,nt,null),w(this,D),w(this,W),w(this,K,null),w(this,z,null),w(this,tt,null),w(this,Wt,async r=>{var a;h(this,W).reset();let{body:p,redirected:u,status:c,headers:g}=r;if(c===204){O(this,E,et).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?b(this,V,new URL(r.url)):b(this,V,void 0),c!==200){O(this,E,et).call(this,`Non-200 status code (${c})`,c);return}if(!(g.get("content-type")||"").startsWith("text/event-stream")){O(this,E,et).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(h(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let y=new Event("open");if((a=h(this,tt))==null||a.call(this,y),this.dispatchEvent(y),typeof p!="object"||!p||!("getReader"in p)){O(this,E,et).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,S=p.getReader(),f=!0;do{let{done:I,value:T}=await S.read();T&&h(this,W).feed(m.decode(T,{stream:!I})),I&&(f=!1,h(this,W).reset(),O(this,E,Yt).call(this))}while(f)}),w(this,zt,r=>{b(this,D,void 0),!(r.name==="AbortError"||r.type==="aborted")&&O(this,E,Yt).call(this,qt(r))}),w(this,Xt,r=>{typeof r.id=="string"&&b(this,nt,r.id);let a=new MessageEvent(r.event||"message",{data:r.data,origin:h(this,V)?h(this,V).origin:h(this,_).origin,lastEventId:r.id||""});h(this,z)&&(!r.event||r.event==="message")&&h(this,z).call(this,a),this.dispatchEvent(a)}),w(this,Kt,r=>{b(this,st,r)}),w(this,Qt,()=>{b(this,X,void 0),h(this,P)===this.CONNECTING&&O(this,E,Vt).call(this)});try{if(t instanceof URL)b(this,_,t);else if(typeof t=="string")b(this,_,new URL(t,ns()));else throw new Error("Invalid URL")}catch{throw ss("An invalid or illegal string was specified")}b(this,W,Se({onEvent:h(this,Xt),onRetry:h(this,Kt)})),b(this,P,this.CONNECTING),b(this,st,3e3),b(this,Lt,(s=e?.fetch)!=null?s:globalThis.fetch),b(this,Dt,(i=e?.withCredentials)!=null?i:!1),O(this,E,Vt).call(this)}get readyState(){return h(this,P)}get url(){return h(this,_).href}get withCredentials(){return h(this,Dt)}get onerror(){return h(this,K)}set onerror(t){b(this,K,t)}get onmessage(){return h(this,z)}set onmessage(t){b(this,z,t)}get onopen(){return h(this,tt)}set onopen(t){b(this,tt,t)}addEventListener(t,e,s){let i=e;super.addEventListener(t,i,s)}removeEventListener(t,e,s){let i=e;super.removeEventListener(t,i,s)}close(){h(this,X)&&clearTimeout(h(this,X)),h(this,P)!==this.CLOSED&&(h(this,D)&&h(this,D).abort(),b(this,P,this.CLOSED),b(this,D,void 0))}};P=new WeakMap,_=new WeakMap,V=new WeakMap,Dt=new WeakMap,Lt=new WeakMap,st=new WeakMap,X=new WeakMap,nt=new WeakMap,D=new WeakMap,W=new WeakMap,K=new WeakMap,z=new WeakMap,tt=new WeakMap,E=new WeakSet,Vt=function(){b(this,P,this.CONNECTING),b(this,D,new AbortController),h(this,Lt)(h(this,_),O(this,E,Pe).call(this)).then(h(this,Wt)).catch(h(this,zt))},Wt=new WeakMap,zt=new WeakMap,Pe=function(){var n;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...h(this,nt)?{"Last-Event-ID":h(this,nt)}:void 0},cache:"no-store",signal:(n=h(this,D))==null?void 0:n.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Xt=new WeakMap,Kt=new WeakMap,et=function(n,t){var e;h(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s)},Yt=function(n,t){var e;if(h(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s),b(this,X,setTimeout(h(this,Qt),h(this,st)))},Qt=new WeakMap,F.CONNECTING=0,F.OPEN=1,F.CLOSED=2;function ns(){let n="document"in globalThis?globalThis.document:void 0;return n&&typeof n=="object"&&"baseURI"in n&&typeof n.baseURI=="string"?n.baseURI:void 0}var _t=class{eventSource=null;handlers=new Map;config;reconnectAttempts=0;maxReconnectAttempts=10;baseReconnectDelay=1e3;connected=!1;constructor(t){this.config={...t,sessionId:t.sessionId??crypto.randomUUID()}}async connect(){return new Promise((t,e)=>{let s=new URL("/events",this.config.sseUrl);s.searchParams.set("sessionId",this.config.sessionId),this.eventSource=new F(s.toString(),{fetch:(i,r)=>fetch(i,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}),this.eventSource.onopen=()=>{this.connected=!0,this.reconnectAttempts=0,t()},this.eventSource.onerror=()=>{if(!this.connected){e(new Error("Failed to connect to SSE server"));return}this.handleReconnect()},this.eventSource.onmessage=i=>{try{let r=JSON.parse(i.data);this.dispatchEvent(r)}catch{}}})}async subscribe(t){if(!this.connected)throw new Error("Not connected to SSE server");let e=new URL("/subscribe",this.config.sseUrl),s=await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})});if(!s.ok)throw new Error(`Failed to subscribe to project ${t}: ${s.status}`)}async unsubscribe(t){if(!this.connected)return;let e=new URL("/unsubscribe",this.config.sseUrl);await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})})}on(t,e){let s=t;return this.handlers.has(s)||this.handlers.set(s,new Set),this.handlers.get(s).add(e),()=>{this.handlers.get(s)?.delete(e)}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.connected=!1,this.handlers.clear()}get isConnected(){return this.connected}dispatchEvent(t){let e={type:t.type,data:t.data??t,timestamp:t.timestamp??new Date().toISOString(),sequenceNumber:t.sequenceNumber},s=this.handlers.get(e.type);if(s)for(let r of s)r(e);let i=this.handlers.get("*");if(i)for(let r of i)r(e)}handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.disconnect();return}this.eventSource&&(this.eventSource.close(),this.eventSource=null);let t=this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{this.handleReconnect()})},t)}};var Ft=$(require("fs")),it=$(require("path"));var is=["JOB_CONTEXT.json",it.join(process.env.HOME||"/home/daytona","JOB_CONTEXT.json")];function rt(n){let t=n?[it.resolve(n)]:is.map(e=>it.resolve(e));for(let e of t)if(Ft.existsSync(e)){let s=Ft.readFileSync(e,"utf-8"),i;try{i=JSON.parse(s)}catch{throw new A(`Invalid JSON in ${e}`)}return rs(i,e),i}throw new R("JOB_CONTEXT.json not found. Searched: "+t.join(", "),{code:"JOB_CONTEXT_NOT_FOUND",exitCode:1})}function rs(n,t){let e=[];if(n.jobId||e.push("jobId"),n.fileId||e.push("fileId"),n.fileName||e.push("fileName"),n.sourceFileUrl||e.push("sourceFileUrl"),n.deploymentId||e.push("deploymentId"),n.extractionSchemaId||e.push("extractionSchemaId"),e.length>0)throw new A(`JOB_CONTEXT.json (${t}) missing required fields: ${e.join(", ")}`);if(!n.schema||!Array.isArray(n.schema.tables)||n.schema.tables.length===0)throw new A(`JOB_CONTEXT.json (${t}) must have schema.tables with at least one table`);for(let s of n.schema.tables){if(!s.id||!s.name)throw new A("JOB_CONTEXT.json: table missing id or name");if(!Array.isArray(s.columns)||s.columns.length===0)throw new A(`JOB_CONTEXT.json: table "${s.name}" has no columns`)}}function Ee(n){let t=process.env.LIMAI_JOB_ID;return t||rt(n).jobId}function Te(n){let t=process.env.LIMAI_FILE_ID;return t||rt(n).fileId}function Ae(n){let t=process.env.LIMAI_DEPLOYMENT_ID;return t||rt(n).deploymentId}function Ie(n,t){let e=[],s=[],i=[],r=0;if(!n||typeof n!="object")return{valid:!1,errors:["Submission must be a JSON object"],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};if(!n.tables||typeof n.tables!="object")return{valid:!1,errors:['Submission must have a "tables" object'],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};let a=new Map;for(let u of t.schema.tables)a.set(u.name,u);let p=Object.keys(n.tables);for(let u of p){let c=a.get(u);if(!c){e.push(`Table "${u}" not found in schema. Available tables: ${[...a.keys()].join(", ")}`);continue}let g=n.tables[u];if(!Array.isArray(g)){e.push(`Table "${u}": rows must be an array`);continue}let y=!c.isPrimary,m=new Set(c.columns.map(f=>f.name)),S=new Map(c.columns.map(f=>[f.name,f]));for(let f=0;f<g.length;f++){let I=g[f];os(I,f,u,y,m,S,e,s)}i.push({name:u,rowCount:g.length,isChild:y}),r+=g.length}for(let u of t.schema.tables)p.includes(u.name)||s.push(`Schema table "${u.name}" has no data in submission`);return{valid:e.length===0,errors:e,warnings:s,summary:{tablesFound:p.length,totalRows:r,tableDetails:i}}}function os(n,t,e,s,i,r,a,p){let u=`Table "${e}" row ${t}`;if(typeof n!="object"||n===null){a.push(`${u}: must be an object`);return}if(typeof n.index!="number"&&a.push(`${u}: missing or invalid "index" (must be a number)`),!n.cells||typeof n.cells!="object"){a.push(`${u}: missing or invalid "cells" object`);return}s&&(n.parentIndex===void 0||n.parentIndex===null)&&a.push(`${u}: child table rows must have "parentIndex"`),s&&n.parentIndex!==void 0&&typeof n.parentIndex!="number"&&a.push(`${u}: "parentIndex" must be a number`);let c=Object.keys(n.cells);if(c.length===0){a.push(`${u}: cells object is empty`);return}let g=0;for(let y of c)if(!i.has(y))p.push(`${u}: unknown column "${y}" (will be skipped by API)`);else{g++;let m=r.get(y);m&&as(n.cells[y],y,m.type,m.isList,u,p)}g===0&&a.push(`${u}: no cell keys match any schema column`)}function as(n,t,e,s,i,r){if(n!=null){if(s&&!Array.isArray(n)){r.push(`${i}: column "${t}" is a LIST but value is not an array`);return}switch(e){case"NUMBER":typeof n!="number"&&typeof n!="string"&&r.push(`${i}: column "${t}" (NUMBER) has unexpected type ${typeof n}`);break;case"BOOLEAN":typeof n!="boolean"&&r.push(`${i}: column "${t}" (BOOLEAN) has unexpected type ${typeof n}`);break;case"DATE":typeof n!="string"&&r.push(`${i}: column "${t}" (DATE) should be an ISO date string`);break;case"LIST":Array.isArray(n)||r.push(`${i}: column "${t}" (LIST) should be an array`);break}}}0&&(module.exports={AuthError,ConflictError,ForbiddenError,HttpClient,JobPoller,LimaiClient,LimaiError,NotFoundError,RateLimitError,SSEClient,ServerError,TimeoutError,UploadError,ValidationError,collectAll,getDeploymentId,getFileId,getJobId,loadConfig,loadJobContext,mapHttpError,paginateOffset,paginatePage,requireConfig,saveConfig,validateSubmission});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limai.io/cli",
3
- "version": "0.1.1",
3
+ "version": "0.4.0",
4
4
  "description": "CLI and SDK for the LimAI data extraction platform",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -34,7 +34,6 @@
34
34
  "devDependencies": {
35
35
  "@types/cli-progress": "^3.11.6",
36
36
  "@types/node": "^22.15.3",
37
- "chalk": "^5.4.1",
38
37
  "cli-progress": "^3.12.0",
39
38
  "commander": "^13.1.0",
40
39
  "eventsource": "^3.0.6",