@superglue/cli 1.1.165 → 1.1.166
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.166",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "superglue",
|
|
7
7
|
"email": "hello@superglue.cloud"
|
package/dist/cli.js
CHANGED
|
@@ -1234,7 +1234,7 @@ DEPRECATED ENDPOINTS: GET /user/{email} and GET /members are deprecated; use V2
|
|
|
1234
1234
|
${e.join(`
|
|
1235
1235
|
`)}`}function ohe({payload:t,tool:e}){let r=[],n=new Set(Vt.RESERVED_RUNTIME_KEYS),i=new Set(Vt.PAGINATION_RUNTIME_KEYS),o=new Set((e.steps||[]).map(c=>c.id).filter(Boolean)),s=Fb(e),a=(0,oL.getToolSystemIds)(e).map(c=>`${c}_`);for(let c of Object.keys(t)){n.has(c)&&r.push({key:c,kind:"reserved",message:`Payload key "${c}" collides with ${aL(c)}, which the runtime injects into sourceData. Remove or rename it.`}),o.has(c)&&r.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)&&r.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 u=a.find(l=>c.startsWith(l));u&&r.push({key:c,kind:"credential",message:`Payload key "${c}" starts with "${u}", the credential namespace of a system this tool uses. Credentials always win over payload values. Remove or rename it.`})}return r}function she(t){let e=t.map(r=>`- ${r.message}`);return`Payload has ${t.length} key name collision${t.length===1?"":"s"} with the runtime namespace:
|
|
1236
1236
|
${e.join(`
|
|
1237
|
-
`)}`}});var uL=m(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});Eg.getSystemCallUrlError=fhe;Eg.planDefaultSystemAuth=ghe;var ahe=xn(),che=/^[a-z][a-z0-9+.-]*:\/\//i,uhe=["access_token","accessToken"],lhe=["username","user","email"],dhe=["password","pass","api_token","token"];function Ahe(t){return typeof t=="string"&&che.test(t)}var phe=/^<<[A-Za-z0-9_-]
|
|
1237
|
+
`)}`}});var uL=m(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});Eg.getSystemCallUrlError=fhe;Eg.planDefaultSystemAuth=ghe;var ahe=xn(),che=/^[a-z][a-z0-9+.-]*:\/\//i,uhe=["access_token","accessToken"],lhe=["username","user","email"],dhe=["password","pass","api_token","token"];function Ahe(t){return typeof t=="string"&&che.test(t)}var phe=/^<<[A-Za-z0-9_-]+>>/;function fhe(t,e){return t?Ahe(t)||(e?t.startsWith(`<<${e}_`):phe.test(t))?null:`url must be absolute or start with a <<${e??"systemId"}_*>> placeholder such as <<${e??"systemId"}_url>>; a relative path is not joined to the system URL.`:"url is required: pass the absolute URL, or <<systemId_url>> followed by the path."}function hhe(t,e){if(!t)return!1;let r=e.toLowerCase();return Object.keys(t).some(n=>n.toLowerCase()===r)}function yg(t,e){return e.find(r=>t.includes(r))}function ghe({systemId:t,authentication:e,credentialKeys:r,config:n,protocol:i,mode:o="auto"}){let s=r.map(u=>`<<${t}_${u}>>`);if((0,ahe.getCredentialPlaceholderKeysForSystem)(n,t).length>0||hhe(n.headers,"authorization"))return{auth:{applied:"explicit",placeholders:s}};if(o==="none")return{auth:{applied:"none",placeholders:s}};if(i!=="http")return{auth:{applied:"none",placeholders:s,reason:"Non-HTTP protocols take credentials in the connection URL."}};let c=e?.type;if(r.length===0&&(c==="oauth2"||c==="basic_auth"||c==="api_key"))return{auth:{applied:"unavailable",placeholders:s,reason:"The credential has no stored secret values; authenticate or set its secrets first."}};if(c==="oauth2"){let u=yg(r,uhe);return u?{headers:{Authorization:`Bearer <<${t}_${u}>>`},auth:{applied:"bearer",header:"Authorization",placeholders:s}}:{auth:{applied:"unavailable",placeholders:s,reason:"The credential has no access token; authenticate the system first."}}}if(c==="basic_auth"){let u=yg(r,lhe),l=yg(r,dhe);return!u||!l?{auth:{applied:"unavailable",placeholders:s,reason:"Basic auth needs a username and a password secret; place the placeholders in the Authorization header yourself."}}:{headers:{Authorization:`Basic <<${t}_${u}>>:<<${t}_${l}>>`},auth:{applied:"basic",header:"Authorization",placeholders:s}}}if(c==="api_key"){let u=yg(r,["api_key","apiKey","access_token","token"])??(r.length===1?r[0]:void 0);return u?{headers:{Authorization:`Bearer <<${t}_${u}>>`},auth:{applied:"bearer",header:"Authorization",placeholders:s,reason:"API key sent as a Bearer token; pass the header the API documents when it expects another header or query parameter."}}:{auth:{applied:"unavailable",placeholders:s,reason:"Several secrets are stored and none is named api_key; place the right placeholder in the header the API expects."}}}return{auth:{applied:"none",placeholders:s,...r.length>0?{reason:"The system declares no authentication type; place placeholders where the API expects them."}:{}}}}});var pL=m(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});Rd.normalizeApiConfig=AL;Rd.normalizeSystem=mhe;Rd.normalizeTool=Ehe;var dL=xn();function AL(t){return t&&(!t.url&&(t.urlHost||t.urlPath)&&(t.url=(0,dL.composeUrl)(t.urlHost||"",t.urlPath||"")),delete t.urlHost,delete t.urlPath,t)}function mhe(t){return t&&(!t.url&&(t.urlHost||t.urlPath)&&(t.url=(0,dL.composeUrl)(t.urlHost||"",t.urlPath||"")),delete t.urlHost,delete t.urlPath,Array.isArray(t.tags)?t.tags=t.tags.filter(e=>typeof e=="string"):Object.prototype.hasOwnProperty.call(t,"tags")&&(t.tags=[]),t)}var lL={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function yhe(t){return t?lL[t]?lL[t]:t:"disabled"}function Ehe(t){if(!t)return t;let e=t.steps?.map(r=>{let{integrationId:n,apiConfig:i,config:o,executionMode:s,loopSelector:a,systemId:c,...u}=r,l=o||i,d=n??i?.integrationId,A;if(l){if(l=AL(l),l.type||(l.type=l.url||!l.transformCode?"request":"transform"),delete l.id,delete l.integrationId,A=r.instruction??l.instruction,delete l.instruction,l.type==="request"){let g=c??d;g&&(l.systemId=g)}l.pagination?.type&&(l.pagination.type=yhe(l.pagination.type))}let p=u.failureBehavior;p&&(p=p.toLowerCase());let h=u.dataSelector??a;return{id:r.id,config:l,instruction:A,modify:u.modify,dataSelector:h,failureBehavior:p,...u.outputFile?{outputFile:u.outputFile}:{}}});return{id:t.id,name:t.name,version:t.version,instruction:t.instruction,inputSchema:t.inputSchema,outputSchema:t.outputSchema??t.responseSchema,steps:e,outputTransform:t.outputTransform??t.finalTransform,folder:t.folder,archived:t.archived,createdByUserId:t.createdByUserId,createdAt:t.createdAt,updatedAt:t.updatedAt,lastUsedAt:t.lastUsedAt}}});var hL=m(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.PAGINATION_TYPE_MAP=void 0;ko.mapPaginationType=Ihe;ko.mapFailureBehavior=Che;ko.validateToolStructure=bhe;var fL=lr();ko.PAGINATION_TYPE_MAP={OFFSET_BASED:"offsetBased",PAGE_BASED:"pageBased",CURSOR_BASED:"cursorBased",DISABLED:"disabled"};function Ihe(t){return t?ko.PAGINATION_TYPE_MAP[t]?ko.PAGINATION_TYPE_MAP[t]:t:"disabled"}function Che(t){if(t)return t.toLowerCase()}function bhe(t){if(!t||typeof t!="object")return{valid:!1,error:"Tool must be an object"};let e=t;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 r=0;r<e.steps.length;r++){let n=e.steps[r],i=n?.id?`Step ${r+1} (${n.id})`:`Step ${r+1}`;if(!n?.id)return{valid:!1,error:`Step ${r+1}: missing 'id'`};if(!n.config)return{valid:!1,error:`${i}: missing 'config'`};if((0,fL.isTransformConfig)(n.config)){if(!n.config.transformCode)return{valid:!1,error:`${i}: transform step missing 'transformCode'`};continue}if(!(0,fL.isRequestConfig)(n.config))return{valid:!1,error:`${i}: unknown step config type`};if(typeof n.config.url!="string"||n.config.url.trim().length===0)return{valid:!1,error:`${i}: request step missing 'url'`};if(n.config.captureHttpResponse!==void 0&&typeof n.config.captureHttpResponse!="boolean")return{valid:!1,error:`${i}: captureHttpResponse must be a boolean`}}return{valid:!0}}});var gL=m(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});tu.VM_HELPERS_CODE=void 0;tu.executeWithVMHelpers=She;function She(t,e){let r=t.replace(/;\s*$/,""),n=`
|
|
1238
1238
|
${tu.VM_HELPERS_CODE}
|
|
1239
1239
|
|
|
1240
1240
|
const fn = (
|
|
@@ -1771,7 +1771,7 @@ ${s}`;return}if(my(e,i,gTe)){mTe(e,o)&&(r.retry=e.toString("utf8",o));return}if(
|
|
|
1771
1771
|
`);t.stack=r?`${r}
|
|
1772
1772
|
${o}`:i.stack}V.exports.fetch=function(e,r=void 0){return WTe(e,r).catch(n=>{throw eG?iG(n,eG):n&&typeof n=="object"&&Error.captureStackTrace(n,V.exports.fetch),n})};V.exports.Headers=ic().Headers;V.exports.Response=DA().Response;V.exports.Request=Nu().Request;V.exports.FormData=Fg().FormData;var{setGlobalOrigin:ZTe,getGlobalOrigin:KTe}=GS();V.exports.setGlobalOrigin=ZTe;V.exports.getGlobalOrigin=KTe;var{CacheStorage:XTe}=jz(),{kConstruct:eRe}=$e();V.exports.caches=new XTe(eRe);var{deleteCookie:tRe,getCookies:rRe,getSetCookies:nRe,setCookie:iRe,parseCookie:oRe}=eH();V.exports.deleteCookie=tRe;V.exports.getCookies=rRe;V.exports.getSetCookies=nRe;V.exports.setCookie=iRe;V.exports.parseCookie=oRe;var{parseMIMEType:sRe,serializeAMimeType:aRe}=yn();V.exports.parseMIMEType=sRe;V.exports.serializeAMimeType=aRe;var{CloseEvent:cRe,ErrorEvent:uRe,MessageEvent:lRe}=oy(),{WebSocket:dRe,ping:ARe}=NH();V.exports.WebSocket=dRe;V.exports.CloseEvent=cRe;V.exports.ErrorEvent=uRe;V.exports.MessageEvent=lRe;V.exports.ping=ARe;V.exports.WebSocketStream=$H().WebSocketStream;V.exports.WebSocketError=Qv().WebSocketError;V.exports.request=$A(Hu.request);V.exports.stream=$A(Hu.stream);V.exports.pipeline=$A(Hu.pipeline);V.exports.connect=$A(Hu.connect);V.exports.upgrade=$A(Hu.upgrade);V.exports.MockClient=LTe;V.exports.MockCallHistory=PTe;V.exports.MockCallHistoryLog=FTe;V.exports.MockPool=jTe;V.exports.MockAgent=$Te;V.exports.SnapshotAgent=qTe;V.exports.mockErrors=zTe;var{EventSource:pRe}=XH();V.exports.EventSource=pRe;function fRe(){globalThis.fetch=V.exports.fetch,globalThis.Headers=V.exports.Headers,globalThis.Response=V.exports.Response,globalThis.Request=V.exports.Request,globalThis.FormData=V.exports.FormData,globalThis.WebSocket=V.exports.WebSocket,globalThis.CloseEvent=V.exports.CloseEvent,globalThis.ErrorEvent=V.exports.ErrorEvent,globalThis.MessageEvent=V.exports.MessageEvent,globalThis.EventSource=V.exports.EventSource}V.exports.install=fRe});var aG=m(Yu=>{"use strict";Object.defineProperty(Yu,"__esModule",{value:!0});Yu.SuperglueClient=Yu.SuperglueHttpError=void 0;var Gu=lr(),vn=pb(),hRe=jb(),gRe=yL(),mRe=xn(),Yo=xc(),yRe=Zl(),qA=14400*1e3,jA;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=oG();jA=new t({headersTimeout:qA,bodyTimeout:qA})}catch{}function sG(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var Iy=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};Yu.SuperglueHttpError=Iy;var kv=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new hRe.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;sG(r);let o=await this.refreshToken();return sG(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,mRe.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,u=d=>{let A={Authorization:`Bearer ${d}`,...i};return a&&!c&&e!=="GET"&&(A["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:A,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(qA),...jA?{dispatcher:jA}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!l.ok)throw await this.buildHttpError(l);return l}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,files:n.map(({fileName:l,contentType:d,contentLength:A})=>({fileName:l,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(l,d)=>{let A=n[d],p=await fetch(l.uploadUrl,{method:"PUT",body:A.content,headers:A.contentType?{"Content-Type":A.contentType}:void 0,signal:AbortSignal.timeout(Math.min(qA,l.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return l.id})),a=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(a.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(l.data.files.map(d=>[d.id,d]))}catch(l){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(l.id)||{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(u.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),u}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 r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new Iy(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=u=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(qA),...jA?{dispatcher:jA}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let u=await a.text();return u?JSON.parse(u):void 0}try{return await(0,gRe.consumeEventStreamResult)(a)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return(await this.restRequest("GET",`/v1/memory-notes${n?`?${n}`:""}`)).data}async createMemoryNote(e){return(await this.restRequest("POST","/v1/memory-notes",e)).data}async updateMemoryNote(e,r){return(await this.restRequest("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)).data}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=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:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{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:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h,signal:g,stream:S}){let B={step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h};return S?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:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:u,executionKind:l,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,Yo.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Yo.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:d,draftId:A})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:Gu.RunStatus.RUNNING,success:Gu.RunStatus.SUCCESS,failed:Gu.RunStatus.FAILED,aborted:Gu.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Gu.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??Gu.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Yo.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Yo.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Yo.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Yo.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,vn.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,Yo.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,Yo.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,Yo.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,vn.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,vn.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,vn.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,vn.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,vn.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return(await this.restRequest(r?"PATCH":"POST",i,n)).data}async listSchedules(e={}){let r=(0,vn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,vn.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,yRe.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e={}){let r=(0,vn.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/credentials${n}`)}async listAllCredentials(e={}){return(0,vn.listAllPages)((r,n)=>this.listCredentials({...e,page:r,limit:n}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,r){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:r})).data}async updateCredentials(e,r){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,r)).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 r=(0,vn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,vn.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}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,r){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,r)).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,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async searchSystemDocumentation(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:r})).data}async triggerSystemDocumentationScrapeJob(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,r)).data}async fetchOpenApiSpec(e,r,n){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:r,link:n?.link})).data}async uploadSystemDocumentationFiles(e,r,n){let i=await this.uploadFiles(r,{process:!0}),o=i.flatMap(s=>s.status==="uploaded"?[s.id]:[]);if(o.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:o,link:n?.link!==!1})}catch(s){throw await Promise.all(o.map(a=>this.deleteFileUpload(a).catch(()=>{}))),s}if(!n?.settle){let s=i.filter(a=>a.status==="failed");if(s.length>0)throw new Error(s.map(a=>a.error).join("; "))}return i}async listSystemDocumentationFiles(e,r){let n=new URLSearchParams;r?.length&&n.set("fileIds",r.join(","));let i=n.size>0?`?${n.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,r,n){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}/content?processed=${n.processed}`)).data}async deleteSystemDocumentationFile(e,r){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};Yu.SuperglueClient=kv});var uG=m(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.UnquotedKeyStrategy=st.TripleQuoteStrategy=st.TrailingCommaStrategy=st.SingleQuoteStrategy=st.PythonLiteralStrategy=st.CommentStrategy=st.ResilientJsonParser=st.RepairStrategy=void 0;st.parseJsonResilient=ERe;st.parseJSON=IRe;st.isValidJson=CRe;st.prettyPrintJson=bRe;st.minifyJson=SRe;var Gn=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};st.RepairStrategy=Gn;var Cy=class extends Gn{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,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};st.TripleQuoteStrategy=Cy;var by=class extends Gn{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")}};st.PythonLiteralStrategy=by;var Sy=class extends Gn{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")}};st.TrailingCommaStrategy=Sy;var wy=class extends Gn{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 r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};st.SingleQuoteStrategy=wy;var By=class extends Gn{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')}};st.UnquotedKeyStrategy=By;var Qy=class extends Gn{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};st.CommentStrategy=Qy;var Nv=class extends Gn{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(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
|
|
1773
1773
|
`:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},Ov=class extends Gn{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let u=r[c];if(o)s?s=!1:u==="\\"?s=!0:u==='"'&&(o=!1);else if(u==='"')o=!0;else if(u==="{")n++;else if(u==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(u==="[")i++;else if(u==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},Vu=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 Cy,new wy,new Nv,new Ov,new by,new Sy,new By,new Qy]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.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()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};st.ResilientJsonParser=Vu;var cG=new Vu;function ERe(t,e){return(e?new Vu(e):cG).parse(t)}function IRe(t){let e=cG.parse(t);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 CRe(t){try{return JSON.parse(t),!0}catch{return!1}}function bRe(t,e=2){return JSON.stringify(t,null,e)}function SRe(t){let r=new Vu().parse(t);if(r.success)return JSON.stringify(r.data);throw new Error("Cannot minify invalid JSON")}});var cr=m(K=>{"use strict";var wRe=K&&K.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),le=K&&K.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&wRe(e,t,r)};Object.defineProperty(K,"__esModule",{value:!0});K.SSELogSubscriptionManager=K.SuperglueHttpError=K.SuperglueClient=void 0;le(Tk(),K);le(JU(),K);le(aM(),K);le(uM(),K);le(fM(),K);le(hM(),K);le(mM(),K);le(Id(),K);le(ZM(),K);le(KM(),K);le(XM(),K);le(ex(),K);le(pb(),K);le(rx(),K);le(ox(),K);le(sx(),K);le(ax(),K);le(hb(),K);le(ux(),K);le(dx(),K);le(Ax(),K);le(fx(),K);le(sp(),K);le(gx(),K);le(mx(),K);le(Ex(),K);le(Ix(),K);le(Sx(),K);le(wx(),K);le(Dx(),K);le(Rx(),K);le(Nx(),K);le(KC(),K);le(qx(),K);le(Hx(),K);le(jh(),K);le(iL(),K);le(Pb(),K);le(cL(),K);le(uL(),K);le(pL(),K);le(hL(),K);le(lr(),K);le(xn(),K);le(gL(),K);le(mL(),K);le(ng(),K);le(xc(),K);le(Zl(),K);var lG=aG();Object.defineProperty(K,"SuperglueClient",{enumerable:!0,get:function(){return lG.SuperglueClient}});Object.defineProperty(K,"SuperglueHttpError",{enumerable:!0,get:function(){return lG.SuperglueHttpError}});var BRe=jb();Object.defineProperty(K,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return BRe.SSELogSubscriptionManager}});le(uG(),K)});var lE=require("commander");var wr=pe(require("fs")),pG=pe(require("os")),Vo=pe(require("path")),zA=pe(cr()),dG=new Set(["runner","builder","admin"]),AG={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Jo(t){let e=Vo.join(process.cwd(),".superglue"),r=pG.homedir();if(!r)return e;let n=Vo.join(r,".superglue");return t===!0?e:t===!1?n:wr.existsSync(Vo.join(e,"config.json"))?e:n}function Uv(t){return Vo.join(Jo(t),"config.json")}function vy(t){let e=Uv(t);if(!wr.existsSync(e))return{};try{return JSON.parse(wr.readFileSync(e,"utf-8"))}catch{return{}}}function Ju(t){let e=vy(),r=t.apiKey||(0,zA.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,zA.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,zA.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,zA.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&dG.has(o)?o:e.preset&&dG.has(e.preset)?e.preset:"admin";return{...AG,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...AG.output,...e.output}}}function _y(t,e){let r=Jo(e);wr.existsSync(r)||wr.mkdirSync(r,{recursive:!0}),wr.writeFileSync(Vo.join(r,"config.json"),JSON.stringify(t,null,2)+`
|
|
1774
|
-
`,{mode:384})}function Dy(t,e){let r=Vo.join(Jo(e),"drafts");if(wr.existsSync(r)||wr.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Vo.resolve(t.output.directory);wr.existsSync(n)||wr.mkdirSync(n,{recursive:!0})}}var jv=pe(cr());var Mv=pe(require("readline"));var gG=require("child_process"),mG=require("util");var fG={name:"@superglue/cli",version:"1.1.
|
|
1774
|
+
`,{mode:384})}function Dy(t,e){let r=Vo.join(Jo(e),"drafts");if(wr.existsSync(r)||wr.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Vo.resolve(t.output.directory);wr.existsSync(n)||wr.mkdirSync(n,{recursive:!0})}}var jv=pe(cr());var Mv=pe(require("readline"));var gG=require("child_process"),mG=require("util");var fG={name:"@superglue/cli",version:"1.1.166",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 vRe=(0,mG.promisify)(gG.exec),ur=fG.version;function hG(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function Ry(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=hG(r[o]||"0"),a=hG(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function ky(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var Ty=null;function yG(){re()&&(Ty=ky())}async function EG(){if(!(!re()||!Ty)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([Ty,t]);e&&Ry(ur,e)<0&&(console.error(""),console.error(`${y.cyan}${y.bold} Update available: ${ur} \u2192 ${e}${y.reset}`),console.error(`${y.cyan} Run ${y.bold}sg update${y.reset}${y.cyan} to upgrade${y.reset}`),console.error(""))}catch{}Ty=null}}async function IG(){let t=await ky();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(Ry(ur,t)>=0)return{success:!0,message:`Already on latest version (${ur})`};try{return await vRe("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${ur} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var re=()=>process.argv.includes("--table")&&process.stdout.isTTY,Br=()=>process.argv.includes("--full"),y={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 CG(t,e){let r=e||t;return`\x1B]8;;${t}\x07${y.underline}${y.cyan}${r}${y.reset}\x1B]8;;\x07`}function bG(){if(!re())return;let t=y.reset,e=y.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),u=i.slice(s+1);console.log(` ${a}${r}${c}${t}${u}`)}),console.log(` ${e} CLI v${ur}${t}`),console.log("")}function nt(t){if(!re())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${y.cyan}${e[r++%e.length]}${y.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${y.dim}\u2502${y.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function W(t){re()?Ny(t):console.log(JSON.stringify(t,null,2))}function we(t,e){re()?(console.log(` ${y.green}\u2713${y.reset} ${t}`),e&&Ny(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function _(t,e){re()?(console.error(` ${y.red}\u2717${y.reset} ${t}`),e&&Ny(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function SG(t){re()&&console.log(` ${y.yellow}\u26A0${y.reset} ${t}`)}function Kt(t){re()&&console.log(` ${y.dim}${t}${y.reset}`)}function Wo(t){re()&&(console.log(`
|
|
1775
1775
|
${y.bold}${y.cyan}${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(t.length)}${y.reset}`))}function Qr(t,e,r){if(!re()){console.log(JSON.stringify({success:!0,total:r?.total??t.length,items:t}));return}if(t.length===0){console.log(`
|
|
1776
1776
|
${y.dim}0 results${y.reset}
|
|
1777
1777
|
`);return}let n=e||Object.keys(t[0]),i=Br()?1/0:60,o=n.map(l=>Math.min(i,Math.max(l.length,...t.map(d=>String(d[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=n.map((l,d)=>`${y.bold}${y.cyan}${l.toUpperCase().padEnd(o[d])}${y.reset}`).join(" ");console.log(` ${s}`);let a=o.map(l=>`${y.dim}${"\u2500".repeat(l)}${y.reset}`).join(`${y.dim}\u2500\u2500${y.reset}`);console.log(` ${a}`);for(let l of t){let d=n.map((A,p)=>{let h=String(l[A]??"").replace(/[\n\r]+/g," ").trim();if(h.length>i){let S=`\u2026 (${h.length})`;h=h.slice(0,Math.max(0,i-S.length))+`${y.dim}${S}${y.reset}`}return A==="status"?`${{success:y.green,running:y.yellow,failed:y.red,aborted:y.red,error:y.red,pending:y.dim}[h.toLowerCase()]||""}${h.padEnd(o[p])}${y.reset}`:h.padEnd(o[p])}).join(" ");console.log(` ${d}`)}let c=r?.total??t.length,u=c===t.length?`${t.length} result${t.length===1?"":"s"}`:`${t.length} of ${c} result${c===1?"":"s"}`;console.log(`
|
|
@@ -1843,8 +1843,8 @@ ${Object.entries(Gs.systems).filter(([,n])=>n.oauth).map(([n,i])=>` ${n.padEnd(
|
|
|
1843
1843
|
`).action(async r=>{let{client:n}=e(),i;if(r.config)try{i=JSON.parse(tY.readFileSync(r.config,"utf-8"))}catch(a){_(`Invalid config file: ${a.message}`),process.exit(1)}else{let a,c;if(r.credentials)try{a=JSON.parse(r.credentials)}catch(u){_(`Invalid --credentials JSON: ${u.message}`),process.exit(1)}if(r.authentication)try{c=JSON.parse(r.authentication)}catch(u){_(`Invalid --authentication JSON: ${u.message}`),process.exit(1)}i={id:r.id,name:r.name,url:r.url,specificInstructions:r.instructions,credentials:a,authentication:c}}let o=r.template,s;if(o)s=Gs.systems[o],s||(_(`Template not found: ${o}. Available: ${Object.keys(Gs.systems).join(", ")}`),process.exit(1));else if(i.url||i.name||i.id){let a=(0,Gs.findTemplateForSystem)({url:i.url,name:i.name,id:i.id});a&&(o=a.key,s=a.template,process.stderr.isTTY&&process.stderr.write(`${y.dim}Auto-detected template: ${y.bold}${o}${y.reset}${y.dim} (use --template to override)${y.reset}
|
|
1844
1844
|
`))}if(s&&o){let a={};s.oauth&&(s.oauth.authUrl&&(a.auth_url=s.oauth.authUrl),s.oauth.tokenUrl&&(a.token_url=s.oauth.tokenUrl),s.oauth.scopes&&(a.scopes=s.oauth.scopes)),i={...i,name:i.name||s.name,url:i.url||s.apiUrl,templateName:o,credentials:{...a,...i.credentials}}}(typeof i.name!="string"||i.name.trim()==="")&&(_("System name is required (--name)"),process.exit(1)),i.id||(i.id=(0,Gs.slugify)(i.name.trim()),i.id||(_("System ID could not be derived from name; use --id with letters or numbers"),process.exit(1)));try{let a=nt(`Creating system ${y.bold}${i.id}${y.reset}...`),c=await n.createSystem(i);if(a.stop(),r.docsUrl)try{await n.triggerSystemDocumentationScrapeJob(c.id,{url:r.docsUrl})}catch{}if(r.openapiUrl)try{await n.fetchOpenApiSpec(c.id,r.openapiUrl)}catch{}re()?we(`System created: ${y.bold}${c.id}${y.reset}`,{name:c.name,url:c.url,...o?{template:o}:{}}):W({success:!0,system:{id:c.id,name:c.name,url:c.url},...o?{template:o}:{}})}catch(a){_(a.message),process.exit(1)}})}function nY(t,e){t.command("edit").description("Edit an existing system").requiredOption("--id <id>","System ID").option("--name <name>","New name").option("--url <url>","New URL").option("--instructions <text>","New specific instructions").option("--credentials <json>","Credentials JSON to merge (all fields including secrets)").option("--authentication <json>","Authentication config JSON").option("--scrape-url <url>","Documentation URL to scrape").option("--scrape-keywords <keywords>","Space-separated scrape keywords").action(async r=>{let{client:n}=e(),i={id:r.id};if(r.name&&(i.name=r.name),r.url&&(i.url=r.url),r.instructions&&(i.specificInstructions=r.instructions),r.credentials)try{i.credentials=JSON.parse(r.credentials)}catch(o){_(`Invalid --credentials JSON: ${o.message}`),process.exit(1)}if(r.authentication)try{i.authentication=JSON.parse(r.authentication)}catch(o){_(`Invalid --authentication JSON: ${o.message}`),process.exit(1)}try{let o=nt(`Updating system ${y.bold}${r.id}${y.reset}...`),s=await n.getSystem(r.id);s||(o.stop(),_(`System not found: ${r.id}`),process.exit(1)),i.credentials&&s.credentials&&(i.credentials={...s.credentials,...i.credentials});let a=await n.updateSystem(r.id,i);if(r.scrapeUrl)try{let c=r.scrapeKeywords?.split(" ").filter(Boolean);await n.triggerSystemDocumentationScrapeJob(a.id,{url:r.scrapeUrl,keywords:c})}catch(c){let u=c instanceof Error?c.message:String(c||"Unknown error");SG(`Documentation scrape failed for ${r.scrapeUrl}: ${u}`)}o.stop(),re()?we(`System updated: ${y.bold}${a.id}${y.reset}`):W({success:!0,system:{id:a.id,name:a.name,url:a.url}})}catch(o){_(o.message),process.exit(1)}})}var Ky=pe(cr());function iY(t){if(!t.createdAt)return Number.POSITIVE_INFINITY;let e=new Date(t.createdAt).getTime();return Number.isNaN(e)?Number.POSITIVE_INFINITY:e}function WRe(t){let e=t.filter(r=>r.isOwner);return e.find(r=>r.isDefault)||e.sort((r,n)=>iY(r)-iY(n))[0]}async function Ko(t,e){let r=await t.listAllCredentials({systemId:e});return WRe(r)}async function oY({client:t,systemId:e,credentials:r,url:n}){let i=await Ko(t,e);if(!i)return Object.keys(r).length===0&&n===void 0?null:t.createCredentials({systemId:e,credentials:r,url:n||void 0});let o=await t.replaceCredentials(i.id,r);return n===void 0?o:t.updateCredentials(i.id,{url:n||null})}async function sY(t,e){let r=await Ko(t,e);return r?t.replaceCredentials(r.id,{}):null}function aY(t){return t.authentication?.type||"none"}function ZRe(t){return t.hasUserCredentials?"credentials: configured":"credentials: missing"}function Yv(t,e){return{id:t.id,name:t.name,url:t.url,tags:t.tags,authType:aY(t),hasUserCredentials:!!t.hasUserCredentials,...Array.isArray(t.requiredCredentialKeys)&&t.requiredCredentialKeys.length>0?{requiredCredentialKeys:t.requiredCredentialKeys}:{},specificInstructions:t.specificInstructions,credentialKeys:e?.map(r=>({...r,placeholder:`<<${t.id}_${r.key}>>`}))}}function cY(t,e){t.command("list").description("List all systems").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||25,1),Ky.LIST_MAX_LIMIT),o=Math.max(parseInt(r.offset,10)||0,0),{items:s,total:a,hasMore:c}=await Wy({limit:i,offset:o,fetchPage:(d,A)=>n.listSystems({limit:A,page:d})}),u=Br(),l=s.map(d=>({id:d.id,name:d.name||"",tags:Array.isArray(d.tags)?d.tags.join(","):"",auth:aY(d),url:u?d.url||"":(d.url||"").slice(0,40),credentials:ZRe(d)}));re()?Qr(l,["id","name","tags","auth","url","credentials"],{total:a}):W({success:!0,total:a,hasMore:c,items:l})}catch(i){_(i.message),process.exit(1)}}),t.command("find [query]").description("Find systems by query or exact ID").option("--id <exactId>","Exact system ID lookup").action(async(r,n)=>{let{client:i}=e();try{if(n.id){let u=await i.getSystem(n.id);u||(_(`System not found: ${n.id}`),process.exit(1));let l=(0,Ky.findTemplateForSystem)(u),d;u.hasUserCredentials&&(d=(await Ko(i,u.id))?.credentialKeys),W({success:!0,system:Yv(u,d),template:l?.template||null});return}let o=(r||"*").trim(),{data:s}=await i.listSystems({limit:100,page:1});if(o==="*"){W({success:!0,systems:s.map(u=>Yv(u))});return}let a=o.toLowerCase().split(/\s+/),c=s.filter(u=>{let l=[u.id,u.name,u.url].filter(Boolean).join(" ").toLowerCase();return a.some(d=>l.includes(d))});W({success:!0,systems:c.map(u=>Yv(u))})}catch(o){_(o.message),process.exit(1)}})}var Xy=pe(cr());function KRe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&"currentItem"in t&&"data"in t&&typeof t.success=="boolean"}function uY(t,e){t.command("call").description("Call a system (API, database, file server)").option("--url <url>","Absolute URL, or <<systemId_url>> followed by the path").option("--system-id <id>","System ID; selects your credential and adds its auth header").option("--credential-id <id>","Credential override; implies its system when --system-id is omitted").option("--auth <mode>","auto (default) adds the auth header; none sends no default header","auto").option("--method <method>","HTTP method","GET").option("--headers <json>","HTTP headers JSON").option("--body <string>","Request body").option("--timeout <ms>","Per-request timeout in milliseconds (minimum 1000)").option("--continue-on-error","Return failed response envelope instead of exiting non-zero").option("--file <key=path...>","File references",(r,n)=>(n.push(r),n),[]).addHelpText("after",`
|
|
1845
1845
|
${y.bold}Authentication:${y.reset}
|
|
1846
|
-
With --system-id or --credential-id the server picks your credential (starred,
|
|
1847
|
-
|
|
1846
|
+
With --system-id or --credential-id the server picks your credential (your starred one, otherwise
|
|
1847
|
+
the accessible one you have held longest, owned or shared), refreshes OAuth tokens, and adds the
|
|
1848
1848
|
Authorization header for oauth2, basic_auth, and api_key systems. The result reports the credential
|
|
1849
1849
|
and auth that were used. An Authorization header or any <<systemId_secretName>> placeholder you pass
|
|
1850
1850
|
replaces the default header; 'sg system find --id <id>' prints each secret's placeholder.
|
|
@@ -44,7 +44,7 @@ Read these on demand — they are authoritative for their topic and kept in sync
|
|
|
44
44
|
|
|
45
45
|
**Authentication & Credentials**
|
|
46
46
|
|
|
47
|
-
- `sg system call --system-id <id> --url <url>` selects your credential (starred,
|
|
47
|
+
- `sg system call --system-id <id> --url <url>` selects your credential (your starred one, otherwise the accessible one you have held longest, owned or shared), refreshes OAuth tokens, and adds the `Authorization` header for `oauth2`, `basic_auth`, and `api_key` systems. The output reports `credential` and `auth`; `auth.applied: "unavailable"` names what is missing. Pass `--credential-id` to use a specific credential. `--url` is the absolute URL, or `<<systemId_url>>` plus the path for tenant-specific hosts.
|
|
48
48
|
- Pass `--headers` with `<<systemId_credentialKey>>` placeholders only when the API expects another header or a query parameter; that replaces the default header. `sg system find --id <id>` prints each secret's exact placeholder; `sg system call` rejects bare `<<credentialKey>>` placeholders before sending.
|
|
49
49
|
- Saved tool steps inject nothing: put the auth header or connection string in the step config.
|
|
50
50
|
- Databases/Redis/file servers: embed credential placeholders in the connection URL (e.g. `postgres://<<sys_user>>:<<sys_pass>>@host/db`).
|
package/package.json
CHANGED
|
@@ -44,7 +44,7 @@ Read these on demand — they are authoritative for their topic and kept in sync
|
|
|
44
44
|
|
|
45
45
|
**Authentication & Credentials**
|
|
46
46
|
|
|
47
|
-
- `sg system call --system-id <id> --url <url>` selects your credential (starred,
|
|
47
|
+
- `sg system call --system-id <id> --url <url>` selects your credential (your starred one, otherwise the accessible one you have held longest, owned or shared), refreshes OAuth tokens, and adds the `Authorization` header for `oauth2`, `basic_auth`, and `api_key` systems. The output reports `credential` and `auth`; `auth.applied: "unavailable"` names what is missing. Pass `--credential-id` to use a specific credential. `--url` is the absolute URL, or `<<systemId_url>>` plus the path for tenant-specific hosts.
|
|
48
48
|
- Pass `--headers` with `<<systemId_credentialKey>>` placeholders only when the API expects another header or a query parameter; that replaces the default header. `sg system find --id <id>` prints each secret's exact placeholder; `sg system call` rejects bare `<<credentialKey>>` placeholders before sending.
|
|
49
49
|
- Saved tool steps inject nothing: put the auth header or connection string in the step config.
|
|
50
50
|
- Databases/Redis/file servers: embed credential placeholders in the connection URL (e.g. `postgres://<<sys_user>>:<<sys_pass>>@host/db`).
|