@superglue/cli 1.1.93 → 1.1.94
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.
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "superglue",
|
|
3
3
|
"description": "Build, test, and manage superglue tools via the sg CLI. Use when working with superglue tools, systems, APIs, SDKs, or the sg command.",
|
|
4
|
-
"version": "1.1.
|
|
4
|
+
"version": "1.1.94",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "superglue",
|
|
7
7
|
"email": "hello@superglue.cloud"
|
package/dist/cli.js
CHANGED
|
@@ -1054,7 +1054,7 @@ DEPRECATED ENDPOINTS: GET /user/{email} and GET /members are deprecated; use V2
|
|
|
1054
1054
|
${e.join(`
|
|
1055
1055
|
`)}`}function aV({payload:o,tool:e}){let t=[],a=new Set(mo.RESERVED_RUNTIME_KEYS),i=new Set(mo.PAGINATION_RUNTIME_KEYS),r=new Set((e.steps||[]).map(c=>c.id).filter(Boolean)),s=Eb(e),n=(0,rI.getToolSystemIds)(e).map(c=>`${c}_`);for(let c of Object.keys(o)){a.has(c)&&t.push({key:c,kind:"reserved",message:`Payload key "${c}" collides with ${nI(c)}, which the runtime injects into sourceData. Remove or rename it.`}),r.has(c)&&t.push({key:c,kind:"step-id",message:`Payload key "${c}" has the same name as a step id. The step result overwrites the payload value in sourceData after that step runs. Remove or rename it.`}),s&&i.has(c)&&t.push({key:c,kind:"pagination",message:`Payload key "${c}" collides with a pagination variable and this tool has a paginated step, so it would override the runtime's pagination counter. Remove or rename it.`});let m=n.find(l=>c.startsWith(l));m&&t.push({key:c,kind:"credential",message:`Payload key "${c}" starts with "${m}", the credential namespace of a system this tool uses. Credentials always win over payload values. Remove or rename it.`})}return t}function iV(o){let e=o.map(t=>`- ${t.message}`);return`Payload has ${o.length} key name collision${o.length===1?"":"s"} with the runtime namespace:
|
|
1056
1056
|
${e.join(`
|
|
1057
|
-
`)}`}});var dI=y(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.normalizeApiConfig=uI;Yc.normalizeSystem=rV;Yc.normalizeTool=nV;var lI=Kt();function uI(o){return o&&(!o.url&&(o.urlHost||o.urlPath)&&(o.url=(0,lI.composeUrl)(o.urlHost||"",o.urlPath||"")),delete o.urlHost,delete o.urlPath,o)}function rV(o){return o&&(!o.url&&(o.urlHost||o.urlPath)&&(o.url=(0,lI.composeUrl)(o.urlHost||"",o.urlPath||"")),delete o.urlHost,delete o.urlPath,Array.isArray(o.tags)?o.tags=o.tags.filter(e=>typeof e=="string"):Object.prototype.hasOwnProperty.call(o,"tags")&&(o.tags=[]),o)}var mI={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function sV(o){return o?mI[o]?mI[o]:o:"disabled"}function nV(o){if(!o)return o;let e=o.steps?.map(t=>{let{integrationId:a,apiConfig:i,config:r,executionMode:s,loopSelector:n,systemId:c,...m}=t,l=r||i,u=a??i?.integrationId,d;if(l){if(l=uI(l),l.type||(l.type=l.url||!l.transformCode?"request":"transform"),delete l.id,delete l.integrationId,d=t.instruction??l.instruction,delete l.instruction,l.type==="request"){let b=c??u;b&&(l.systemId=b)}l.pagination?.type&&(l.pagination.type=sV(l.pagination.type))}let g=m.failureBehavior;g&&(g=g.toLowerCase());let p=m.dataSelector??n;return{id:t.id,config:l,instruction:d,modify:m.modify,dataSelector:p,failureBehavior:g,...m.outputFile?{outputFile:m.outputFile}:{}}});return{id:o.id,name:o.name,version:o.version,instruction:o.instruction,inputSchema:o.inputSchema,outputSchema:o.outputSchema??o.responseSchema,steps:e,outputTransform:o.outputTransform??o.finalTransform,folder:o.folder,archived:o.archived,createdByUserId:o.createdByUserId,createdAt:o.createdAt,updatedAt:o.updatedAt,lastUsedAt:o.lastUsedAt}}});var pI=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.PAGINATION_TYPE_MAP=void 0;Sa.mapPaginationType=cV;Sa.mapFailureBehavior=mV;Sa.validateToolStructure=lV;var gI=rt();Sa.PAGINATION_TYPE_MAP={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function cV(o){return o?Sa.PAGINATION_TYPE_MAP[o]?Sa.PAGINATION_TYPE_MAP[o]:o:"disabled"}function mV(o){if(o)return o.toLowerCase()}function lV(o){if(!o||typeof o!="object")return{valid:!1,error:"Tool must be an object"};let e=o;if(!e.id||typeof e.id!="string")return{valid:!1,error:"Tool must have a valid 'id' string"};if(!Array.isArray(e.steps))return{valid:!1,error:"Tool must have a 'steps' array"};if(e.steps.length===0&&!e.outputTransform)return{valid:!1,error:"Tool must have at least one step or an outputTransform"};for(let t=0;t<e.steps.length;t++){let a=e.steps[t],i=a?.id?`Step ${t+1} (${a.id})`:`Step ${t+1}`;if(!a?.id)return{valid:!1,error:`Step ${t+1}: missing 'id'`};if(!a.config)return{valid:!1,error:`${i}: missing 'config'`};if((0,gI.isTransformConfig)(a.config)){if(!a.config.transformCode)return{valid:!1,error:`${i}: transform step missing 'transformCode'`};continue}if(!(0,gI.isRequestConfig)(a.config))return{valid:!1,error:`${i}: unknown step config type`};if(typeof a.config.url!="string"||a.config.url.trim().length===0)return{valid:!1,error:`${i}: request step missing 'url'`}}return{valid:!0}}});var hI=y(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.VM_HELPERS_CODE=void 0;Fs.executeWithVMHelpers=uV;function uV(o,e){let t=o.replace(/;\s*$/,""),a=`
|
|
1057
|
+
`)}`}});var dI=y(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.normalizeApiConfig=uI;Yc.normalizeSystem=rV;Yc.normalizeTool=nV;var lI=Kt();function uI(o){return o&&(!o.url&&(o.urlHost||o.urlPath)&&(o.url=(0,lI.composeUrl)(o.urlHost||"",o.urlPath||"")),delete o.urlHost,delete o.urlPath,o)}function rV(o){return o&&(!o.url&&(o.urlHost||o.urlPath)&&(o.url=(0,lI.composeUrl)(o.urlHost||"",o.urlPath||"")),delete o.urlHost,delete o.urlPath,Array.isArray(o.tags)?o.tags=o.tags.filter(e=>typeof e=="string"):Object.prototype.hasOwnProperty.call(o,"tags")&&(o.tags=[]),o)}var mI={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function sV(o){return o?mI[o]?mI[o]:o:"disabled"}function nV(o){if(!o)return o;let e=o.steps?.map(t=>{let{integrationId:a,apiConfig:i,config:r,executionMode:s,loopSelector:n,systemId:c,...m}=t,l=r||i,u=a??i?.integrationId,d;if(l){if(l=uI(l),l.type||(l.type=l.url||!l.transformCode?"request":"transform"),delete l.id,delete l.integrationId,d=t.instruction??l.instruction,delete l.instruction,l.type==="request"){let b=c??u;b&&(l.systemId=b)}l.pagination?.type&&(l.pagination.type=sV(l.pagination.type))}let g=m.failureBehavior;g&&(g=g.toLowerCase());let p=m.dataSelector??n;return{id:t.id,config:l,instruction:d,modify:m.modify,dataSelector:p,failureBehavior:g,...m.outputFile?{outputFile:m.outputFile}:{}}});return{id:o.id,name:o.name,version:o.version,instruction:o.instruction,inputSchema:o.inputSchema,outputSchema:o.outputSchema??o.responseSchema,steps:e,outputTransform:o.outputTransform??o.finalTransform,folder:o.folder,archived:o.archived,createdByUserId:o.createdByUserId,createdAt:o.createdAt,updatedAt:o.updatedAt,lastUsedAt:o.lastUsedAt}}});var pI=y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.PAGINATION_TYPE_MAP=void 0;Sa.mapPaginationType=cV;Sa.mapFailureBehavior=mV;Sa.validateToolStructure=lV;var gI=rt();Sa.PAGINATION_TYPE_MAP={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function cV(o){return o?Sa.PAGINATION_TYPE_MAP[o]?Sa.PAGINATION_TYPE_MAP[o]:o:"disabled"}function mV(o){if(o)return o.toLowerCase()}function lV(o){if(!o||typeof o!="object")return{valid:!1,error:"Tool must be an object"};let e=o;if(!e.id||typeof e.id!="string")return{valid:!1,error:"Tool must have a valid 'id' string"};if(!Array.isArray(e.steps))return{valid:!1,error:"Tool must have a 'steps' array"};if(e.steps.length===0&&!e.outputTransform)return{valid:!1,error:"Tool must have at least one step or an outputTransform"};for(let t=0;t<e.steps.length;t++){let a=e.steps[t],i=a?.id?`Step ${t+1} (${a.id})`:`Step ${t+1}`;if(!a?.id)return{valid:!1,error:`Step ${t+1}: missing 'id'`};if(!a.config)return{valid:!1,error:`${i}: missing 'config'`};if((0,gI.isTransformConfig)(a.config)){if(!a.config.transformCode)return{valid:!1,error:`${i}: transform step missing 'transformCode'`};continue}if(!(0,gI.isRequestConfig)(a.config))return{valid:!1,error:`${i}: unknown step config type`};if(typeof a.config.url!="string"||a.config.url.trim().length===0)return{valid:!1,error:`${i}: request step missing 'url'`};if(a.config.captureHttpResponse!==void 0&&typeof a.config.captureHttpResponse!="boolean")return{valid:!1,error:`${i}: captureHttpResponse must be a boolean`}}return{valid:!0}}});var hI=y(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.VM_HELPERS_CODE=void 0;Fs.executeWithVMHelpers=uV;function uV(o,e){let t=o.replace(/;\s*$/,""),a=`
|
|
1058
1058
|
${Fs.VM_HELPERS_CODE}
|
|
1059
1059
|
|
|
1060
1060
|
const fn = (
|
|
@@ -1591,7 +1591,7 @@ ${r}`;break;case"retry":L5(r)&&(t[i]=r);break;case"id":F5(r)&&(t[i]=r);break;cas
|
|
|
1591
1591
|
`);o.stack=t?`${t}
|
|
1592
1592
|
${r}`:i.stack}Q.exports.fetch=function(e,t=void 0){return Eme(e,t).catch(a=>{throw X5?aS(a,X5):a&&typeof a=="object"&&Error.captureStackTrace(a,Q.exports.fetch),a})};Q.exports.Headers=Jr().Headers;Q.exports.Response=Pm().Response;Q.exports.Request=vn().Request;Q.exports.FormData=fd().FormData;var{setGlobalOrigin:Ime,getGlobalOrigin:Cme}=Sy();Q.exports.setGlobalOrigin=Ime;Q.exports.getGlobalOrigin=Cme;var{CacheStorage:jme}=M9(),{kConstruct:Bme}=ge();Q.exports.caches=new jme(Bme);var{deleteCookie:Qme,getCookies:Sme,getSetCookies:Dme,setCookie:Tme,parseCookie:Rme}=K9();Q.exports.deleteCookie=Qme;Q.exports.getCookies=Sme;Q.exports.getSetCookies=Dme;Q.exports.setCookie=Tme;Q.exports.parseCookie=Rme;var{parseMIMEType:Nme,serializeAMimeType:Ume}=bt();Q.exports.parseMIMEType=Nme;Q.exports.serializeAMimeType=Ume;var{CloseEvent:Ome,ErrorEvent:Mme,MessageEvent:_me}=Rg(),{WebSocket:Lme,ping:Fme}=B5();Q.exports.WebSocket=Lme;Q.exports.CloseEvent=Ome;Q.exports.ErrorEvent=Mme;Q.exports.MessageEvent=_me;Q.exports.ping=Fme;Q.exports.WebSocketStream=O5().WebSocketStream;Q.exports.WebSocketError=cv().WebSocketError;Q.exports.request=ol(Dn.request);Q.exports.stream=ol(Dn.stream);Q.exports.pipeline=ol(Dn.pipeline);Q.exports.connect=ol(Dn.connect);Q.exports.upgrade=ol(Dn.upgrade);Q.exports.MockClient=pme;Q.exports.MockCallHistory=hme;Q.exports.MockCallHistoryLog=fme;Q.exports.MockPool=yme;Q.exports.MockAgent=bme;Q.exports.SnapshotAgent=kme;Q.exports.mockErrors=Ame;var{EventSource:Pme}=Z5();Q.exports.EventSource=Pme;function Hme(){globalThis.fetch=Q.exports.fetch,globalThis.Headers=Q.exports.Headers,globalThis.Response=Q.exports.Response,globalThis.Request=Q.exports.Request,globalThis.FormData=Q.exports.FormData,globalThis.WebSocket=Q.exports.WebSocket,globalThis.CloseEvent=Q.exports.CloseEvent,globalThis.ErrorEvent=Q.exports.ErrorEvent,globalThis.MessageEvent=Q.exports.MessageEvent,globalThis.EventSource=Q.exports.EventSource}Q.exports.install=Hme});var rS=y(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.SuperglueClient=Rn.SuperglueHttpError=void 0;var Tn=rt(),$a=Kf(),Gme=Cb(),Yme=bI(),Vme=Kt(),Wa=js(),$me=vu(),al=14400*1e3,tl;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:o}=iS();tl=new o({headersTimeout:al,bodyTimeout:al})}catch{}var Wg=class extends Error{constructor(e,t,a,i){super(e),this.status=t,this.code=a,this.details=i,this.name="SuperglueHttpError"}};Rn.SuperglueHttpError=Wg;var pv=class{constructor({apiKey:e,apiEndpoint:t,onInfrastructureError:a,sseTokenProvider:i,tokenProvider:r}){if(!e&&!r)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=r??(async()=>e),this.apiEndpoint=t??"https://api.superglue.cloud",this.sseManager=new Gme.SSELogSubscriptionManager(this.apiEndpoint,i??this.tokenProvider),this.onInfrastructureError=a}async getApiKey(){return this.tokenProvider()}isInfrastructureError(e){return(0,Vme.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,t,a,i,r){let n=await(await this.restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:r})).text();if(n)return JSON.parse(n)}async restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:r}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${t}`,n=a!=null,c=typeof FormData<"u"&&a instanceof FormData,l={Authorization:`Bearer ${await this.getApiKey()}`,...i};n&&!c&&e!=="GET"&&(l["Content-Type"]="application/json");let u;try{u=await fetch(s,{...r,method:e,headers:l,body:n?c?a:JSON.stringify(a):void 0,signal:r?.signal??AbortSignal.timeout(al),...tl?{dispatcher:tl}:{}})}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!u.ok)throw await this.buildHttpError(u);return u}async uploadFiles(e,t){if(typeof t?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let a=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),r=(await this.restRequest("POST","/v1/files/uploads",{process:t.process,files:a.map(({fileName:l,contentType:u,contentLength:d})=>({fileName:l,contentLength:d,...u?{contentType:u}:{}}))})).data.files;if(r.length!==a.length)throw await Promise.all(r.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(r.map(async(l,u)=>{let d=a[u],g=await fetch(l.uploadUrl,{method:"PUT",body:d.content,headers:d.contentType?{"Content-Type":d.contentType}:void 0,signal:AbortSignal.timeout(Math.min(al,l.expiresIn*1e3))});if(!g.ok)throw new Error(`Upload failed for ${d.fileName}: ${g.status} ${g.statusText}`);return l.id})),n=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(n.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:n});c=new Map(l.data.files.map(u=>[u.id,u]))}catch(l){c=new Map(n.map(u=>[u,{id:u,fileName:a[r.findIndex(d=>d.id===u)]?.fileName||u,contentLength:a[r.findIndex(d=>d.id===u)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let m=r.map((l,u)=>{let d=s[u],g=a[u];return d.status==="rejected"?{id:l.id,fileName:g.fileName,contentLength:g.contentLength,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)}:c.get(l.id)||{id:l.id,fileName:g.fileName,contentLength:g.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(m.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),m}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let t=await e.text(),a=`HTTP ${e.status}: ${t}`,i,r;try{let s=JSON.parse(t);s&&typeof s=="object"&&!Array.isArray(s)&&(r=s),typeof s?.code=="string"&&(i=s.code);let n=s.error;typeof n=="string"?a=n:n&&typeof n=="object"&&(a=n.message||JSON.stringify(n))}catch{}return new Wg(a,e.status,i,r)}async streamRequest(e,t,a){let i=e.includes("?")?"&":"?",r=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,n={Authorization:`Bearer ${await this.getApiKey()}`,Accept:"text/event-stream","Content-Type":"application/json"},c;try{c=await fetch(r,{method:"POST",headers:n,body:JSON.stringify(t),signal:a??AbortSignal.timeout(al),...tl?{dispatcher:tl}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!c.ok)throw await this.buildHttpError(c);if(!(c.headers.get("content-type")||"").includes("text/event-stream")){let l=await c.text();return l?JSON.parse(l):void 0}try{return await(0,Yme.consumeEventStreamResult)(c)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let t=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:t.status==="success",data:t.data,error:t.error,tool:t.tool,stepResults:t.stepResults?.map(a=>({...a}))||[],...t.fileArtifacts&&t.fileArtifacts.length>0?{fileArtifacts:t.fileArtifacts}:{},...t.metadata?.warnings?.length?{warnings:t.metadata.warnings}:{}}}async runToolConfig(e){let t=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",a=await this.restRequest("POST",t,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:a.status?a.status==="success":a.success??!1,data:a.data,error:a.error,tool:a.tool||e.tool,stepResults:a.stepResults?.map(r=>({...r}))||[],...a.fileArtifacts&&a.fileArtifacts.length>0?{fileArtifacts:a.fileArtifacts}:{},...a.metadata?.warnings?.length?{warnings:a.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:t,files:a,previousResults:i,credentials:r,options:s,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d,signal:g,stream:p}){let b={step:e,payload:t,files:a,previousResults:i,credentials:r,options:s,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d};return p?this.streamRequest("/v1/tools/step/run",b,g):this.restRequest("POST","/v1/tools/step/run",b,void 0,g?{signal:g}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:r,stepResults:s,options:n,runId:c,createRun:m,parentToolId:l,stepId:u,signal:d,stream:g}){let p={outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:r,stepResults:s,options:n,runId:c,createRun:m,parentToolId:l,stepId:u};return g?this.streamRequest("/v1/tools/transform/run",p,d):this.restRequest("POST","/v1/tools/transform/run",p,void 0,d?{signal:d}:void 0)}async createRun({toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:r,status:s,error:n,startedAt:c,completedAt:m,executionKind:l,parentToolId:u,draftId:d}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:r,status:s,error:n,startedAt:(0,Wa.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Wa.toUTCISOString)(m,"run.completedAt"),executionKind:l,parentToolId:u,draftId:d})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:t}){if(!e)throw new Error("File must be provided for extract.");let a=new FormData;a.append("file",e);let i=t?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,a)}mapOpenAPIRunToRun(e){let t={running:Tn.RunStatus.RUNNING,success:Tn.RunStatus.SUCCESS,failed:Tn.RunStatus.FAILED,aborted:Tn.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:t[e.status]??Tn.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??Tn.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Wa.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Wa.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Wa.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Wa.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let t=(0,$a.createSearchListQueryParams)(e);e.toolId!==void 0&&t.set("toolId",e.toolId),e.searchUserIds?.length&&t.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&t.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&t.set("startedAfter",e.startedAfter instanceof Date?(0,Wa.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?t.set("status",e.statuses.join(",")):e.status!==void 0&&t.set("status",e.status),e.requestSources!==void 0&&t.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&t.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&t.set("userId",e.userId),e.systemId!==void 0&&t.set("systemId",e.systemId),e.systemIds!==void 0&&t.set("systemIds",e.systemIds.join(","));let a=t.size>0?`?${t.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${a}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(r=>this.mapOpenAPIRunToRun(r)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let t=new URLSearchParams;e?.from&&t.set("from",e.from instanceof Date?(0,Wa.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&t.set("to",e.to instanceof Date?(0,Wa.toUTCISOString)(e.to,"activity.to"):e.to);let a=t.toString();return(await this.restRequest("GET",`/v1/activity/counts${a?`?${a}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let t=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(t)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found"))return null;throw t}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found")||t.message?.includes("403")||t.message?.includes("not allowed"))return null;throw t}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,t){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:t})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,t=!0){return this.updateTool(e,{archived:t})}async bulkArchiveTools(e,t=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:t})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let t=(0,$a.createListQueryParams)(e);e.includeArchived!==void 0&&t.set("includeArchived",String(e.includeArchived));let a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/tools${a}`)}async listAllTools(e={}){return(0,$a.listAllPages)((t,a)=>this.listTools({...e,page:t,limit:a}))}async createTool(e,t){return this.restRequest("POST","/v1/tools",{...t,id:e})}async updateTool(e,t){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,t)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(t){if(t.message?.includes("404"))return!1;throw t}}async renameTool(e,t){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:t})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,t=!0){return this.upsertWorkflow(e,{archived:t})}async createWorkflow(e,t){return this.createTool(e,t)}async updateWorkflow(e,t){return this.updateTool(e,t)}async upsertWorkflow(e,t){return await this.getTool(e)?this.updateTool(e,t):this.createTool(e,t)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,t){return this.renameTool(e,t)}async listSchedules(e={}){let t=(0,$a.createListQueryParams)(e),a=t.size>0?`?${t.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${a}`:`/v1/schedules${a}`,r=await this.restRequest("GET",i);return{...r,data:r.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,$a.listAllPages)((t,a)=>this.listSchedules({...e,page:t,limit:a}))}async getToolSchedule(e,t){try{let a=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`);return this.mapOpenAPIScheduleToToolSchedule(a)}catch(a){if(a.message?.includes("404")||a.message?.includes("not found"))return null;throw a}}async createToolSchedule(e,t){let a=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...t,timezone:t.timezone||(0,$me.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(a)}async updateToolSchedule(e,t,a){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`,a);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,t){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`),!0}async bulkSetSchedulesEnabled(e,t){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:t})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e={}){let t=(0,$a.createListQueryParams)(e);e.systemId!==void 0&&t.set("systemId",e.systemId);let a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/credentials${a}`)}async listAllCredentials(e={}){return(0,$a.listAllPages)((t,a)=>this.listCredentials({...e,page:t,limit:a}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,t){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:t})).data}async updateCredentials(e,t){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,t)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let t=(0,$a.createListQueryParams)(e),a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/systems${a}`)}async listAllSystems(e={}){return(0,$a.listAllPages)((t,a)=>this.listSystems({...e,page:t,limit:a}))}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,t){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,t)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,t){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,t)).data}async searchSystemDocumentation(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:t})).data}async triggerSystemDocumentationScrapeJob(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,t)).data}async fetchOpenApiSpec(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:t,link:a?.link})).data}async uploadSystemDocumentationFiles(e,t,a){let i=await this.uploadFiles(t,{process:!0}),r=i.flatMap(s=>s.status==="uploaded"?[s.id]:[]);if(r.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:r,link:a?.link!==!1})}catch(s){throw await Promise.all(r.map(n=>this.deleteFileUpload(n).catch(()=>{}))),s}if(!a?.settle){let s=i.filter(n=>n.status==="failed");if(s.length>0)throw new Error(s.map(n=>n.error).join("; "))}return i}async listSystemDocumentationFiles(e,t){let a=new URLSearchParams;t?.length&&a.set("fileIds",t.join(","));let i=a.size>0?`?${a.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,t,a){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}/content?processed=${a.processed}`)).data}async deleteSystemDocumentationFile(e,t){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(t){return{success:!1,error:t.message}}}};Rn.SuperglueClient=pv});var nS=y(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.UnquotedKeyStrategy=Ce.TripleQuoteStrategy=Ce.TrailingCommaStrategy=Ce.SingleQuoteStrategy=Ce.PythonLiteralStrategy=Ce.CommentStrategy=Ce.ResilientJsonParser=Ce.RepairStrategy=void 0;Ce.parseJsonResilient=Wme;Ce.parseJSON=Jme;Ce.isValidJson=Kme;Ce.prettyPrintJson=Zme;Ce.minifyJson=Xme;var Ht=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};Ce.RepairStrategy=Ht;var Jg=class extends Ht{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(t,a)=>{let i=a.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};Ce.TripleQuoteStrategy=Jg;var Kg=class extends Ht{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};Ce.PythonLiteralStrategy=Kg;var Zg=class extends Ht{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};Ce.TrailingCommaStrategy=Zg;var Xg=class extends Ht{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let t=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return t=t.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),t}};Ce.SingleQuoteStrategy=Xg;var ep=class extends Ht{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};Ce.UnquotedKeyStrategy=ep;var op=class extends Ht{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t}};Ce.CommentStrategy=op;var hv=class extends Ht{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(t){let a=t.message||"";return a.includes("control character")||a.includes("Bad control")||a.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let t="",a=!1,i=!1;for(let r=0;r<e.length;r++){let s=e[r],n=r>0?e[r-1]:"";if(i){t+=s,i=!1;continue}if(s==="\\"&&a){t+=s,i=!0;continue}if(s==='"'&&n!=="\\"){a=!a,t+=s;continue}if(a)switch(s){case`
|
|
1593
1593
|
`:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;case"\b":t+="\\b";break;case"\f":t+="\\f";break;default:let c=s.charCodeAt(0);c<32?t+="\\u"+("0000"+c.toString(16)).slice(-4):t+=s}else t+=s}return t}},fv=class extends Ht{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return!1;let a=0,i=0,r=!1,s=!1;for(let n=0;n<t.length;n++){let c=t[n];if(r)s?s=!1:c==="\\"?s=!0:c==='"'&&(r=!1);else if(c==='"')r=!0;else if(c==="{")a++;else if(c==="}"){if(a--,a===0&&i===0&&n>0&&n<t.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&a===0&&n>0&&n<t.length-1))return!0}return!1}apply(e){let t=e.trim(),a=0,i=0,r=!1,s=!1,n=-1;for(let c=0;c<t.length;c++){let m=t[c];if(r)s?s=!1:m==="\\"?s=!0:m==='"'&&(r=!1);else if(m==='"')r=!0;else if(m==="{")a++;else if(m==="}"){if(a--,a===0&&i===0&&c>0){n=c;break}}else if(m==="[")i++;else if(m==="]"&&(i--,i===0&&a===0&&c>0)){n=c;break}}return n>0&&n<t.length-1?t.substring(0,n+1):e}},Nn=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new Jg,new Xg,new hv,new fv,new Kg,new Zg,new ep,new op]}parse(e){let t=Date.now();this.repairLog=[];let a=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(a),metadata:{parseTime:Date.now()-t,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-t}}}let i=a,r=[];for(let s of this.strategies)if(s.canApply(i)){let n=i;if(i=s.apply(i),n!==i){r.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:r}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:r}}}catch(s){let n=this.aggressiveFallback(i);return n.success?{...n,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-t,strategiesApplied:[...r,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${r.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:r}}}}aggressiveFallback(e){try{let t=e.indexOf("{"),a=e.indexOf("[");if(t===-1&&a===-1)return{success:!1,error:"No JSON-like structure found"};let i=t===-1?a:a===-1?t:Math.min(t,a),r=e.substring(i);for(let n of this.strategies)n.canApply(r)&&(r=n.apply(r));return{success:!0,data:JSON.parse(r)}}catch(t){return{success:!1,error:`Aggressive fallback failed: ${t}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(t=>t.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};Ce.ResilientJsonParser=Nn;var sS=new Nn;function Wme(o,e){return(e?new Nn(e):sS).parse(o)}function Jme(o){let e=sS.parse(o);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}function Kme(o){try{return JSON.parse(o),!0}catch{return!1}}function Zme(o,e=2){return JSON.stringify(o,null,e)}function Xme(o){let t=new Nn().parse(o);if(t.success)return JSON.stringify(t.data);throw new Error("Cannot minify invalid JSON")}});var tt=y(U=>{"use strict";var ele=U&&U.__createBinding||(Object.create?(function(o,e,t,a){a===void 0&&(a=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(o,a,i)}):(function(o,e,t,a){a===void 0&&(a=t),o[a]=e[t]})),J=U&&U.__exportStar||function(o,e){for(var t in o)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&ele(e,o,t)};Object.defineProperty(U,"__esModule",{value:!0});U.SSELogSubscriptionManager=U.SuperglueHttpError=U.SuperglueClient=void 0;J(d1(),U);J(v1(),U);J(x1(),U);J(C1(),U);J(S1(),U);J(Lc(),U);J(K1(),U);J(Z1(),U);J(X1(),U);J(e2(),U);J(Kf(),U);J(t2(),U);J(a2(),U);J(i2(),U);J(eb(),U);J(n2(),U);J(m2(),U);J(l2(),U);J(d2(),U);J(wl(),U);J(p2(),U);J(h2(),U);J(b2(),U);J(A2(),U);J(ab(),U);J(E2(),U);J(C2(),U);J(B2(),U);J(Q2(),U);J(F2(),U);J(H2(),U);J(bb(),U);J(iI(),U);J(qb(),U);J(cI(),U);J(dI(),U);J(pI(),U);J(rt(),U);J(Kt(),U);J(hI(),U);J(fI(),U);J(Nu(),U);J(js(),U);J(vu(),U);var cS=rS();Object.defineProperty(U,"SuperglueClient",{enumerable:!0,get:function(){return cS.SuperglueClient}});Object.defineProperty(U,"SuperglueHttpError",{enumerable:!0,get:function(){return cS.SuperglueHttpError}});var ole=Cb();Object.defineProperty(U,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return ole.SSELogSubscriptionManager}});J(nS(),U)});var Rp=require("commander");var Ro=W(require("fs")),uS=W(require("os")),Ja=W(require("path")),il=W(tt()),mS=new Set(["runner","builder","admin"]),lS={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Ka(o){let e=Ja.join(process.cwd(),".superglue"),t=uS.homedir();if(!t)return e;let a=Ja.join(t,".superglue");return o===!0?e:o===!1?a:Ro.existsSync(Ja.join(e,"config.json"))?e:a}function bv(o){return Ja.join(Ka(o),"config.json")}function tp(o){let e=bv(o);if(!Ro.existsSync(e))return{};try{return JSON.parse(Ro.readFileSync(e,"utf-8"))}catch{return{}}}function Un(o){let e=tp(),t=o.apiKey||(0,il.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",a=o.endpoint||(0,il.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,il.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),r=(0,il.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=r&&mS.has(r)?r:e.preset&&mS.has(e.preset)?e.preset:"admin";return{...lS,...e,apiKey:t,endpoint:a,webEndpoint:i,preset:s,output:{...lS.output,...e.output}}}function ap(o,e){let t=Ka(e);Ro.existsSync(t)||Ro.mkdirSync(t,{recursive:!0}),Ro.writeFileSync(Ja.join(t,"config.json"),JSON.stringify(o,null,2)+`
|
|
1594
|
-
`,{mode:384})}function ip(o,e){let t=Ja.join(Ka(e),"drafts");if(Ro.existsSync(t)||Ro.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Ja.resolve(o.output.directory);Ro.existsSync(a)||Ro.mkdirSync(a,{recursive:!0})}}var zv=W(tt());var yv=W(require("readline"));var pS=require("child_process"),hS=require("util");var dS={name:"@superglue/cli",version:"1.1.
|
|
1594
|
+
`,{mode:384})}function ip(o,e){let t=Ja.join(Ka(e),"drafts");if(Ro.existsSync(t)||Ro.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Ja.resolve(o.output.directory);Ro.existsSync(a)||Ro.mkdirSync(a,{recursive:!0})}}var zv=W(tt());var yv=W(require("readline"));var pS=require("child_process"),hS=require("util");var dS={name:"@superglue/cli",version:"1.1.94",bin:{sg:"./dist/cli.js"},files:[".claude-plugin/","dist/","skills/","LICENSE"],dependencies:{commander:"15.0.0-0","fast-json-patch":"3.1.1"},devDependencies:{"@superglue/shared":"file:../shared","@types/node":"25.5.0",tsup:"8.5.1",typescript:"5.8.3"},scripts:{build:"tsup && (cp -r skills dist/ 2>/dev/null || true)",dev:"tsup --watch","type-check":"tsc --noEmit",prepublishOnly:"npm run build"},publishConfig:{access:"public"}};var ale=(0,hS.promisify)(pS.exec),xo=dS.version;function gS(o){let e=o.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:o}}function sp(o,e){let t=o.split("."),a=e.split("."),i=Math.max(t.length,a.length);for(let r=0;r<i;r++){let s=gS(t[r]||"0"),n=gS(a[r]||"0");if(s.numeric<n.numeric)return-1;if(s.numeric>n.numeric||s.prerelease===null&&n.prerelease!==null)return 1;if(s.prerelease!==null&&n.prerelease===null)return-1;if(s.prerelease!==null&&n.prerelease!==null){if(s.prerelease<n.prerelease)return-1;if(s.prerelease>n.prerelease)return 1}}return 0}async function np(){try{let o=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return o.ok&&(await o.json()).version||null}catch{return null}}var rp=null;function fS(){G()&&(rp=np())}async function bS(){if(!(!G()||!rp)){try{let o=new Promise(t=>{setTimeout(()=>t(null),2e3).unref()}),e=await Promise.race([rp,o]);e&&sp(xo,e)<0&&(console.error(""),console.error(`${h.cyan}${h.bold} Update available: ${xo} \u2192 ${e}${h.reset}`),console.error(`${h.cyan} Run ${h.bold}sg update${h.reset}${h.cyan} to upgrade${h.reset}`),console.error(""))}catch{}rp=null}}async function yS(){let o=await np();if(!o)return{success:!1,message:"Could not fetch latest version from npm"};if(sp(xo,o)>=0)return{success:!0,message:`Already on latest version (${xo})`};try{return await ale("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${xo} to ${o}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var G=()=>process.argv.includes("--table")&&process.stdout.isTTY,Et=()=>process.argv.includes("--full"),h={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"};function kS(o,e){let t=e||o;return`\x1B]8;;${o}\x07${h.underline}${h.cyan}${t}${h.reset}\x1B]8;;\x07`}function AS(){if(!G())return;let o=h.reset,e=h.dim,t="\x1B[47;30m",a=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),a.forEach(i=>{let r=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(r===-1)return console.log(" "+i);let n=i.slice(0,r),c=i.slice(r,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),m=i.slice(s+1);console.log(` ${n}${t}${c}${o}${m}`)}),console.log(` ${e} CLI v${xo}${o}`),console.log("")}function Ee(o){if(!G())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,a=o,i=()=>process.stdout.write("\r\x1B[2K"),r=()=>{process.stdout.write(`\r ${h.cyan}${e[t++%e.length]}${h.reset} ${a}`)},s=setInterval(r,80);return{update:n=>{a=n},log:n=>{i(),console.log(` ${h.dim}\u2502${h.reset} ${n}`),r()},stop:n=>{clearInterval(s),i(),n&&console.log(` ${n}`)}}}function O(o){G()?cp(o):console.log(JSON.stringify(o,null,2))}function re(o,e){G()?(console.log(` ${h.green}\u2713${h.reset} ${o}`),e&&cp(e,4)):console.log(JSON.stringify({success:!0,message:o,...e&&typeof e=="object"?e:{data:e}}))}function z(o,e){G()?(console.error(` ${h.red}\u2717${h.reset} ${o}`),e&&cp(e,4)):console.error(JSON.stringify({success:!1,error:o,details:e}))}function wS(o){G()&&console.log(` ${h.yellow}\u26A0${h.reset} ${o}`)}function po(o){G()&&console.log(` ${h.dim}${o}${h.reset}`)}function Za(o){G()&&(console.log(`
|
|
1595
1595
|
${h.bold}${h.cyan}${o}${h.reset}`),console.log(` ${h.dim}${"\u2500".repeat(o.length)}${h.reset}`))}function pa(o,e,t){if(!G()){console.log(JSON.stringify({success:!0,total:t?.total??o.length,items:o}));return}if(o.length===0){console.log(`
|
|
1596
1596
|
${h.dim}0 results${h.reset}
|
|
1597
1597
|
`);return}let a=e||Object.keys(o[0]),i=Et()?1/0:60,r=a.map(l=>Math.min(i,Math.max(l.length,...o.map(u=>String(u[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=a.map((l,u)=>`${h.bold}${h.cyan}${l.toUpperCase().padEnd(r[u])}${h.reset}`).join(" ");console.log(` ${s}`);let n=r.map(l=>`${h.dim}${"\u2500".repeat(l)}${h.reset}`).join(`${h.dim}\u2500\u2500${h.reset}`);console.log(` ${n}`);for(let l of o){let u=a.map((d,g)=>{let p=String(l[d]??"").replace(/[\n\r]+/g," ").trim();if(p.length>i){let A=`\u2026 (${p.length})`;p=p.slice(0,Math.max(0,i-A.length))+`${h.dim}${A}${h.reset}`}return d==="status"?`${{success:h.green,running:h.yellow,failed:h.red,aborted:h.red,error:h.red,pending:h.dim}[p.toLowerCase()]||""}${p.padEnd(r[g])}${h.reset}`:p.padEnd(r[g])}).join(" ");console.log(` ${u}`)}let c=t?.total??o.length,m=c===o.length?`${o.length} result${o.length===1?"":"s"}`:`${o.length} of ${c} result${c===1?"":"s"}`;console.log(`
|
|
@@ -87,6 +87,15 @@ XML responses (SOAP and other XML APIs) are auto-parsed to an object on `sourceD
|
|
|
87
87
|
- Default headers: `Accept: */*`, Chrome-like `User-Agent`
|
|
88
88
|
- HTTPS: `rejectUnauthorized: false` (accepts self-signed certs)
|
|
89
89
|
|
|
90
|
+
### Tool Step Response Metadata
|
|
91
|
+
|
|
92
|
+
Set `config.captureHttpResponse: true` on HTTP request steps that need response metadata. The default is off.
|
|
93
|
+
Successful steps expose `sourceData.stepId.http.statusCode` and `sourceData.stepId.http.headers`; `.data` remains the response body.
|
|
94
|
+
Loop results carry `.http` per item. Pagination exposes the final response's metadata; stop conditions retain per-page `response.headers`.
|
|
95
|
+
Stored `stepResults` retain the metadata, including failed HTTP responses. No HTTP response means no `.http` field.
|
|
96
|
+
Header names are lowercase; `set-cookie` values are arrays, and other values are strings.
|
|
97
|
+
Steps without the option keep their existing envelopes and outputs.
|
|
98
|
+
|
|
90
99
|
### Body Resolution
|
|
91
100
|
|
|
92
101
|
The runtime processes the body in this order:
|
package/package.json
CHANGED
|
@@ -87,6 +87,15 @@ XML responses (SOAP and other XML APIs) are auto-parsed to an object on `sourceD
|
|
|
87
87
|
- Default headers: `Accept: */*`, Chrome-like `User-Agent`
|
|
88
88
|
- HTTPS: `rejectUnauthorized: false` (accepts self-signed certs)
|
|
89
89
|
|
|
90
|
+
### Tool Step Response Metadata
|
|
91
|
+
|
|
92
|
+
Set `config.captureHttpResponse: true` on HTTP request steps that need response metadata. The default is off.
|
|
93
|
+
Successful steps expose `sourceData.stepId.http.statusCode` and `sourceData.stepId.http.headers`; `.data` remains the response body.
|
|
94
|
+
Loop results carry `.http` per item. Pagination exposes the final response's metadata; stop conditions retain per-page `response.headers`.
|
|
95
|
+
Stored `stepResults` retain the metadata, including failed HTTP responses. No HTTP response means no `.http` field.
|
|
96
|
+
Header names are lowercase; `set-cookie` values are arrays, and other values are strings.
|
|
97
|
+
Steps without the option keep their existing envelopes and outputs.
|
|
98
|
+
|
|
90
99
|
### Body Resolution
|
|
91
100
|
|
|
92
101
|
The runtime processes the body in this order:
|