@tableau/mcp-server 1.10.3 → 1.12.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/build/index.js +40 -30
- package/build/index.js.map +4 -4
- package/package.json +8 -3
package/build/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Ca=Object.defineProperty;var Ra=(t,e)=>{for(var r in e)Ca(t,r,{get:e[r],enumerable:!0})};import{StdioServerTransport as lm}from"@modelcontextprotocol/sdk/server/stdio.js";import cm from"dotenv";import{existsSync as ka}from"fs";import{join as Pa}from"path";import{fileURLToPath as Da}from"url";var jr=["list-datasources","list-workbooks","list-views","query-datasource","get-datasource-metadata","get-workbook","get-view-data","get-view-image","list-all-pulse-metric-definitions","list-pulse-metric-definitions-from-definition-ids","list-pulse-metrics-from-metric-definition-id","list-pulse-metrics-from-metric-ids","list-pulse-metric-subscriptions","generate-pulse-metric-value-insight-bundle","search-content"],xa=["datasource","workbook","view","pulse","content-exploration"],Vr={datasource:["list-datasources","get-datasource-metadata","query-datasource"],workbook:["list-workbooks","get-workbook"],view:["list-views","get-view-data","get-view-image"],pulse:["list-all-pulse-metric-definitions","list-pulse-metric-definitions-from-definition-ids","list-pulse-metrics-from-metric-definition-id","list-pulse-metrics-from-metric-ids","list-pulse-metric-subscriptions","generate-pulse-metric-value-insight-bundle"],"content-exploration":["search-content"]};function Br(t){return!!jr.find(e=>e===t)}function zr(t){return!!xa.find(e=>e===t)}var Ia=["stdio","http"];function ni(t){return!!Ia.find(e=>e===t)}function ce(t,e){if(!t)throw new Error(e||"Invariant Violation")}var La=Da(new URL(".",import.meta.url)),Oa=10*60*1e3,ai=60*60*1e3,li=30*24*60*60*1e3,Ma=365.25*24*60*60*1e3,Na=["pat","direct-trust","oauth"];function Fa(t){return!!Na.find(e=>e===t)}var Hr=class{auth;server;transport;sslKey;sslCert;httpPort;corsOriginConfig;trustProxyConfig;siteName;patName;patValue;jwtSubClaim;connectedAppClientId;connectedAppSecretId;connectedAppSecretValue;jwtAdditionalPayload;datasourceCredentials;defaultLogLevel;disableLogMasking;includeTools;excludeTools;maxResultLimit;disableQueryDatasourceFilterValidation;disableMetadataApiRequests;disableSessionManagement;enableServerLogging;serverLogDirectory;boundedContext;tableauServerVersionCheckIntervalInHours;oauth;constructor(){let e=Va(process.env),{AUTH:r,SERVER:o,SITE_NAME:i,TRANSPORT:n,SSL_KEY:s,SSL_CERT:a,HTTP_PORT_ENV_VAR_NAME:c,CORS_ORIGIN_CONFIG:l,TRUST_PROXY_CONFIG:u,PAT_NAME:p,PAT_VALUE:g,JWT_SUB_CLAIM:b,CONNECTED_APP_CLIENT_ID:f,CONNECTED_APP_SECRET_ID:y,CONNECTED_APP_SECRET_VALUE:w,JWT_ADDITIONAL_PAYLOAD:v,DATASOURCE_CREDENTIALS:D,DEFAULT_LOG_LEVEL:A,DISABLE_LOG_MASKING:x,INCLUDE_TOOLS:R,EXCLUDE_TOOLS:j,MAX_RESULT_LIMIT:F,DISABLE_QUERY_DATASOURCE_FILTER_VALIDATION:ae,DISABLE_METADATA_API_REQUESTS:pe,DISABLE_SESSION_MANAGEMENT:Ae,ENABLE_SERVER_LOGGING:_e,SERVER_LOG_DIRECTORY:se,INCLUDE_PROJECT_IDS:le,INCLUDE_DATASOURCE_IDS:$,INCLUDE_WORKBOOK_IDS:J,TABLEAU_SERVER_VERSION_CHECK_INTERVAL_IN_HOURS:Se,DANGEROUSLY_DISABLE_OAUTH:S,OAUTH_ISSUER:_,OAUTH_JWE_PRIVATE_KEY:z,OAUTH_JWE_PRIVATE_KEY_PATH:K,OAUTH_JWE_PRIVATE_KEY_PASSPHRASE:U,OAUTH_REDIRECT_URI:te,OAUTH_CLIENT_ID_SECRET_PAIRS:me,OAUTH_AUTHORIZATION_CODE_TIMEOUT_MS:Y,OAUTH_ACCESS_TOKEN_TIMEOUT_MS:re,OAUTH_REFRESH_TOKEN_TIMEOUT_MS:er}=e;if(this.siteName=i??"",this.sslKey=s?.trim()??"",this.sslCert=a?.trim()??"",this.httpPort=At(e[c?.trim()||"PORT"],{defaultValue:3927,minValue:1,maxValue:65535}),this.corsOriginConfig=qa(l?.trim()??""),this.trustProxyConfig=ja(u?.trim()??""),this.datasourceCredentials=D??"",this.defaultLogLevel=A??"debug",this.disableLogMasking=x==="true",this.disableQueryDatasourceFilterValidation=ae==="true",this.disableMetadataApiRequests=pe==="true",this.disableSessionManagement=Ae==="true",this.enableServerLogging=_e==="true",this.serverLogDirectory=se||Pa(La,"logs"),this.boundedContext={projectIds:Wr(le),datasourceIds:Wr($),workbookIds:Wr(J)},this.boundedContext.projectIds?.size===0)throw new Error("When set, the environment variable INCLUDE_PROJECT_IDS must have at least one value");if(this.boundedContext.datasourceIds?.size===0)throw new Error("When set, the environment variable INCLUDE_DATASOURCE_IDS must have at least one value");if(this.boundedContext.workbookIds?.size===0)throw new Error("When set, the environment variable INCLUDE_WORKBOOK_IDS must have at least one value");this.tableauServerVersionCheckIntervalInHours=At(Se,{defaultValue:1,minValue:1,maxValue:24*7});let Le=S==="true";if(this.oauth={enabled:Le?!1:!!_,issuer:_??"",redirectUri:te||(_?`${_}/Callback`:""),jwePrivateKey:z??"",jwePrivateKeyPath:K??"",jwePrivateKeyPassphrase:U||void 0,authzCodeTimeoutMs:At(Y,{defaultValue:Oa,minValue:0,maxValue:ai}),accessTokenTimeoutMs:At(re,{defaultValue:ai,minValue:0,maxValue:li}),refreshTokenTimeoutMs:At(er,{defaultValue:li,minValue:0,maxValue:Ma}),clientIdSecretPairs:me?me.split(",").reduce((Ye,fe)=>{let[ii,si]=fe.split(":");return ii&&si&&(Ye[ii]=si),Ye},{}):null},this.auth=Fa(r)?r:this.oauth.enabled?"oauth":"pat",this.transport=ni(n)?n:this.oauth.enabled?"http":"stdio",this.transport==="http"&&!Le&&!this.oauth.issuer)throw new Error('OAUTH_ISSUER must be set when TRANSPORT is "http" unless DANGEROUSLY_DISABLE_OAUTH is "true"');if(this.auth==="oauth"){if(Le)throw new Error('When AUTH is "oauth", DANGEROUSLY_DISABLE_OAUTH cannot be "true"');if(!this.oauth.issuer)throw new Error('When AUTH is "oauth", OAUTH_ISSUER must be set')}else ce(o,"The environment variable SERVER is not set"),Ua(o);if(this.oauth.enabled){if(ce(this.oauth.redirectUri,"The environment variable OAUTH_REDIRECT_URI is not set"),!this.oauth.jwePrivateKey&&!this.oauth.jwePrivateKeyPath)throw new Error("One of the environment variables: OAUTH_JWE_PRIVATE_KEY_PATH or OAUTH_JWE_PRIVATE_KEY must be set");if(this.oauth.jwePrivateKey&&this.oauth.jwePrivateKeyPath)throw new Error("Only one of the environment variables: OAUTH_JWE_PRIVATE_KEY or OAUTH_JWE_PRIVATE_KEY_PATH must be set");if(this.oauth.jwePrivateKeyPath&&process.env.TABLEAU_MCP_TEST!=="true"&&!ka(this.oauth.jwePrivateKeyPath))throw new Error(`OAuth JWE private key path does not exist: ${this.oauth.jwePrivateKeyPath}`);if(this.transport==="stdio")throw new Error('TRANSPORT must be "http" when OAUTH_ISSUER is set')}let Q=F?parseInt(F):NaN;if(this.maxResultLimit=isNaN(Q)||Q<=0?null:Q,this.includeTools=R?R.split(",").flatMap(Ye=>{let fe=Ye.trim();return Br(fe)?fe:zr(fe)?Vr[fe]:[]}):[],this.excludeTools=j?j.split(",").flatMap(Ye=>{let fe=Ye.trim();return Br(fe)?fe:zr(fe)?Vr[fe]:[]}):[],this.includeTools.length>0&&this.excludeTools.length>0)throw new Error("Cannot include and exclude tools simultaneously");this.auth==="pat"?(ce(p,"The environment variable PAT_NAME is not set"),ce(g,"The environment variable PAT_VALUE is not set")):this.auth==="direct-trust"&&(ce(b,"The environment variable JWT_SUB_CLAIM is not set"),ce(f,"The environment variable CONNECTED_APP_CLIENT_ID is not set"),ce(y,"The environment variable CONNECTED_APP_SECRET_ID is not set"),ce(w,"The environment variable CONNECTED_APP_SECRET_VALUE is not set")),this.server=o??"",this.patName=p??"",this.patValue=g??"",this.jwtSubClaim=b??"",this.connectedAppClientId=f??"",this.connectedAppSecretId=y??"",this.connectedAppSecretValue=w??"",this.jwtAdditionalPayload=v||"{}"}};function Ua(t){if(!t.startsWith("https://"))throw new Error(`The environment variable SERVER must start with "https://": ${t}`);try{let e=new URL(t)}catch(e){let r=e instanceof Error?e.message:String(e);throw new Error(`The environment variable SERVER is not a valid URL: ${t} -- ${r}`)}}function qa(t){if(!t)return!0;if(t.match(/^true|false$/i))return t.toLowerCase()==="true";if(t==="*")return"*";if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t).map(r=>new URL(r).origin)}catch{throw new Error(`The environment variable CORS_ORIGIN_CONFIG is not a valid array of URLs: ${t}`)}try{return new URL(t).origin}catch{throw new Error(`The environment variable CORS_ORIGIN_CONFIG is not a valid URL: ${t}`)}}function ja(t){return t?t.match(/^true|false$/i)?t.toLowerCase()==="true":t.match(/^\d+$/)?parseInt(t,10):t:null}function Wr(t){return t===void 0?null:new Set(t.trim().split(",").map(e=>e.trim()).filter(Boolean))}function Va(t){return Object.entries(t).reduce((e,[r,o])=>(o?.startsWith("${user_config.")?e[r]="":e[r]=o,e),{})}function At(t,{defaultValue:e,minValue:r,maxValue:o}={defaultValue:0,minValue:Number.NEGATIVE_INFINITY,maxValue:Number.POSITIVE_INFINITY}){if(!t)return e;let i=parseFloat(t);return isNaN(i)||r!==void 0&&i<r||o!==void 0&&i>o?e:i}var E=()=>new Hr;var Gr=["debug","info","notice","warning","error","critical","alert","emergency"],Et="debug",ci;function ui(t){return!!Gr.find(e=>e===t)}var Xe=(t,e,{silent:r=!1}={})=>{Et!==e&&(Et=e,r||ue.notice(t,`Logging level set to: ${e}`))},di=t=>{ci=t},ue={debug:ve("debug"),info:ve("info"),notice:ve("notice"),warning:ve("warning"),error:ve("error"),critical:ve("critical"),alert:ve("alert"),emergency:ve("emergency")},Oe=(t=Et)=>Gr.indexOf(t)>=Gr.indexOf(Et),Me=t=>{process.env.TABLEAU_MCP_TEST!=="true"&&(t=t.endsWith(`
|
|
3
3
|
`)?t:`${t}
|
|
4
|
-
`,process.stderr.write(t))},
|
|
5
|
-
`)}catch(u){Se(`Failed to write to log file ${o}: ${ae(u)}`)}});this._fileMutexes.set(n,l),l.finally(()=>{this._fileMutexes.get(n)===l&&this._fileMutexes.delete(n)}),await l}};import{McpServer as Uu}from"@modelcontextprotocol/sdk/server/mcp.js";import{SetLevelRequestSchema as ju}from"@modelcontextprotocol/sdk/types.js";var Ai={name:"@tableau/mcp-server",description:"An MCP server for Tableau, providing a suite of tools that will make it easier for developers to build AI applications that integrate with Tableau.",version:"1.10.3",repository:{type:"git",url:"git+https://github.com/tableau/tableau-mcp.git"},homepage:"https://github.com/tableau/tableau-mcp",bugs:"https://github.com/tableau/tableau-mcp/issues",author:"Tableau",type:"module",license:"Apache-2.0",keywords:["tableau","mcp"],bin:{"tableau-mcp-server":"./build/index.js"},scripts:{":build":"npx rimraf ./build && esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --minify --outdir=build --sourcemap",build:"run-s :build exec-perms","build:watch":"npm run :build -- --watch","build:docker":"docker build -t tableau-mcp .",":build:mcpb":"npx -y @anthropic-ai/mcpb pack . tableau-mcp.mcpb","build:mcpb":"run-s build:manifest:script build:manifest :build:mcpb","build:manifest":"node build/scripts/createClaudeMcpBundleManifest.mjs","build:manifest:script":"esbuild src/scripts/createClaudeMcpBundleManifest.ts --bundle --platform=node --format=esm --outdir=build/scripts --sourcemap=inline --out-extension:.js=.mjs","start:http":"node build/index.js","start:http:docker":"docker run -p 3927:3927 -i --rm --env-file env.list tableau-mcp",lint:"npm exec eslint",inspect:"npx @modelcontextprotocol/inspector --config config.json --server tableau",":inspect:http":"npx @modelcontextprotocol/inspector --config config.http.json --server tableau","inspect:http":"run-p start:http :inspect:http","inspect:docker":"npx @modelcontextprotocol/inspector --config config.docker.json --server tableau","inspect:docker:http":"run-p start:http:docker :inspect:http","build:inspect":"run-s build inspect","build:inspect:docker":"run-s build:docker inspect:docker","build:inspect:docker:http":"run-s build:docker inspect:docker:http","exec-perms":"shx chmod +x build/*.js",test:"vitest --config ./vitest.config.ts","test:e2e":"vitest --config ./vitest.config.e2e.ts","test:eval":"vitest --config ./vitest.config.eval.ts",coverage:"vitest run --config ./vitest.config.ts --coverage","version:major":"npm version major --no-git-tag-version","version:minor":"npm version minor --no-git-tag-version","version:patch":"npm version patch --no-git-tag-version"},dependencies:{"@modelcontextprotocol/sdk":"^1.12.1","@zodios/core":"^10.9.6",cors:"^2.8.5",dotenv:"^16.5.0",express:"^5.1.0","fast-levenshtein":"^3.0.0",jose:"^6.0.12","ts-results-es":"^5.0.1",zod:"^3.24.3","zod-validation-error":"^4.0.1"},devDependencies:{"@anthropic-ai/mcpb":"^1.0.0","@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.25.1","@modelcontextprotocol/inspector":"^0.16.6","@openai/agents":"^0.1.9","@types/cors":"^2.8.19","@types/eslint__js":"^8.42.3","@types/express":"^5.0.3","@types/fast-levenshtein":"^0.0.1","@types/node":"^22.15.3","@typescript-eslint/eslint-plugin":"^8.31.1","@typescript-eslint/parser":"^8.31.1","@vitest/coverage-v8":"^3.1.3",esbuild:"^0.25.5",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","eslint-plugin-prettier":"^5.2.6","eslint-plugin-simple-import-sort":"^12.1.1","npm-run-all":"^4.1.5",openai:"^5.23.2",prettier:"^3.5.3",rimraf:"^6.0.1",shx:"^0.4.0",typescript:"^5.8.3","typescript-eslint":"^8.31.1",vitest:"^3.1.3"},engines:{node:">=20"}};import{Ok as Gc}from"ts-results-es";import{z as fs}from"zod";import{Err as Si,Ok as An}from"ts-results-es";var _i=t=>{let e=Ri(t);if(e.isErr())return t;let r=e.value;return Ae("debug")?(r.data?.credentials&&(r.data.credentials="<redacted>"),Array.isArray(r?.data?.datasource?.connections)&&r.data.datasource.connections.forEach(o=>{o.connectionUsername="<redacted>",o.connectionPassword="<redacted>"}),r.headers?.["X-Tableau-Auth"]&&(r.headers["X-Tableau-Auth"]="<redacted>"),r.params?.user_id&&(r.params.user_id="<redacted>")):(delete r.data,delete r.headers,delete r.params),r},Ci=t=>{let e=Ri(t);if(e.isErr())return t;let r=e.value;return Ae("debug")?r.data?.credentials&&(r.data.credentials="<redacted>"):(delete r.data,delete r.headers),r};function Ri(t){try{return An(structuredClone(t))}catch(e){if(e instanceof Error)return Si(e);let r=ae(e);return Se(`Could not clone object, notification may not be sanitized! Error: ${r}`),Si(new Error(r))}}function Pt(t){return{method:t.method??"UNKNOWN METHOD",url:t.url??"UNKNOWN URL",headers:t.headers,data:t.data,params:t.params}}function Nt(t){return{url:t.config.url??"UNKNOWN URL",status:t.status,headers:t.headers,data:t.data}}import{Zodios as Di}from"@zodios/core";import{randomUUID as Sn}from"node:crypto";import{SignJWT as _n}from"jose";async function xi({username:t,connectedApp:e,scopes:r,additionalPayload:i}){let o={alg:"HS256",typ:"JWT",kid:e.secretId},n={jti:Sn(),iss:e.clientId,aud:"tableau",sub:t,scp:[...r],iat:Math.floor(Date.now()/1e3)-5,exp:Math.floor(Date.now()/1e3)+5*60,...i};return await new _n(n).setProtectedHeader(o).sign(new TextEncoder().encode(e.secretValue))}import{makeApi as Cn,makeEndpoint as Li}from"@zodios/core";import{z as de}from"zod";import{z as _e}from"zod";var vi=_e.object({credentials:_e.object({site:_e.object({id:_e.string()}),user:_e.object({id:_e.string()}),token:_e.string()})});var Rn=de.object({credentials:de.object({site:de.object({contentUrl:de.string()})}).and(de.object({personalAccessTokenName:de.string(),personalAccessTokenSecret:de.string()}).or(de.object({jwt:de.string()})))}),xn=Li({method:"post",path:"/auth/signin",alias:"signIn",description:"Signs in with Tableau credentials.",response:vi,parameters:[{name:"credentials",type:"Body",schema:Rn}]}),vn=Li({method:"post",path:"/auth/signout",alias:"signOut",description:"Signs you out of the current session. This call invalidates the authentication token that is created by a call to Sign In.",response:de.void()}),Ln=Cn([xn,vn]),yr=[...Ln];var Ce=class{_apiClient;constructor(e){this._apiClient=e}get interceptors(){return this._apiClient.axios.interceptors}};var W=class extends Ce{_creds;get authHeader(){if(!this._creds)throw new Error("Authenticate by calling signIn() first");return{headers:{"X-Tableau-Auth":this._creds.token}}}get userId(){if(!this._creds)throw new Error("Authenticate by calling signIn() first");return this._creds.user.id}constructor(e,r){super(e),this._creds=r}};var nt=class extends Ce{constructor(e){super(new Di(e,yr))}signIn=async e=>(await this._apiClient.signIn({credentials:{site:{contentUrl:e.siteName},...await(async()=>{switch(e.type){case"pat":return{personalAccessTokenName:e.patName,personalAccessTokenSecret:e.patValue};case"direct-trust":return{jwt:await xi({username:e.username,connectedApp:{clientId:e.clientId,secretId:e.secretId,secretValue:e.secretValue},scopes:e.scopes,additionalPayload:e.additionalPayload})}}})()}})).credentials},Ft=class extends W{constructor(e,r){super(new Di(e,yr),r)}signOut=async()=>{await this._apiClient.signOut(void 0,{...this.authHeader})}};import{Zodios as kn}from"@zodios/core";import{makeApi as On,makeEndpoint as Pn}from"@zodios/core";import{z as Me}from"zod";import{z as L}from"zod";var Dn=L.enum(["hitsTotal","hitsSmallSpanTotal","hitsMediumSpanTotal","hitsLargeSpanTotal","downstreamWorkbookCount"]),Ii=L.array(L.object({method:Dn,sortDirection:L.enum(["asc","desc"]).default("asc").optional()})).nonempty(),Oi=L.enum(["lens","datasource","virtualconnection","collection","project","flow","datarole","table","database","view","workbook"]),Pi=L.union([L.array(L.string().datetime()).nonempty(),L.object({startDate:L.string().datetime(),endDate:L.string().datetime().optional()}).strict(),L.object({startDate:L.string().datetime().optional(),endDate:L.string().datetime()}).strict()]),br=L.object({contentTypes:L.array(Oi).nonempty(),ownerIds:L.array(L.number().int()).nonempty(),modifiedTime:Pi}).partial(),Ni=L.union([br.extend({contentTypes:L.array(Oi).nonempty()}).strict(),br.extend({ownerIds:L.array(L.number().int()).nonempty()}).strict(),br.extend({modifiedTime:Pi}).strict()]),In=L.object({uri:L.string(),content:L.record(L.string(),L.unknown())}),Fi=L.object({next:L.string(),prev:L.string(),pageIndex:L.number().int(),startIndex:L.number().int(),total:L.number().int(),limit:L.number().int(),items:L.array(In)}).partial();var Nn=Pn({method:"get",path:"/search",alias:"searchContent",description:"Searches across all supported content types for objects relevant to the search expression specified in the querystring of the request URI.",parameters:[{name:"terms",type:"Query",schema:Me.string().optional()},{name:"page",type:"Query",schema:Me.number().int().optional()},{name:"limit",type:"Query",schema:Me.number().int().optional()},{name:"order_by",type:"Query",schema:Me.string().optional()},{name:"filter",type:"Query",schema:Me.string().optional()}],response:Me.object({hits:Fi})}),Fn=On([Nn]),ki=[...Fn];var at=class extends W{constructor(e,r){super(new kn(e,ki),r)}searchContent=async e=>(Object.entries(e).forEach(([i,o])=>{o===void 0&&delete e[i]}),(await this._apiClient.searchContent({queries:e,...this.authHeader})).hits)};import{Zodios as Bn}from"@zodios/core";import{makeApi as Mn,makeEndpoint as qn}from"@zodios/core";import{z as je}from"zod";import{z as Mt}from"zod";import{z as Tr}from"zod";var kt=Tr.object({name:Tr.string(),id:Tr.string()});var Mi=Mt.object({id:Mt.string(),name:Mt.string(),description:Mt.string().optional(),project:kt});import{z as qt}from"zod";var qe=qt.object({pageNumber:qt.coerce.number(),pageSize:qt.coerce.number(),totalAvailable:qt.coerce.number()});import{z as qi}from"zod";var Ue=[{name:"pageSize",type:"Query",schema:qi.number().optional(),description:"The number of items to return in one response. The minimum is 1. The maximum is 1000. The default is 100."},{name:"pageNumber",type:"Query",schema:qi.number().optional(),description:"The offset for paging. The default is 1."}];var Un=qn({method:"get",path:"/sites/:siteId/datasources",alias:"listDatasources",description:"Returns a list of published data sources on the specified site. Supports a filter string as a query parameter in the format field:operator:value.",parameters:[...Ue,{name:"siteId",type:"Path",schema:je.string()},{name:"filter",type:"Query",schema:je.string().optional(),description:"Filter string in the format field:operator:value (e.g., name:eq:Project Views)"}],response:je.object({pagination:qe,datasources:je.object({datasource:je.optional(je.array(Mi))})})}),jn=Mn([Un]),Ui=[...jn];var lt=class extends W{constructor(e,r){super(new Bn(e,Ui),r)}listDatasources=async({siteId:e,filter:r,pageSize:i,pageNumber:o})=>{let n=await this._apiClient.listDatasources({params:{siteId:e},queries:{filter:r,pageSize:i,pageNumber:o},...this.authHeader});return{pagination:n.pagination,datasources:n.datasources.datasource??[]}}};import{Zodios as Qn}from"@zodios/core";import{makeApi as Vn,makeEndpoint as zn}from"@zodios/core";import{z as D}from"zod";var Wn=D.object({data:D.object({publishedDatasources:D.array(D.object({name:D.string().nullable(),description:D.string().nullable(),owner:D.object({name:D.string().nullable()}),fields:D.array(D.object({name:D.string(),isHidden:D.boolean().nullable(),description:D.string().nullable(),descriptionInherited:D.array(D.object({attribute:D.string(),value:D.string().nullable()}).nullable()).nullable(),fullyQualifiedName:D.string(),__typename:D.string(),dataCategory:D.string().nullish(),role:D.string().nullish(),dataType:D.string().nullish(),defaultFormat:D.string().nullish(),semanticRole:D.string().nullish(),aggregation:D.string().nullish(),aggregationParam:D.string().nullish(),formula:D.string().nullish(),isAutoGenerated:D.boolean().nullish(),hasUserReference:D.boolean().nullish(),binSize:D.number().nullish(),hasOther:D.boolean().nullish(),delimiter:D.string().nullish(),combinationType:D.string().nullish()}))}))})}),Hn=zn({method:"post",path:"/graphql",alias:"graphql",response:Wn,parameters:[{name:"query",type:"Body",schema:D.object({query:D.string()})}]}),Gn=Vn([Hn]),ji=[...Gn];var ct=class extends W{constructor(e,r){super(new Qn(e,ji),r)}graphql=async e=>await this._apiClient.graphql({query:e},{...this.authHeader})};import{Zodios as Xl}from"@zodios/core";import{Err as Zo,Ok as ec}from"ts-results-es";function ut(t,e){return function(){return t.apply(e,arguments)}}var{toString:$n}=Object.prototype,{getPrototypeOf:Er}=Object,{iterator:jt,toStringTag:Vi}=Symbol,Bt=(t=>e=>{let r=$n.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),le=t=>(t=t.toLowerCase(),e=>Bt(e)===t),Vt=t=>e=>typeof e===t,{isArray:Ve}=Array,Be=Vt("undefined");function dt(t){return t!==null&&!Be(t)&&t.constructor!==null&&!Be(t.constructor)&&J(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var zi=le("ArrayBuffer");function Zn(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&zi(t.buffer),e}var Jn=Vt("string"),J=Vt("function"),Wi=Vt("number"),pt=t=>t!==null&&typeof t=="object",Kn=t=>t===!0||t===!1,Ut=t=>{if(Bt(t)!=="object")return!1;let e=Er(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Vi in t)&&!(jt in t)},Yn=t=>{if(!pt(t)||dt(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Xn=le("Date"),ea=le("File"),ta=le("Blob"),ra=le("FileList"),ia=t=>pt(t)&&J(t.pipe),oa=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||J(t.append)&&((e=Bt(t))==="formdata"||e==="object"&&J(t.toString)&&t.toString()==="[object FormData]"))},sa=le("URLSearchParams"),[na,aa,la,ca]=["ReadableStream","Request","Response","Headers"].map(le),ua=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function mt(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let i,o;if(typeof t!="object"&&(t=[t]),Ve(t))for(i=0,o=t.length;i<o;i++)e.call(null,t[i],i,t);else{if(dt(t))return;let n=r?Object.getOwnPropertyNames(t):Object.keys(t),s=n.length,l;for(i=0;i<s;i++)l=n[i],e.call(null,t[l],l,t)}}function Hi(t,e){if(dt(t))return null;e=e.toLowerCase();let r=Object.keys(t),i=r.length,o;for(;i-- >0;)if(o=r[i],e===o.toLowerCase())return o;return null}var Re=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Gi=t=>!Be(t)&&t!==Re;function wr(){let{caseless:t,skipUndefined:e}=Gi(this)&&this||{},r={},i=(o,n)=>{let s=t&&Hi(r,n)||n;Ut(r[s])&&Ut(o)?r[s]=wr(r[s],o):Ut(o)?r[s]=wr({},o):Ve(o)?r[s]=o.slice():(!e||!Be(o))&&(r[s]=o)};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&mt(arguments[o],i);return r}var da=(t,e,r,{allOwnKeys:i}={})=>(mt(e,(o,n)=>{r&&J(o)?t[n]=ut(o,r):t[n]=o},{allOwnKeys:i}),t),pa=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),ma=(t,e,r,i)=>{t.prototype=Object.create(e.prototype,i),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},fa=(t,e,r,i)=>{let o,n,s,l={};if(e=e||{},t==null)return e;do{for(o=Object.getOwnPropertyNames(t),n=o.length;n-- >0;)s=o[n],(!i||i(s,t,e))&&!l[s]&&(e[s]=t[s],l[s]=!0);t=r!==!1&&Er(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},ha=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let i=t.indexOf(e,r);return i!==-1&&i===r},ga=t=>{if(!t)return null;if(Ve(t))return t;let e=t.length;if(!Wi(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},ya=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Er(Uint8Array)),ba=(t,e)=>{let i=(t&&t[jt]).call(t),o;for(;(o=i.next())&&!o.done;){let n=o.value;e.call(t,n[0],n[1])}},Ta=(t,e)=>{let r,i=[];for(;(r=t.exec(e))!==null;)i.push(r);return i},wa=le("HTMLFormElement"),Ea=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,i,o){return i.toUpperCase()+o}),Bi=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Aa=le("RegExp"),Qi=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),i={};mt(r,(o,n)=>{let s;(s=e(o,n,t))!==!1&&(i[n]=s||o)}),Object.defineProperties(t,i)},Sa=t=>{Qi(t,(e,r)=>{if(J(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let i=t[r];if(J(i)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},_a=(t,e)=>{let r={},i=o=>{o.forEach(n=>{r[n]=!0})};return Ve(t)?i(t):i(String(t).split(e)),r},Ca=()=>{},Ra=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function xa(t){return!!(t&&J(t.append)&&t[Vi]==="FormData"&&t[jt])}var va=t=>{let e=new Array(10),r=(i,o)=>{if(pt(i)){if(e.indexOf(i)>=0)return;if(dt(i))return i;if(!("toJSON"in i)){e[o]=i;let n=Ve(i)?[]:{};return mt(i,(s,l)=>{let u=r(s,o+1);!Be(u)&&(n[l]=u)}),e[o]=void 0,n}}return i};return r(t,0)},La=le("AsyncFunction"),Da=t=>t&&(pt(t)||J(t))&&J(t.then)&&J(t.catch),$i=((t,e)=>t?setImmediate:e?((r,i)=>(Re.addEventListener("message",({source:o,data:n})=>{o===Re&&n===r&&i.length&&i.shift()()},!1),o=>{i.push(o),Re.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",J(Re.postMessage)),Ia=typeof queueMicrotask<"u"?queueMicrotask.bind(Re):typeof process<"u"&&process.nextTick||$i,Oa=t=>t!=null&&J(t[jt]),a={isArray:Ve,isArrayBuffer:zi,isBuffer:dt,isFormData:oa,isArrayBufferView:Zn,isString:Jn,isNumber:Wi,isBoolean:Kn,isObject:pt,isPlainObject:Ut,isEmptyObject:Yn,isReadableStream:na,isRequest:aa,isResponse:la,isHeaders:ca,isUndefined:Be,isDate:Xn,isFile:ea,isBlob:ta,isRegExp:Aa,isFunction:J,isStream:ia,isURLSearchParams:sa,isTypedArray:ya,isFileList:ra,forEach:mt,merge:wr,extend:da,trim:ua,stripBOM:pa,inherits:ma,toFlatObject:fa,kindOf:Bt,kindOfTest:le,endsWith:ha,toArray:ga,forEachEntry:ba,matchAll:Ta,isHTMLForm:wa,hasOwnProperty:Bi,hasOwnProp:Bi,reduceDescriptors:Qi,freezeMethods:Sa,toObjectSet:_a,toCamelCase:Ea,noop:Ca,toFiniteNumber:Ra,findKey:Hi,global:Re,isContextDefined:Gi,isSpecCompliantForm:xa,toJSONObject:va,isAsyncFn:La,isThenable:Da,setImmediate:$i,asap:Ia,isIterable:Oa};function ze(t,e,r,i,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),i&&(this.request=i),o&&(this.response=o,this.status=o.status?o.status:null)}a.inherits(ze,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:a.toJSONObject(this.config),code:this.code,status:this.status}}});var Zi=ze.prototype,Ji={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Ji[t]={value:t}});Object.defineProperties(ze,Ji);Object.defineProperty(Zi,"isAxiosError",{value:!0});ze.from=(t,e,r,i,o,n)=>{let s=Object.create(Zi);a.toFlatObject(t,s,function(c){return c!==Error.prototype},m=>m!=="isAxiosError");let l=t&&t.message?t.message:"Error",u=e==null&&t?t.code:e;return ze.call(s,l,u,r,i,o),t&&s.cause==null&&Object.defineProperty(s,"cause",{value:t,configurable:!0}),s.name=t&&t.name||"Error",n&&Object.assign(s,n),s};var g=ze;import Pa from"form-data";var zt=Pa;function Ar(t){return a.isPlainObject(t)||a.isArray(t)}function Yi(t){return a.endsWith(t,"[]")?t.slice(0,-2):t}function Ki(t,e,r){return t?t.concat(e).map(function(o,n){return o=Yi(o),!r&&n?"["+o+"]":o}).join(r?".":""):e}function Na(t){return a.isArray(t)&&!t.some(Ar)}var Fa=a.toFlatObject(a,{},null,function(e){return/^is[A-Z]/.test(e)});function ka(t,e,r){if(!a.isObject(t))throw new TypeError("target must be an object");e=e||new(zt||FormData),r=a.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,T){return!a.isUndefined(T[y])});let i=r.metaTokens,o=r.visitor||c,n=r.dots,s=r.indexes,u=(r.Blob||typeof Blob<"u"&&Blob)&&a.isSpecCompliantForm(e);if(!a.isFunction(o))throw new TypeError("visitor must be a function");function m(f){if(f===null)return"";if(a.isDate(f))return f.toISOString();if(a.isBoolean(f))return f.toString();if(!u&&a.isBlob(f))throw new g("Blob is not supported. Use a Buffer instead.");return a.isArrayBuffer(f)||a.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function c(f,y,T){let C=f;if(f&&!T&&typeof f=="object"){if(a.endsWith(y,"{}"))y=i?y:y.slice(0,-2),f=JSON.stringify(f);else if(a.isArray(f)&&Na(f)||(a.isFileList(f)||a.endsWith(y,"[]"))&&(C=a.toArray(f)))return y=Yi(y),C.forEach(function(A,x){!(a.isUndefined(A)||A===null)&&e.append(s===!0?Ki([y],x,n):s===null?y:y+"[]",m(A))}),!1}return Ar(f)?!0:(e.append(Ki(T,y,n),m(f)),!1)}let h=[],b=Object.assign(Fa,{defaultVisitor:c,convertValue:m,isVisitable:Ar});function w(f,y){if(!a.isUndefined(f)){if(h.indexOf(f)!==-1)throw Error("Circular reference detected in "+y.join("."));h.push(f),a.forEach(f,function(C,N){(!(a.isUndefined(C)||C===null)&&o.call(e,C,a.isString(N)?N.trim():N,y,b))===!0&&w(C,y?y.concat(N):[N])}),h.pop()}}if(!a.isObject(t))throw new TypeError("data must be an object");return w(t),e}var we=ka;function Xi(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(i){return e[i]})}function eo(t,e){this._pairs=[],t&&we(t,this,e)}var to=eo.prototype;to.append=function(e,r){this._pairs.push([e,r])};to.toString=function(e){let r=e?function(i){return e.call(this,i,Xi)}:Xi;return this._pairs.map(function(o){return r(o[0])+"="+r(o[1])},"").join("&")};var ro=eo;function Ma(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function xe(t,e,r){if(!e)return t;let i=r&&r.encode||Ma;a.isFunction(r)&&(r={serialize:r});let o=r&&r.serialize,n;if(o?n=o(e,r):n=a.isURLSearchParams(e)?e.toString():new ro(e,r).toString(i),n){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t}var Sr=class{constructor(){this.handlers=[]}use(e,r,i){return this.handlers.push({fulfilled:e,rejected:r,synchronous:i?i.synchronous:!1,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){a.forEach(this.handlers,function(i){i!==null&&e(i)})}},_r=Sr;var We={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};import Ua from"crypto";import qa from"url";var io=qa.URLSearchParams;var Cr="abcdefghijklmnopqrstuvwxyz",oo="0123456789",so={DIGIT:oo,ALPHA:Cr,ALPHA_DIGIT:Cr+Cr.toUpperCase()+oo},ja=(t=16,e=so.ALPHA_DIGIT)=>{let r="",{length:i}=e,o=new Uint32Array(t);Ua.randomFillSync(o);for(let n=0;n<t;n++)r+=e[o[n]%i];return r},no={isNode:!0,classes:{URLSearchParams:io,FormData:zt,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:so,generateString:ja,protocols:["http","https","file","data"]};var vr={};an(vr,{hasBrowserEnv:()=>xr,hasStandardBrowserEnv:()=>Ba,hasStandardBrowserWebWorkerEnv:()=>Va,navigator:()=>Rr,origin:()=>za});var xr=typeof window<"u"&&typeof document<"u",Rr=typeof navigator=="object"&&navigator||void 0,Ba=xr&&(!Rr||["ReactNative","NativeScript","NS"].indexOf(Rr.product)<0),Va=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",za=xr&&window.location.href||"http://localhost";var I={...vr,...no};function Lr(t,e){return we(t,new I.classes.URLSearchParams,{visitor:function(r,i,o,n){return I.isNode&&a.isBuffer(r)?(this.append(i,r.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...e})}function Wa(t){return a.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Ha(t){let e={},r=Object.keys(t),i,o=r.length,n;for(i=0;i<o;i++)n=r[i],e[n]=t[n];return e}function Ga(t){function e(r,i,o,n){let s=r[n++];if(s==="__proto__")return!0;let l=Number.isFinite(+s),u=n>=r.length;return s=!s&&a.isArray(o)?o.length:s,u?(a.hasOwnProp(o,s)?o[s]=[o[s],i]:o[s]=i,!l):((!o[s]||!a.isObject(o[s]))&&(o[s]=[]),e(r,i,o[s],n)&&a.isArray(o[s])&&(o[s]=Ha(o[s])),!l)}if(a.isFormData(t)&&a.isFunction(t.entries)){let r={};return a.forEachEntry(t,(i,o)=>{e(Wa(i),o,r,0)}),r}return null}var Wt=Ga;function Qa(t,e,r){if(a.isString(t))try{return(e||JSON.parse)(t),a.trim(t)}catch(i){if(i.name!=="SyntaxError")throw i}return(r||JSON.stringify)(t)}var Dr={transitional:We,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){let i=r.getContentType()||"",o=i.indexOf("application/json")>-1,n=a.isObject(e);if(n&&a.isHTMLForm(e)&&(e=new FormData(e)),a.isFormData(e))return o?JSON.stringify(Wt(e)):e;if(a.isArrayBuffer(e)||a.isBuffer(e)||a.isStream(e)||a.isFile(e)||a.isBlob(e)||a.isReadableStream(e))return e;if(a.isArrayBufferView(e))return e.buffer;if(a.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(n){if(i.indexOf("application/x-www-form-urlencoded")>-1)return Lr(e,this.formSerializer).toString();if((l=a.isFileList(e))||i.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return we(l?{"files[]":e}:e,u&&new u,this.formSerializer)}}return n||o?(r.setContentType("application/json",!1),Qa(e)):e}],transformResponse:[function(e){let r=this.transitional||Dr.transitional,i=r&&r.forcedJSONParsing,o=this.responseType==="json";if(a.isResponse(e)||a.isReadableStream(e))return e;if(e&&a.isString(e)&&(i&&!this.responseType||o)){let s=!(r&&r.silentJSONParsing)&&o;try{return JSON.parse(e,this.parseReviver)}catch(l){if(s)throw l.name==="SyntaxError"?g.from(l,g.ERR_BAD_RESPONSE,this,null,this.response):l}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:I.classes.FormData,Blob:I.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};a.forEach(["delete","get","head","post","put","patch"],t=>{Dr.headers[t]={}});var He=Dr;var $a=a.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),ao=t=>{let e={},r,i,o;return t&&t.split(`
|
|
6
|
-
`).forEach(function(s){
|
|
7
|
-
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let
|
|
8
|
-
`,sl=bt.encode(De),nl=2,qr=class{constructor(e,r){let{escapeName:i}=this.constructor,o=a.isString(r),n=`Content-Disposition: form-data; name="${i(e)}"${!o&&r.name?`; filename="${i(r.name)}"`:""}${De}`;o?r=bt.encode(String(r).replace(/\r?\n|\r\n?/g,De)):n+=`Content-Type: ${r.type||"application/octet-stream"}${De}`,this.headers=bt.encode(n+De),this.contentLength=o?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+nl,this.name=e,this.value=r}async*encode(){yield this.headers;let{value:e}=this;a.isTypedArray(e)?yield e:yield*Gt(e),yield sl}static escapeName(e){return String(e).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},al=(t,e,r)=>{let{tag:i="form-data-boundary",size:o=25,boundary:n=i+"-"+I.generateString(o,ol)}=r||{};if(!a.isFormData(t))throw TypeError("FormData instance required");if(n.length<1||n.length>70)throw Error("boundary must be 10-70 characters long");let s=bt.encode("--"+n+De),l=bt.encode("--"+n+"--"+De),u=l.byteLength,m=Array.from(t.entries()).map(([h,b])=>{let w=new qr(h,b);return u+=w.size,w});u+=s.byteLength*m.length,u=a.toFiniteNumber(u);let c={"Content-Type":`multipart/form-data; boundary=${n}`};return Number.isFinite(u)&&(c["Content-Length"]=u),e&&e(c),il.from(async function*(){for(let h of m)yield s,yield*h.encode();yield l}())},po=al;import ll from"stream";var Ur=class extends ll.Transform{__transform(e,r,i){this.push(e),i()}_transform(e,r,i){if(e.length!==0&&(this._transform=this.__transform,e[0]!==120)){let o=Buffer.alloc(2);o[0]=120,o[1]=156,this.push(o,r)}this.__transform(e,r,i)}},mo=Ur;var cl=(t,e)=>a.isAsyncFn(t)?function(...r){let i=r.pop();t.apply(this,r).then(o=>{try{e?i(null,...e(o)):i(null,o)}catch(n){i(n)}},i)}:t,fo=cl;function ul(t,e){t=t||10;let r=new Array(t),i=new Array(t),o=0,n=0,s;return e=e!==void 0?e:1e3,function(u){let m=Date.now(),c=i[n];s||(s=m),r[o]=u,i[o]=m;let h=n,b=0;for(;h!==o;)b+=r[h++],h=h%t;if(o=(o+1)%t,o===n&&(n=(n+1)%t),m-s<e)return;let w=c&&m-c;return w?Math.round(b*1e3/w):void 0}}var ho=ul;function dl(t,e){let r=0,i=1e3/e,o,n,s=(m,c=Date.now())=>{r=c,o=null,n&&(clearTimeout(n),n=null),t(...m)};return[(...m)=>{let c=Date.now(),h=c-r;h>=i?s(m,c):(o=m,n||(n=setTimeout(()=>{n=null,s(o)},i-h)))},()=>o&&s(o)]}var go=dl;var ye=(t,e,r=3)=>{let i=0,o=ho(50,250);return go(n=>{let s=n.loaded,l=n.lengthComputable?n.total:void 0,u=s-i,m=o(u),c=s<=l;i=s;let h={loaded:s,total:l,progress:l?s/l:void 0,bytes:u,rate:m||void 0,estimated:m&&l&&c?(l-s)/m:void 0,event:n,lengthComputable:l!=null,[e?"download":"upload"]:!0};t(h)},r)},Qe=(t,e)=>{let r=t!=null;return[i=>e[0]({lengthComputable:r,total:t,loaded:i}),e[1]]},$e=t=>(...e)=>a.asap(()=>t(...e));function jr(t){if(!t||typeof t!="string"||!t.startsWith("data:"))return 0;let e=t.indexOf(",");if(e<0)return 0;let r=t.slice(5,e),i=t.slice(e+1);if(/;base64/i.test(r)){let n=i.length,s=i.length;for(let b=0;b<s;b++)if(i.charCodeAt(b)===37&&b+2<s){let w=i.charCodeAt(b+1),f=i.charCodeAt(b+2);(w>=48&&w<=57||w>=65&&w<=70||w>=97&&w<=102)&&(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102)&&(n-=2,b+=2)}let l=0,u=s-1,m=b=>b>=2&&i.charCodeAt(b-2)===37&&i.charCodeAt(b-1)===51&&(i.charCodeAt(b)===68||i.charCodeAt(b)===100);u>=0&&(i.charCodeAt(u)===61?(l++,u--):m(u)&&(l++,u-=3)),l===1&&u>=0&&(i.charCodeAt(u)===61||m(u))&&l++;let h=Math.floor(n/4)*3-(l||0);return h>0?h:0}return Buffer.byteLength(i,"utf8")}var yo={flush:Ee.constants.Z_SYNC_FLUSH,finishFlush:Ee.constants.Z_SYNC_FLUSH},bl={flush:Ee.constants.BROTLI_OPERATION_FLUSH,finishFlush:Ee.constants.BROTLI_OPERATION_FLUSH},bo=a.isFunction(Ee.createBrotliDecompress),{http:Tl,https:wl}=gl,El=/https:?/,To=I.protocols.map(t=>t+":"),wo=(t,[e,r])=>(t.on("end",r).on("error",r),e);function Al(t,e){t.beforeRedirects.proxy&&t.beforeRedirects.proxy(t),t.beforeRedirects.config&&t.beforeRedirects.config(t,e)}function Ao(t,e,r){let i=e;if(!i&&i!==!1){let o=pl.getProxyForUrl(r);o&&(i=new URL(o))}if(i){if(i.username&&(i.auth=(i.username||"")+":"+(i.password||"")),i.auth){(i.auth.username||i.auth.password)&&(i.auth=(i.auth.username||"")+":"+(i.auth.password||""));let n=Buffer.from(i.auth,"utf8").toString("base64");t.headers["Proxy-Authorization"]="Basic "+n}t.headers.host=t.hostname+(t.port?":"+t.port:"");let o=i.hostname||i.host;t.hostname=o,t.host=o,t.port=i.port,t.path=r,i.protocol&&(t.protocol=i.protocol.includes(":")?i.protocol:`${i.protocol}:`)}t.beforeRedirects.proxy=function(n){Ao(n,e,n.href)}}var Sl=typeof process<"u"&&a.kindOf(process)==="process",_l=t=>new Promise((e,r)=>{let i,o,n=(u,m)=>{o||(o=!0,i&&i(u,m))},s=u=>{n(u),e(u)},l=u=>{n(u,!0),r(u)};t(s,l,u=>i=u).catch(l)}),Cl=({address:t,family:e})=>{if(!a.isString(t))throw TypeError("address must be a string");return{address:t,family:e||(t.indexOf(".")<0?6:4)}},Eo=(t,e)=>Cl(a.isObject(t)?t:{address:t,family:e}),So=Sl&&function(e){return _l(async function(i,o,n){let{data:s,lookup:l,family:u}=e,{responseType:m,responseEncoding:c}=e,h=e.method.toUpperCase(),b,w=!1,f;if(l){let E=fo(l,S=>a.isArray(S)?S:[S]);l=(S,z,Q)=>{E(S,z,(F,re,be)=>{if(F)return Q(F);let ee=a.isArray(re)?re.map(ie=>Eo(ie)):[Eo(re,be)];z.all?Q(F,ee):Q(F,ee[0].address,ee[0].family)})}}let y=new yl,T=()=>{e.cancelToken&&e.cancelToken.unsubscribe(C),e.signal&&e.signal.removeEventListener("abort",C),y.removeAllListeners()};n((E,S)=>{b=!0,S&&(w=!0,T())});function C(E){y.emit("abort",!E||E.type?new te(null,e,f):E)}y.once("abort",o),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(C),e.signal&&(e.signal.aborted?C():e.signal.addEventListener("abort",C)));let N=ve(e.baseURL,e.url,e.allowAbsoluteUrls),A=new URL(N,I.hasBrowserEnv?I.origin:void 0),x=A.protocol||To[0];if(x==="data:"){if(e.maxContentLength>-1){let S=String(e.url||N||"");if(jr(S)>e.maxContentLength)return o(new g("maxContentLength size of "+e.maxContentLength+" exceeded",g.ERR_BAD_RESPONSE,e))}let E;if(h!=="GET")return pe(i,o,{status:405,statusText:"method not allowed",headers:{},config:e});try{E=Nr(e.url,m==="blob",{Blob:e.env&&e.env.Blob})}catch(S){throw g.from(S,g.ERR_BAD_REQUEST,e)}return m==="text"?(E=E.toString(c),(!c||c==="utf8")&&(E=a.stripBOM(E))):m==="stream"&&(E=Ze.Readable.from(E)),pe(i,o,{data:E,status:200,statusText:"OK",headers:new M,config:e})}if(To.indexOf(x)===-1)return o(new g("Unsupported protocol "+x,g.ERR_BAD_REQUEST,e));let v=M.from(e.headers).normalize();v.set("User-Agent","axios/"+Le,!1);let{onUploadProgress:q,onDownloadProgress:U}=e,ue=e.maxRate,ne,fe;if(a.isSpecCompliantForm(s)){let E=v.getContentType(/boundary=([-_\w\d]{10,70})/i);s=po(s,S=>{v.set(S)},{tag:`axios-${Le}-boundary`,boundary:E&&E[1]||void 0})}else if(a.isFormData(s)&&a.isFunction(s.getHeaders)){if(v.set(s.getHeaders()),!v.hasContentLength())try{let E=await hl.promisify(s.getLength).call(s);Number.isFinite(E)&&E>=0&&v.setContentLength(E)}catch{}}else if(a.isBlob(s)||a.isFile(s))s.size&&v.setContentType(s.type||"application/octet-stream"),v.setContentLength(s.size||0),s=Ze.Readable.from(Gt(s));else if(s&&!a.isStream(s)){if(!Buffer.isBuffer(s))if(a.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(a.isString(s))s=Buffer.from(s,"utf-8");else return o(new g("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",g.ERR_BAD_REQUEST,e));if(v.setContentLength(s.length,!1),e.maxBodyLength>-1&&s.length>e.maxBodyLength)return o(new g("Request body larger than maxBodyLength limit",g.ERR_BAD_REQUEST,e))}let he=a.toFiniteNumber(v.getContentLength());a.isArray(ue)?(ne=ue[0],fe=ue[1]):ne=fe=ue,s&&(q||ne)&&(a.isStream(s)||(s=Ze.Readable.from(s,{objectMode:!1})),s=Ze.pipeline([s,new Mr({maxRate:a.toFiniteNumber(ne)})],a.noop),q&&s.on("progress",wo(s,Qe(he,ye($e(q),!1,3)))));let Y;if(e.auth){let E=e.auth.username||"",S=e.auth.password||"";Y=E+":"+S}if(!Y&&A.username){let E=A.username,S=A.password;Y=E+":"+S}Y&&v.delete("authorization");let X;try{X=xe(A.pathname+A.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(E){let S=new Error(E.message);return S.config=e,S.url=e.url,S.exists=!0,o(S)}v.set("Accept-Encoding","gzip, compress, deflate"+(bo?", br":""),!1);let j={path:X,method:h,headers:v.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:Y,protocol:x,family:u,beforeRedirect:Al,beforeRedirects:{}};!a.isUndefined(l)&&(j.lookup=l),e.socketPath?j.socketPath=e.socketPath:(j.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,j.port=A.port,Ao(j,e.proxy,x+"//"+A.hostname+(A.port?":"+A.port:"")+j.path));let B,G=El.test(j.protocol);if(j.agent=G?e.httpsAgent:e.httpAgent,e.transport?B=e.transport:e.maxRedirects===0?B=G?fl:ml:(e.maxRedirects&&(j.maxRedirects=e.maxRedirects),e.beforeRedirect&&(j.beforeRedirects.config=e.beforeRedirect),B=G?wl:Tl),e.maxBodyLength>-1?j.maxBodyLength=e.maxBodyLength:j.maxBodyLength=1/0,e.insecureHTTPParser&&(j.insecureHTTPParser=e.insecureHTTPParser),f=B.request(j,function(S){if(f.destroyed)return;let z=[S],Q=+S.headers["content-length"];if(U||fe){let ie=new Mr({maxRate:a.toFiniteNumber(fe)});U&&ie.on("progress",wo(ie,Qe(Q,ye($e(U),!0,3)))),z.push(ie)}let F=S,re=S.req||f;if(e.decompress!==!1&&S.headers["content-encoding"])switch((h==="HEAD"||S.statusCode===204)&&delete S.headers["content-encoding"],(S.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":z.push(Ee.createUnzip(yo)),delete S.headers["content-encoding"];break;case"deflate":z.push(new mo),z.push(Ee.createUnzip(yo)),delete S.headers["content-encoding"];break;case"br":bo&&(z.push(Ee.createBrotliDecompress(bl)),delete S.headers["content-encoding"])}F=z.length>1?Ze.pipeline(z,a.noop):z[0];let be=Ze.finished(F,()=>{be(),T()}),ee={status:S.statusCode,statusText:S.statusMessage,headers:new M(S.headers),config:e,request:re};if(m==="stream")ee.data=F,pe(i,o,ee);else{let ie=[],gi=0;F.on("data",function($){ie.push($),gi+=$.length,e.maxContentLength>-1&&gi>e.maxContentLength&&(w=!0,F.destroy(),o(new g("maxContentLength size of "+e.maxContentLength+" exceeded",g.ERR_BAD_RESPONSE,e,re)))}),F.on("aborted",function(){if(w)return;let $=new g("stream has been aborted",g.ERR_BAD_RESPONSE,e,re);F.destroy($),o($)}),F.on("error",function($){f.destroyed||o(g.from($,null,e,re))}),F.on("end",function(){try{let $=ie.length===1?ie[0]:Buffer.concat(ie);m!=="arraybuffer"&&($=$.toString(c),(!c||c==="utf8")&&($=a.stripBOM($))),ee.data=$}catch($){return o(g.from($,null,e,ee.request,ee))}pe(i,o,ee)})}y.once("abort",ie=>{F.destroyed||(F.emit("error",ie),F.destroy())})}),y.once("abort",E=>{o(E),f.destroy(E)}),f.on("error",function(S){o(g.from(S,null,e,f))}),f.on("socket",function(S){S.setKeepAlive(!0,1e3*60)}),e.timeout){let E=parseInt(e.timeout,10);if(Number.isNaN(E)){o(new g("error trying to parse `config.timeout` to int",g.ERR_BAD_OPTION_VALUE,e,f));return}f.setTimeout(E,function(){if(b)return;let z=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",Q=e.transitional||We;e.timeoutErrorMessage&&(z=e.timeoutErrorMessage),o(new g(z,Q.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,e,f)),C()})}if(a.isStream(s)){let E=!1,S=!1;s.on("end",()=>{E=!0}),s.once("error",z=>{S=!0,f.destroy(z)}),s.on("close",()=>{!E&&!S&&C(new te("Request stream has been aborted",e,f))}),s.pipe(f)}else f.end(s)})};var _o=I.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,I.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(I.origin),I.navigator&&/(msie|trident)/i.test(I.navigator.userAgent)):()=>!0;var Co=I.hasStandardBrowserEnv?{write(t,e,r,i,o,n){let s=[t+"="+encodeURIComponent(e)];a.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),a.isString(i)&&s.push("path="+i),a.isString(o)&&s.push("domain="+o),n===!0&&s.push("secure"),document.cookie=s.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var Ro=t=>t instanceof M?{...t}:t;function ce(t,e){e=e||{};let r={};function i(m,c,h,b){return a.isPlainObject(m)&&a.isPlainObject(c)?a.merge.call({caseless:b},m,c):a.isPlainObject(c)?a.merge({},c):a.isArray(c)?c.slice():c}function o(m,c,h,b){if(a.isUndefined(c)){if(!a.isUndefined(m))return i(void 0,m,h,b)}else return i(m,c,h,b)}function n(m,c){if(!a.isUndefined(c))return i(void 0,c)}function s(m,c){if(a.isUndefined(c)){if(!a.isUndefined(m))return i(void 0,m)}else return i(void 0,c)}function l(m,c,h){if(h in e)return i(m,c);if(h in t)return i(void 0,m)}let u={url:n,method:n,data:n,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(m,c,h)=>o(Ro(m),Ro(c),h,!0)};return a.forEach(Object.keys({...t,...e}),function(c){let h=u[c]||o,b=h(t[c],e[c],c);a.isUndefined(b)&&h!==l||(r[c]=b)}),r}var Qt=t=>{let e=ce({},t),{data:r,withXSRFToken:i,xsrfHeaderName:o,xsrfCookieName:n,headers:s,auth:l}=e;if(e.headers=s=M.from(s),e.url=xe(ve(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),l&&s.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),a.isFormData(r)){if(I.hasStandardBrowserEnv||I.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(a.isFunction(r.getHeaders)){let u=r.getHeaders(),m=["content-type","content-length"];Object.entries(u).forEach(([c,h])=>{m.includes(c.toLowerCase())&&s.set(c,h)})}}if(I.hasStandardBrowserEnv&&(i&&a.isFunction(i)&&(i=i(e)),i||i!==!1&&_o(e.url))){let u=o&&n&&Co.read(n);u&&s.set(o,u)}return e};var Rl=typeof XMLHttpRequest<"u",xo=Rl&&function(t){return new Promise(function(r,i){let o=Qt(t),n=o.data,s=M.from(o.headers).normalize(),{responseType:l,onUploadProgress:u,onDownloadProgress:m}=o,c,h,b,w,f;function y(){w&&w(),f&&f(),o.cancelToken&&o.cancelToken.unsubscribe(c),o.signal&&o.signal.removeEventListener("abort",c)}let T=new XMLHttpRequest;T.open(o.method.toUpperCase(),o.url,!0),T.timeout=o.timeout;function C(){if(!T)return;let A=M.from("getAllResponseHeaders"in T&&T.getAllResponseHeaders()),v={data:!l||l==="text"||l==="json"?T.responseText:T.response,status:T.status,statusText:T.statusText,headers:A,config:t,request:T};pe(function(U){r(U),y()},function(U){i(U),y()},v),T=null}"onloadend"in T?T.onloadend=C:T.onreadystatechange=function(){!T||T.readyState!==4||T.status===0&&!(T.responseURL&&T.responseURL.indexOf("file:")===0)||setTimeout(C)},T.onabort=function(){T&&(i(new g("Request aborted",g.ECONNABORTED,t,T)),T=null)},T.onerror=function(x){let v=x&&x.message?x.message:"Network Error",q=new g(v,g.ERR_NETWORK,t,T);q.event=x||null,i(q),T=null},T.ontimeout=function(){let x=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",v=o.transitional||We;o.timeoutErrorMessage&&(x=o.timeoutErrorMessage),i(new g(x,v.clarifyTimeoutError?g.ETIMEDOUT:g.ECONNABORTED,t,T)),T=null},n===void 0&&s.setContentType(null),"setRequestHeader"in T&&a.forEach(s.toJSON(),function(x,v){T.setRequestHeader(v,x)}),a.isUndefined(o.withCredentials)||(T.withCredentials=!!o.withCredentials),l&&l!=="json"&&(T.responseType=o.responseType),m&&([b,f]=ye(m,!0),T.addEventListener("progress",b)),u&&T.upload&&([h,w]=ye(u),T.upload.addEventListener("progress",h),T.upload.addEventListener("loadend",w)),(o.cancelToken||o.signal)&&(c=A=>{T&&(i(!A||A.type?new te(null,t,T):A),T.abort(),T=null)},o.cancelToken&&o.cancelToken.subscribe(c),o.signal&&(o.signal.aborted?c():o.signal.addEventListener("abort",c)));let N=yt(o.url);if(N&&I.protocols.indexOf(N)===-1){i(new g("Unsupported protocol "+N+":",g.ERR_BAD_REQUEST,t));return}T.send(n||null)})};var xl=(t,e)=>{let{length:r}=t=t?t.filter(Boolean):[];if(e||r){let i=new AbortController,o,n=function(m){if(!o){o=!0,l();let c=m instanceof Error?m:this.reason;i.abort(c instanceof g?c:new te(c instanceof Error?c.message:c))}},s=e&&setTimeout(()=>{s=null,n(new g(`timeout ${e} of ms exceeded`,g.ETIMEDOUT))},e),l=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(m=>{m.unsubscribe?m.unsubscribe(n):m.removeEventListener("abort",n)}),t=null)};t.forEach(m=>m.addEventListener("abort",n));let{signal:u}=i;return u.unsubscribe=()=>a.asap(l),u}},vo=xl;var vl=function*(t,e){let r=t.byteLength;if(!e||r<e){yield t;return}let i=0,o;for(;i<r;)o=i+e,yield t.slice(i,o),i=o},Ll=async function*(t,e){for await(let r of Dl(t))yield*vl(r,e)},Dl=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}let e=t.getReader();try{for(;;){let{done:r,value:i}=await e.read();if(r)break;yield i}}finally{await e.cancel()}},Br=(t,e,r,i)=>{let o=Ll(t,e),n=0,s,l=u=>{s||(s=!0,i&&i(u))};return new ReadableStream({async pull(u){try{let{done:m,value:c}=await o.next();if(m){l(),u.close();return}let h=c.byteLength;if(r){let b=n+=h;r(b)}u.enqueue(new Uint8Array(c))}catch(m){throw l(m),m}},cancel(u){return l(u),o.return()}},{highWaterMark:2})};var Lo=64*1024,{isFunction:$t}=a,Po=(({fetch:t,Request:e,Response:r})=>({fetch:t,Request:e,Response:r}))(a.global),{ReadableStream:Do,TextEncoder:Io}=a.global,Oo=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Il=t=>{let{fetch:e,Request:r,Response:i}=Object.assign({},Po,t),o=$t(e),n=$t(r),s=$t(i);if(!o)return!1;let l=o&&$t(Do),u=o&&(typeof Io=="function"?(f=>y=>f.encode(y))(new Io):async f=>new Uint8Array(await new r(f).arrayBuffer())),m=n&&l&&Oo(()=>{let f=!1,y=new r(I.origin,{body:new Do,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!y}),c=s&&l&&Oo(()=>a.isReadableStream(new i("").body)),h={stream:c&&(f=>f.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!h[f]&&(h[f]=(y,T)=>{let C=y&&y[f];if(C)return C.call(y);throw new g(`Response type '${f}' is not supported`,g.ERR_NOT_SUPPORT,T)})});let b=async f=>{if(f==null)return 0;if(a.isBlob(f))return f.size;if(a.isSpecCompliantForm(f))return(await new r(I.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(a.isArrayBufferView(f)||a.isArrayBuffer(f))return f.byteLength;if(a.isURLSearchParams(f)&&(f=f+""),a.isString(f))return(await u(f)).byteLength},w=async(f,y)=>{let T=a.toFiniteNumber(f.getContentLength());return T??b(y)};return async f=>{let{url:y,method:T,data:C,signal:N,cancelToken:A,timeout:x,onDownloadProgress:v,onUploadProgress:q,responseType:U,headers:ue,withCredentials:ne="same-origin",fetchOptions:fe}=Qt(f);U=U?(U+"").toLowerCase():"text";let he=vo([N,A&&A.toAbortSignal()],x),Y=null,X=he&&he.unsubscribe&&(()=>{he.unsubscribe()}),j;try{if(q&&m&&T!=="get"&&T!=="head"&&(j=await w(ue,C))!==0){let Q=new r(y,{method:"POST",body:C,duplex:"half"}),F;if(a.isFormData(C)&&(F=Q.headers.get("content-type"))&&ue.setContentType(F),Q.body){let[re,be]=Qe(j,ye($e(q)));C=Br(Q.body,Lo,re,be)}}a.isString(ne)||(ne=ne?"include":"omit");let B=n&&"credentials"in r.prototype,G={...fe,signal:he,method:T.toUpperCase(),headers:ue.normalize().toJSON(),body:C,duplex:"half",credentials:B?ne:void 0};Y=n&&new r(y,G);let E=await(n?e(Y,fe):e(y,G)),S=c&&(U==="stream"||U==="response");if(c&&(v||S&&X)){let Q={};["status","statusText","headers"].forEach(ee=>{Q[ee]=E[ee]});let F=a.toFiniteNumber(E.headers.get("content-length")),[re,be]=v&&Qe(F,ye($e(v),!0))||[];E=new i(Br(E.body,Lo,re,()=>{be&&be(),X&&X()}),Q)}U=U||"text";let z=await h[a.findKey(h,U)||"text"](E,f);return!S&&X&&X(),await new Promise((Q,F)=>{pe(Q,F,{data:z,headers:M.from(E.headers),status:E.status,statusText:E.statusText,config:f,request:Y})})}catch(B){throw X&&X(),B&&B.name==="TypeError"&&/Load failed|fetch/i.test(B.message)?Object.assign(new g("Network Error",g.ERR_NETWORK,f,Y),{cause:B.cause||B}):g.from(B,B&&B.code,f,Y)}}},Ol=new Map,Vr=t=>{let e=a.merge.call({skipUndefined:!0},Po,t?t.env:null),{fetch:r,Request:i,Response:o}=e,n=[i,o,r],s=n.length,l=s,u,m,c=Ol;for(;l--;)u=n[l],m=c.get(u),m===void 0&&c.set(u,m=l?new Map:Il(e)),c=m;return m},_h=Vr();var zr={http:So,xhr:xo,fetch:{get:Vr}};a.forEach(zr,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var No=t=>`- ${t}`,Nl=t=>a.isFunction(t)||t===null||t===!1,Zt={getAdapter:(t,e)=>{t=a.isArray(t)?t:[t];let{length:r}=t,i,o,n={};for(let s=0;s<r;s++){i=t[s];let l;if(o=i,!Nl(i)&&(o=zr[(l=String(i)).toLowerCase()],o===void 0))throw new g(`Unknown adapter '${l}'`);if(o&&(a.isFunction(o)||(o=o.get(e))))break;n[l||"#"+s]=o}if(!o){let s=Object.entries(n).map(([u,m])=>`adapter ${u} `+(m===!1?"is not supported by the environment":"is not available in the build")),l=r?s.length>1?`since :
|
|
9
|
-
`+s.map(
|
|
10
|
-
`):" "+
|
|
11
|
-
`+n):i.stack=n}catch{}}throw i}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=ce(this.defaults,r);let{transitional:i,paramsSerializer:o,headers:n}=r;i!==void 0&&Tt.assertOptions(i,{silentJSONParsing:me.transitional(me.boolean),forcedJSONParsing:me.transitional(me.boolean),clarifyTimeoutError:me.transitional(me.boolean)},!1),o!=null&&(a.isFunction(o)?r.paramsSerializer={serialize:o}:Tt.assertOptions(o,{encode:me.function,serialize:me.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Tt.assertOptions(r,{baseUrl:me.spelling("baseURL"),withXsrfToken:me.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=n&&a.merge(n.common,n[r.method]);n&&a.forEach(["delete","get","head","post","put","patch","common"],f=>{delete n[f]}),r.headers=M.concat(s,n);let l=[],u=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(u=u&&y.synchronous,l.unshift(y.fulfilled,y.rejected))});let m=[];this.interceptors.response.forEach(function(y){m.push(y.fulfilled,y.rejected)});let c,h=0,b;if(!u){let f=[Jt.bind(this),void 0];for(f.unshift(...l),f.push(...m),b=f.length,c=Promise.resolve(r);h<b;)c=c.then(f[h++],f[h++]);return c}b=l.length;let w=r;for(h=0;h<b;){let f=l[h++],y=l[h++];try{w=f(w)}catch(T){y.call(this,T);break}}try{c=Jt.call(this,w)}catch(f){return Promise.reject(f)}for(h=0,b=m.length;h<b;)c=c.then(m[h++],m[h++]);return c}getUri(e){e=ce(this.defaults,e);let r=ve(e.baseURL,e.url,e.allowAbsoluteUrls);return xe(r,e.params,e.paramsSerializer)}};a.forEach(["delete","get","head","options"],function(e){Je.prototype[e]=function(r,i){return this.request(ce(i||{},{method:e,url:r,data:(i||{}).data}))}});a.forEach(["post","put","patch"],function(e){function r(i){return function(n,s,l){return this.request(ce(l||{},{method:e,headers:i?{"Content-Type":"multipart/form-data"}:{},url:n,data:s}))}}Je.prototype[e]=r(),Je.prototype[e+"Form"]=r(!0)});var wt=Je;var Hr=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(n){r=n});let i=this;this.promise.then(o=>{if(!i._listeners)return;let n=i._listeners.length;for(;n-- >0;)i._listeners[n](o);i._listeners=null}),this.promise.then=o=>{let n,s=new Promise(l=>{i.subscribe(l),n=l}).then(o);return s.cancel=function(){i.unsubscribe(n)},s},e(function(n,s,l){i.reason||(i.reason=new te(n,s,l),r(i.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=i=>{e.abort(i)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(o){e=o}),cancel:e}}},ko=Hr;function Gr(t){return function(r){return t.apply(null,r)}}function Qr(t){return a.isObject(t)&&t.isAxiosError===!0}var $r={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries($r).forEach(([t,e])=>{$r[e]=t});var Mo=$r;function qo(t){let e=new wt(t),r=ut(wt.prototype.request,e);return a.extend(r,wt.prototype,e,{allOwnKeys:!0}),a.extend(r,e,null,{allOwnKeys:!0}),r.create=function(o){return qo(ce(t,o))},r}var V=qo(He);V.Axios=wt;V.CanceledError=te;V.CancelToken=ko;V.isCancel=gt;V.VERSION=Le;V.toFormData=we;V.AxiosError=g;V.Cancel=V.CanceledError;V.all=function(e){return Promise.all(e)};V.spread=Gr;V.isAxiosError=Qr;V.mergeConfig=ce;V.AxiosHeaders=M;V.formToJSON=t=>Wt(a.isHTMLForm(t)?new FormData(t):t);V.getAdapter=Zt.getAdapter;V.HttpStatusCode=Mo;V.default=V;var Uo=V;var{Axios:wg,AxiosError:Eg,CanceledError:Ag,isCancel:Sg,CancelToken:_g,VERSION:Cg,all:Rg,Cancel:xg,isAxiosError:Ke,spread:vg,toFormData:Lg,AxiosHeaders:Dg,HttpStatusCode:Ig,formToJSON:Og,getAdapter:Pg,mergeConfig:Ng}=Uo;import{makeApi as Hl,makeEndpoint as Ye}from"@zodios/core";import{z as k}from"zod";import{z as p}from"zod";var kl=p.object({name:p.string(),description:p.string(),id:p.string(),schema_version:p.string(),metric_version:p.coerce.number(),definition_version:p.coerce.number(),last_updated_user:p.object({id:p.string()}).optional()}),Ml=p.object({id:p.string()}),jo=p.object({field:p.string(),operator:p.string(),categorical_values:p.array(p.object({string_value:p.string().optional(),bool_value:p.boolean().optional(),null_value:p.string().optional()}))}),Zr=p.object({measure:p.object({field:p.string(),aggregation:p.string()}),time_dimension:p.object({field:p.string()}),filters:p.array(jo)}),ql=p.object({datasource:Ml,basic_specification:Zr,viz_state_specification:p.object({viz_state_string:p.string()}).optional(),is_running_total:p.boolean()}),Bo=p.object({allowed_dimensions:p.array(p.string()),allowed_granularities:p.array(p.string()),offset_from_today:p.number()}),Vo=p.object({filters:p.array(jo),measurement_period:p.object({granularity:p.string(),range:p.string()}),comparison:p.object({comparison:p.string()})}),zo=p.object({target:p.object({value:p.number()}).optional()}),Yt=p.object({id:p.string(),specification:Vo,definition_id:p.string(),is_default:p.boolean(),schema_version:p.string(),metric_version:p.coerce.number(),goals:zo.optional(),is_followed:p.boolean()}),Wo=p.object({type:p.string(),number_units:p.object({singular_noun:p.string(),plural_noun:p.string()}),sentiment_type:p.string(),row_level_id_field:p.object({identifier_col:p.string()}),row_level_entity_names:p.object({entity_name_singular:p.string().optional(),entity_name_plural:p.string().optional()}),row_level_name_field:p.object({name_col:p.string()}),currency_code:p.string()}),Ho=p.object({settings:p.array(p.object({type:p.string(),disabled:p.boolean()}))}),Ul=p.object({comparisons:p.array(p.object({compare_config:p.object({comparison:p.string()}),index:p.coerce.number()}))}),jl=p.array(p.object({basic_specification:Zr,viz_state_specification:p.object({viz_state_string:p.string()}).optional(),minimum_granularity:p.string()})),Jr=p.object({metadata:kl,specification:ql,extension_options:Bo,metrics:p.array(Yt),total_metrics:p.coerce.number(),representation_options:Wo,insights_options:Ho,comparisons:Ul,datasource_goals:jl}),Go=p.object({id:p.string(),metric_id:p.string()}),Bl=p.enum(["LANGUAGE_UNSPECIFIED","LANGUAGE_DE_DE","LANGUAGE_EN_US","LANGUAGE_EN_GB","LANGUAGE_ES_ES","LANGUAGE_FR_FR","LANGUAGE_FR_CA","LANGUAGE_GA_IE","LANGUAGE_IT_IT","LANGUAGE_JA_JP","LANGUAGE_KO_KR","LANGUAGE_NL_NL","LANGUAGE_PT_BR","LANGUAGE_SV_SE","LANGUAGE_TH_TH","LANGUAGE_ZH_CN","LANGUAGE_ZH_TW"]),Vl=p.enum(["LOCALE_UNSPECIFIED","LOCALE_AR_AE","LOCALE_AR_BH","LOCALE_AR_DZ","LOCALE_AR_EG","LOCALE_AR_IQ","LOCALE_AR_JO","LOCALE_AR_KW","LOCALE_AR_LB","LOCALE_AR_LY","LOCALE_AR_MA","LOCALE_AR_OM","LOCALE_AR_QA","LOCALE_AR_SA","LOCALE_AR_SD","LOCALE_AR_SY","LOCALE_AR_TN","LOCALE_AR_YE","LOCALE_BE_BY","LOCALE_BG_BG","LOCALE_CA_ES","LOCALE_CS_CZ","LOCALE_DA_DK","LOCALE_DE_AT","LOCALE_DE_CH","LOCALE_DE_DE","LOCALE_DE_LU","LOCALE_EL_CY","LOCALE_EL_GR","LOCALE_EN_AU","LOCALE_EN_CA","LOCALE_EN_GB","LOCALE_EN_IE","LOCALE_EN_IN","LOCALE_EN_MT","LOCALE_EN_NZ","LOCALE_EN_PH","LOCALE_EN_SG","LOCALE_EN_US","LOCALE_EN_ZA","LOCALE_ES_AR","LOCALE_ES_BO","LOCALE_ES_CL","LOCALE_ES_CO","LOCALE_ES_CR","LOCALE_ES_DO","LOCALE_ES_EC","LOCALE_ES_ES","LOCALE_ES_GT","LOCALE_ES_HN","LOCALE_ES_MX","LOCALE_ES_NI","LOCALE_ES_PA","LOCALE_ES_PE","LOCALE_ES_PR","LOCALE_ES_PY","LOCALE_ES_SV","LOCALE_ES_US","LOCALE_ES_UY","LOCALE_ES_VE","LOCALE_ET_EE","LOCALE_FI_FI","LOCALE_FR_BE","LOCALE_FR_CA","LOCALE_FR_CH","LOCALE_FR_FR","LOCALE_FR_LU","LOCALE_GA_IE","LOCALE_HE_IL","LOCALE_HI_IN","LOCALE_HR_HR","LOCALE_HU_HU","LOCALE_ID_ID","LOCALE_IN_ID","LOCALE_IS_IS","LOCALE_IT_CH","LOCALE_IT_IT","LOCALE_IW_IL","LOCALE_JA_JP","LOCALE_KO_KR","LOCALE_LT_LT","LOCALE_LV_LV","LOCALE_MK_MK","LOCALE_MS_MY","LOCALE_MT_MT","LOCALE_NL_BE","LOCALE_NL_NL","LOCALE_NB_NO","LOCALE_NO_NO","LOCALE_PL_PL","LOCALE_PT_BR","LOCALE_PT_PT","LOCALE_RO_RO","LOCALE_RU_RU","LOCALE_SK_SK","LOCALE_SL_SI","LOCALE_SQ_AL","LOCALE_SR_BA","LOCALE_SR_ME","LOCALE_SR_RS","LOCALE_SV_SE","LOCALE_TH_TH","LOCALE_TR_TR","LOCALE_UK_UA","LOCALE_VI_VN","LOCALE_ZH_CN","LOCALE_ZH_HK","LOCALE_ZH_SG","LOCALE_ZH_TW"]),zl=p.enum(["OUTPUT_FORMAT_UNSPECIFIED","OUTPUT_FORMAT_HTML","OUTPUT_FORMAT_TEXT"]),Xt=p.object({bundle_request:p.object({version:p.number(),options:p.object({output_format:zl,time_zone:p.string(),language:Bl,locale:Vl}),input:p.object({metadata:p.object({name:p.string().nonempty(),metric_id:p.string().nonempty(),definition_id:p.string().nonempty()}),metric:p.object({definition:p.object({datasource:p.object({id:p.string()}),basic_specification:Zr,is_running_total:p.boolean()}),metric_specification:Vo,extension_options:Bo,representation_options:Wo,insights_options:Ho,goals:zo.optional()})})})}),Wl=p.object({type:p.string(),insights:p.array(p.object({result:p.object({type:p.string(),version:p.number(),content:p.string().optional(),markup:p.string().optional(),viz:p.any().optional(),facts:p.any().optional(),characterization:p.string().optional(),question:p.string(),score:p.number()}),insight_type:p.string()})),summaries:p.array(p.object({result:p.object({id:p.string(),markup:p.string().optional(),viz:p.any().optional(),generation_id:p.string(),timestamp:p.string().optional(),last_attempted_timestamp:p.string().optional()})}))}),Qo=p.object({bundle_response:p.object({result:p.object({insight_groups:p.array(Wl),has_errors:p.boolean(),characterization:p.string()})})}),er=["ban","springboard","basic","detail"],Ie=["DEFINITION_VIEW_BASIC","DEFINITION_VIEW_FULL","DEFINITION_VIEW_DEFAULT"];var Gl=Ye({method:"get",path:"/pulse/definitions",alias:"listAllPulseMetricDefinitions",description:"Returns a list of all published Pulse Metric Definitions on the specified site.",parameters:[{name:"view",type:"Query",schema:k.optional(k.enum(Ie)),description:`The range of metrics to return for a definition. The default is 'DEFINITION_VIEW_BASIC' if not specified.
|
|
4
|
+
`,process.stderr.write(t))},pi=({requestId:t,toolName:e,args:r,username:o})=>({type:"tool",requestId:t,...o?{username:o}:{},tool:{name:e,...r!==void 0?{args:r}:{}}});function ve(t){return async(e,r,{logger:o,requestId:i}={logger:e.name})=>{if(ci?.log({message:r,level:t,logger:o}),!!Oe(t))return e.server.notification({method:"notifications/message",params:{level:t,logger:o,data:JSON.stringify({timestamp:new Date().toISOString(),currentLogLevel:Et,message:r},null,2)}},{relatedRequestId:i})}}import{appendFile as Ba}from"node:fs/promises";import{existsSync as za,mkdirSync as Wa}from"fs";import{join as Ha}from"path";function W(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??"undefined"}catch{return`${t}`}}var tr=class{_logDirectory;_fileMutexes=new Map;constructor({logDirectory:e}){this._logDirectory=e,za(this._logDirectory)||Wa(this._logDirectory,{recursive:!0})}async log(e){let r=new Date().toISOString(),o=`${new Date(new Date().setMinutes(0,0,0)).toISOString().replace(/[:.]/g,"-")}.log`,i=Ha(this._logDirectory,o),n=i,a=(this._fileMutexes.get(n)??Promise.resolve()).then(async()=>{try{await Ba(i,JSON.stringify({timestamp:r,...e})+`
|
|
5
|
+
`)}catch(c){Me(`Failed to write to log file ${i}: ${W(c)}`)}});this._fileMutexes.set(n,a),a.finally(()=>{this._fileMutexes.get(n)===a&&this._fileMutexes.delete(n)}),await a}};import{McpServer as kp}from"@modelcontextprotocol/sdk/server/mcp.js";import{SetLevelRequestSchema as Pp}from"@modelcontextprotocol/sdk/types.js";var mi={name:"@tableau/mcp-server",description:"An MCP server for Tableau, providing a suite of tools that will make it easier for developers to build AI applications that integrate with Tableau.",version:"1.12.4",repository:{type:"git",url:"git+https://github.com/tableau/tableau-mcp.git"},homepage:"https://github.com/tableau/tableau-mcp",bugs:"https://github.com/tableau/tableau-mcp/issues",author:"Tableau",type:"module",license:"Apache-2.0",keywords:["tableau","mcp"],bin:{"tableau-mcp-server":"./build/index.js"},scripts:{":build":"npx rimraf ./build && esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --minify --outdir=build --sourcemap",":build:dev":"npx rimraf ./build && esbuild src/index.ts --bundle --packages=external --platform=node --format=esm --outdir=build --sourcemap",build:"run-s :build exec-perms","build:dev":"run-s :build:dev exec-perms","build:watch":"npm run :build:dev -- --watch","build:docker":"docker build -t tableau-mcp .",":build:mcpb":"npx -y @anthropic-ai/mcpb pack . tableau-mcp.mcpb","build:mcpb":"run-s build:manifest:script build:manifest :build:mcpb","build:manifest":"node build/scripts/createClaudeMcpBundleManifest.mjs","build:manifest:script":"esbuild src/scripts/createClaudeMcpBundleManifest.ts --bundle --platform=node --format=esm --outdir=build/scripts --sourcemap=inline --out-extension:.js=.mjs","start:http":"node build/index.js","start:http:docker":"docker run -p 3927:3927 -i --rm --env-file env.list tableau-mcp",lint:"npm exec eslint",inspect:"npx @modelcontextprotocol/inspector --config config.json --server tableau",":inspect:http":"npx @modelcontextprotocol/inspector --config config.http.json --server tableau","inspect:http":"run-p start:http :inspect:http","inspect:docker":"npx @modelcontextprotocol/inspector --config config.docker.json --server tableau","inspect:docker:http":"run-p start:http:docker :inspect:http","build:inspect":"run-s build inspect","build:inspect:docker":"run-s build:docker inspect:docker","build:inspect:docker:http":"run-s build:docker inspect:docker:http","exec-perms":"shx chmod +x build/*.js",test:"vitest --config ./vitest.config.ts","test:e2e":"vitest --config ./vitest.config.e2e.ts","test:eval":"vitest --config ./vitest.config.eval.ts","test:oauth":"vitest --config ./vitest.config.oauth.ts",coverage:"vitest run --config ./vitest.config.ts --coverage","version:major":"npm version major --no-git-tag-version","version:minor":"npm version minor --no-git-tag-version","version:patch":"npm version patch --no-git-tag-version"},dependencies:{"@modelcontextprotocol/sdk":"^1.12.1","@zodios/core":"^10.9.6",cors:"^2.8.5",dotenv:"^16.5.0",express:"^5.1.0","fast-levenshtein":"^3.0.0",jose:"^6.0.12","ts-results-es":"^5.0.1",zod:"^3.24.3","zod-validation-error":"^4.0.1"},devDependencies:{"@anthropic-ai/mcpb":"^1.0.0","@eslint/eslintrc":"^3.3.1","@eslint/js":"^9.25.1","@modelcontextprotocol/inspector":"^0.16.6","@openai/agents":"^0.1.9","@types/cors":"^2.8.19","@types/eslint__js":"^8.42.3","@types/express":"^5.0.3","@types/fast-levenshtein":"^0.0.1","@types/node":"^22.15.3","@types/supertest":"^6.0.3","@typescript-eslint/eslint-plugin":"^8.31.1","@typescript-eslint/parser":"^8.31.1","@vitest/coverage-v8":"^3.1.3",esbuild:"^0.25.5",eslint:"^9.25.1","eslint-config-prettier":"^10.1.2","eslint-plugin-prettier":"^5.2.6","eslint-plugin-simple-import-sort":"^12.1.1","npm-run-all":"^4.1.5",openai:"^5.23.2",prettier:"^3.5.3",rimraf:"^6.0.1",shx:"^0.4.0",supertest:"^7.1.4",typescript:"^5.8.3","typescript-eslint":"^8.31.1",vitest:"^3.1.3"},engines:{node:">=22.7.5"}};import{Ok as xd}from"ts-results-es";import{z as hn}from"zod";import{Err as fi,Ok as $a}from"ts-results-es";var hi=t=>{let e=bi(t);if(e.isErr())return t;let r=e.value;return Oe("debug")?(r.data?.credentials&&(r.data.credentials="<redacted>"),Array.isArray(r?.data?.datasource?.connections)&&r.data.datasource.connections.forEach(i=>{i.connectionUsername="<redacted>",i.connectionPassword="<redacted>"}),r.headers?.["X-Tableau-Auth"]&&(r.headers["X-Tableau-Auth"]="<redacted>"),r.params?.user_id&&(r.params.user_id="<redacted>")):(delete r.data,delete r.headers,delete r.params),r},gi=t=>{let e=bi(t);if(e.isErr())return t;let r=e.value;return Oe("debug")?r.data?.credentials&&(r.data.credentials="<redacted>"):(delete r.data,delete r.headers),r};function bi(t){try{return $a(structuredClone(t))}catch(e){if(e instanceof Error)return fi(e);let r=W(e);return Me(`Could not clone object, notification may not be sanitized! Error: ${r}`),fi(new Error(r))}}function rr(t){return{method:t.method??"UNKNOWN METHOD",url:t.url??"UNKNOWN URL",headers:t.headers,data:t.data,params:t.params}}function or(t){return{url:t.config.url??"UNKNOWN URL",status:t.status,headers:t.headers,data:t.data}}import{Zodios as Ai}from"@zodios/core";import{randomUUID as Qa}from"node:crypto";import{SignJWT as Ka}from"jose";async function yi({username:t,connectedApp:e,scopes:r,additionalPayload:o}){let i={alg:"HS256",typ:"JWT",kid:e.secretId},n={jti:Qa(),iss:e.clientId,aud:"tableau",sub:t,scp:[...r],iat:Math.floor(Date.now()/1e3)-5,exp:Math.floor(Date.now()/1e3)+5*60,...o};return await new Ka(n).setProtectedHeader(i).sign(new TextEncoder().encode(e.secretValue))}import{makeApi as Ja,makeEndpoint as Ti}from"@zodios/core";import{z as ye}from"zod";import{z as Ne}from"zod";var wi=Ne.object({credentials:Ne.object({site:Ne.object({id:Ne.string()}),user:Ne.object({id:Ne.string()}),token:Ne.string()})});var Za=ye.object({credentials:ye.object({site:ye.object({contentUrl:ye.string()})}).and(ye.object({personalAccessTokenName:ye.string(),personalAccessTokenSecret:ye.string()}).or(ye.object({jwt:ye.string()})))}),Ya=Ti({method:"post",path:"/auth/signin",alias:"signIn",description:"Signs in with Tableau credentials.",response:wi,parameters:[{name:"credentials",type:"Body",schema:Za}]}),Xa=Ti({method:"post",path:"/auth/signout",alias:"signOut",description:"Signs you out of the current session. This call invalidates the authentication token that is created by a call to Sign In.",response:ye.void()}),el=Ja([Ya,Xa]),$r=[...el];var Fe=class{_apiClient;constructor(e){this._apiClient=e}get interceptors(){return this._apiClient.axios.interceptors}};var H=class extends Fe{_creds;get authHeader(){if(!this._creds)throw new Error("Authenticate by calling signIn() first");return{headers:{"X-Tableau-Auth":this._creds.token}}}get userId(){if(!this._creds)throw new Error("Authenticate by calling signIn() first");return this._creds.user.id}constructor(e,r){super(e),this._creds=r}};var _t=class extends Fe{constructor(e){super(new Ai(e,$r))}signIn=async e=>(await this._apiClient.signIn({credentials:{site:{contentUrl:e.siteName},...await(async()=>{switch(e.type){case"pat":return{personalAccessTokenName:e.patName,personalAccessTokenSecret:e.patValue};case"direct-trust":return{jwt:await yi({username:e.username,connectedApp:{clientId:e.clientId,secretId:e.secretId,secretValue:e.secretValue},scopes:e.scopes,additionalPayload:e.additionalPayload})}}})()}})).credentials},ir=class extends H{constructor(e,r){super(new Ai(e,$r),r)}signOut=async()=>{await this._apiClient.signOut(void 0,{...this.authHeader})}};import{Zodios as al}from"@zodios/core";import{makeApi as ol,makeEndpoint as il}from"@zodios/core";import{z as et}from"zod";import{z as k}from"zod";var tl=k.enum(["hitsTotal","hitsSmallSpanTotal","hitsMediumSpanTotal","hitsLargeSpanTotal","downstreamWorkbookCount"]),Ei=k.array(k.object({method:tl,sortDirection:k.enum(["asc","desc"]).default("asc").optional()})).nonempty(),_i=k.enum(["lens","datasource","virtualconnection","collection","project","flow","datarole","table","database","view","workbook"]),Si=k.union([k.array(k.string().datetime()).nonempty(),k.object({startDate:k.string().datetime(),endDate:k.string().datetime().optional()}).strict(),k.object({startDate:k.string().datetime().optional(),endDate:k.string().datetime()}).strict()]),Qr=k.object({contentTypes:k.array(_i).nonempty(),ownerIds:k.array(k.number().int()).nonempty(),modifiedTime:Si}).partial(),vi=k.union([Qr.extend({contentTypes:k.array(_i).nonempty()}).strict(),Qr.extend({ownerIds:k.array(k.number().int()).nonempty()}).strict(),Qr.extend({modifiedTime:Si}).strict()]),rl=k.object({uri:k.string(),content:k.record(k.string(),k.unknown())}),Ci=k.object({next:k.string(),prev:k.string(),pageIndex:k.number().int(),startIndex:k.number().int(),total:k.number().int(),limit:k.number().int(),items:k.array(rl)}).partial();var sl=il({method:"get",path:"/search",alias:"searchContent",description:"Searches across all supported content types for objects relevant to the search expression specified in the querystring of the request URI.",parameters:[{name:"terms",type:"Query",schema:et.string().optional()},{name:"page",type:"Query",schema:et.number().int().optional()},{name:"limit",type:"Query",schema:et.number().int().optional()},{name:"order_by",type:"Query",schema:et.string().optional()},{name:"filter",type:"Query",schema:et.string().optional()}],response:et.object({hits:Ci})}),nl=ol([sl]),Ri=[...nl];var St=class extends H{constructor(e,r){super(new al(e,Ri),r)}searchContent=async e=>(Object.entries(e).forEach(([o,i])=>{i===void 0&&delete e[o]}),(await this._apiClient.searchContent({queries:e,...this.authHeader})).hits)};import{Zodios as pl}from"@zodios/core";import{makeApi as ll,makeEndpoint as Ii}from"@zodios/core";import{z as qe}from"zod";import{z as nr}from"zod";import{z as Kr}from"zod";var sr=Kr.object({name:Kr.string(),id:Kr.string()});var Jr=nr.object({id:nr.string(),name:nr.string(),description:nr.string().optional(),project:sr});import{z as Ue}from"zod";var tt=Ue.object({pageNumber:Ue.coerce.number(),pageSize:Ue.coerce.number(),totalAvailable:Ue.coerce.number()}),Sf=Ue.object({next_page_token:Ue.string().optional(),total_available:Ue.coerce.number().optional()});import{z as xi}from"zod";var rt=[{name:"pageSize",type:"Query",schema:xi.number().optional(),description:"The number of items to return in one response. The minimum is 1. The maximum is 1000. The default is 100."},{name:"pageNumber",type:"Query",schema:xi.number().optional(),description:"The offset for paging. The default is 1."}];var cl=Ii({method:"get",path:"/sites/:siteId/datasources",alias:"listDatasources",description:"Returns a list of published data sources on the specified site. Supports a filter string as a query parameter in the format field:operator:value.",parameters:[...rt,{name:"siteId",type:"Path",schema:qe.string()},{name:"filter",type:"Query",schema:qe.string().optional(),description:"Filter string in the format field:operator:value (e.g., name:eq:Project Views)"}],response:qe.object({pagination:tt,datasources:qe.object({datasource:qe.optional(qe.array(Jr))})})}),ul=Ii({method:"get",path:"/sites/:siteId/datasources/:datasourceId",alias:"queryDatasource",description:"Returns information about the specified data source.",response:qe.object({datasource:Jr})}),dl=ll([cl,ul]),ki=[...dl];var vt=class extends H{constructor(e,r){super(new pl(e,ki),r)}listDatasources=async({siteId:e,filter:r,pageSize:o,pageNumber:i})=>{let n=await this._apiClient.listDatasources({params:{siteId:e},queries:{filter:r,pageSize:o,pageNumber:i},...this.authHeader});return{pagination:n.pagination,datasources:n.datasources.datasource??[]}};queryDatasource=async({siteId:e,datasourceId:r})=>(await this._apiClient.queryDatasource({params:{siteId:e,datasourceId:r},...this.authHeader})).datasource};import{Zodios as yl}from"@zodios/core";import{makeApi as ml,makeEndpoint as fl}from"@zodios/core";import{z as P}from"zod";var hl=P.object({data:P.object({publishedDatasources:P.array(P.object({name:P.string().nullable(),description:P.string().nullable(),owner:P.object({name:P.string().nullable()}),fields:P.array(P.object({name:P.string(),isHidden:P.boolean().nullable(),description:P.string().nullable(),descriptionInherited:P.array(P.object({attribute:P.string(),value:P.string().nullable()}).nullable()).nullable(),fullyQualifiedName:P.string(),__typename:P.string(),dataCategory:P.string().nullish(),role:P.string().nullish(),dataType:P.string().nullish(),defaultFormat:P.string().nullish(),semanticRole:P.string().nullish(),aggregation:P.string().nullish(),aggregationParam:P.string().nullish(),formula:P.string().nullish(),isAutoGenerated:P.boolean().nullish(),hasUserReference:P.boolean().nullish(),binSize:P.number().nullish(),hasOther:P.boolean().nullish(),delimiter:P.string().nullish(),combinationType:P.string().nullish()}))}))})}),gl=fl({method:"post",path:"/graphql",alias:"graphql",response:hl,parameters:[{name:"query",type:"Body",schema:P.object({query:P.string()})}]}),bl=ml([gl]),Pi=[...bl];var Ct=class extends H{constructor(e,r){super(new yl(e,Pi),r)}graphql=async e=>await this._apiClient.graphql({query:e},{...this.authHeader})};import{Zodios as Su}from"@zodios/core";import{Err as qs,Ok as vu}from"ts-results-es";function Rt(t,e){return function(){return t.apply(e,arguments)}}var{toString:wl}=Object.prototype,{getPrototypeOf:Yr}=Object,{iterator:lr,toStringTag:Li}=Symbol,cr=(t=>e=>{let r=wl.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),he=t=>(t=t.toLowerCase(),e=>cr(e)===t),ur=t=>e=>typeof e===t,{isArray:it}=Array,ot=ur("undefined");function xt(t){return t!==null&&!ot(t)&&t.constructor!==null&&!ot(t.constructor)&&oe(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var Oi=he("ArrayBuffer");function Tl(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Oi(t.buffer),e}var Al=ur("string"),oe=ur("function"),Mi=ur("number"),It=t=>t!==null&&typeof t=="object",El=t=>t===!0||t===!1,ar=t=>{if(cr(t)!=="object")return!1;let e=Yr(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Li in t)&&!(lr in t)},_l=t=>{if(!It(t)||xt(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},Sl=he("Date"),vl=he("File"),Cl=he("Blob"),Rl=he("FileList"),xl=t=>It(t)&&oe(t.pipe),Il=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||oe(t.append)&&((e=cr(t))==="formdata"||e==="object"&&oe(t.toString)&&t.toString()==="[object FormData]"))},kl=he("URLSearchParams"),[Pl,Dl,Ll,Ol]=["ReadableStream","Request","Response","Headers"].map(he),Ml=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kt(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let o,i;if(typeof t!="object"&&(t=[t]),it(t))for(o=0,i=t.length;o<i;o++)e.call(null,t[o],o,t);else{if(xt(t))return;let n=r?Object.getOwnPropertyNames(t):Object.keys(t),s=n.length,a;for(o=0;o<s;o++)a=n[o],e.call(null,t[a],a,t)}}function Ni(t,e){if(xt(t))return null;e=e.toLowerCase();let r=Object.keys(t),o=r.length,i;for(;o-- >0;)if(i=r[o],e===i.toLowerCase())return i;return null}var je=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Fi=t=>!ot(t)&&t!==je;function Zr(){let{caseless:t,skipUndefined:e}=Fi(this)&&this||{},r={},o=(i,n)=>{let s=t&&Ni(r,n)||n;ar(r[s])&&ar(i)?r[s]=Zr(r[s],i):ar(i)?r[s]=Zr({},i):it(i)?r[s]=i.slice():(!e||!ot(i))&&(r[s]=i)};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&kt(arguments[i],o);return r}var Nl=(t,e,r,{allOwnKeys:o}={})=>(kt(e,(i,n)=>{r&&oe(i)?t[n]=Rt(i,r):t[n]=i},{allOwnKeys:o}),t),Fl=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),Ul=(t,e,r,o)=>{t.prototype=Object.create(e.prototype,o),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},ql=(t,e,r,o)=>{let i,n,s,a={};if(e=e||{},t==null)return e;do{for(i=Object.getOwnPropertyNames(t),n=i.length;n-- >0;)s=i[n],(!o||o(s,t,e))&&!a[s]&&(e[s]=t[s],a[s]=!0);t=r!==!1&&Yr(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},jl=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let o=t.indexOf(e,r);return o!==-1&&o===r},Vl=t=>{if(!t)return null;if(it(t))return t;let e=t.length;if(!Mi(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Bl=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Yr(Uint8Array)),zl=(t,e)=>{let o=(t&&t[lr]).call(t),i;for(;(i=o.next())&&!i.done;){let n=i.value;e.call(t,n[0],n[1])}},Wl=(t,e)=>{let r,o=[];for(;(r=t.exec(e))!==null;)o.push(r);return o},Hl=he("HTMLFormElement"),Gl=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,o,i){return o.toUpperCase()+i}),Di=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),$l=he("RegExp"),Ui=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),o={};kt(r,(i,n)=>{let s;(s=e(i,n,t))!==!1&&(o[n]=s||i)}),Object.defineProperties(t,o)},Ql=t=>{Ui(t,(e,r)=>{if(oe(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let o=t[r];if(oe(o)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Kl=(t,e)=>{let r={},o=i=>{i.forEach(n=>{r[n]=!0})};return it(t)?o(t):o(String(t).split(e)),r},Jl=()=>{},Zl=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Yl(t){return!!(t&&oe(t.append)&&t[Li]==="FormData"&&t[lr])}var Xl=t=>{let e=new Array(10),r=(o,i)=>{if(It(o)){if(e.indexOf(o)>=0)return;if(xt(o))return o;if(!("toJSON"in o)){e[i]=o;let n=it(o)?[]:{};return kt(o,(s,a)=>{let c=r(s,i+1);!ot(c)&&(n[a]=c)}),e[i]=void 0,n}}return o};return r(t,0)},ec=he("AsyncFunction"),tc=t=>t&&(It(t)||oe(t))&&oe(t.then)&&oe(t.catch),qi=((t,e)=>t?setImmediate:e?((r,o)=>(je.addEventListener("message",({source:i,data:n})=>{i===je&&n===r&&o.length&&o.shift()()},!1),i=>{o.push(i),je.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",oe(je.postMessage)),rc=typeof queueMicrotask<"u"?queueMicrotask.bind(je):typeof process<"u"&&process.nextTick||qi,oc=t=>t!=null&&oe(t[lr]),d={isArray:it,isArrayBuffer:Oi,isBuffer:xt,isFormData:Il,isArrayBufferView:Tl,isString:Al,isNumber:Mi,isBoolean:El,isObject:It,isPlainObject:ar,isEmptyObject:_l,isReadableStream:Pl,isRequest:Dl,isResponse:Ll,isHeaders:Ol,isUndefined:ot,isDate:Sl,isFile:vl,isBlob:Cl,isRegExp:$l,isFunction:oe,isStream:xl,isURLSearchParams:kl,isTypedArray:Bl,isFileList:Rl,forEach:kt,merge:Zr,extend:Nl,trim:Ml,stripBOM:Fl,inherits:Ul,toFlatObject:ql,kindOf:cr,kindOfTest:he,endsWith:jl,toArray:Vl,forEachEntry:zl,matchAll:Wl,isHTMLForm:Hl,hasOwnProperty:Di,hasOwnProp:Di,reduceDescriptors:Ui,freezeMethods:Ql,toObjectSet:Kl,toCamelCase:Gl,noop:Jl,toFiniteNumber:Zl,findKey:Ni,global:je,isContextDefined:Fi,isSpecCompliantForm:Yl,toJSONObject:Xl,isAsyncFn:ec,isThenable:tc,setImmediate:qi,asap:rc,isIterable:oc};function st(t,e,r,o,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),o&&(this.request=o),i&&(this.response=i,this.status=i.status?i.status:null)}d.inherits(st,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:d.toJSONObject(this.config),code:this.code,status:this.status}}});var ji=st.prototype,Vi={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Vi[t]={value:t}});Object.defineProperties(st,Vi);Object.defineProperty(ji,"isAxiosError",{value:!0});st.from=(t,e,r,o,i,n)=>{let s=Object.create(ji);d.toFlatObject(t,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError");let a=t&&t.message?t.message:"Error",c=e==null&&t?t.code:e;return st.call(s,a,c,r,o,i),t&&s.cause==null&&Object.defineProperty(s,"cause",{value:t,configurable:!0}),s.name=t&&t.name||"Error",n&&Object.assign(s,n),s};var T=st;import ic from"form-data";var dr=ic;function Xr(t){return d.isPlainObject(t)||d.isArray(t)}function zi(t){return d.endsWith(t,"[]")?t.slice(0,-2):t}function Bi(t,e,r){return t?t.concat(e).map(function(i,n){return i=zi(i),!r&&n?"["+i+"]":i}).join(r?".":""):e}function sc(t){return d.isArray(t)&&!t.some(Xr)}var nc=d.toFlatObject(d,{},null,function(e){return/^is[A-Z]/.test(e)});function ac(t,e,r){if(!d.isObject(t))throw new TypeError("target must be an object");e=e||new(dr||FormData),r=d.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,w){return!d.isUndefined(w[y])});let o=r.metaTokens,i=r.visitor||u,n=r.dots,s=r.indexes,c=(r.Blob||typeof Blob<"u"&&Blob)&&d.isSpecCompliantForm(e);if(!d.isFunction(i))throw new TypeError("visitor must be a function");function l(f){if(f===null)return"";if(d.isDate(f))return f.toISOString();if(d.isBoolean(f))return f.toString();if(!c&&d.isBlob(f))throw new T("Blob is not supported. Use a Buffer instead.");return d.isArrayBuffer(f)||d.isTypedArray(f)?c&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function u(f,y,w){let v=f;if(f&&!w&&typeof f=="object"){if(d.endsWith(y,"{}"))y=o?y:y.slice(0,-2),f=JSON.stringify(f);else if(d.isArray(f)&&sc(f)||(d.isFileList(f)||d.endsWith(y,"[]"))&&(v=d.toArray(f)))return y=zi(y),v.forEach(function(A,x){!(d.isUndefined(A)||A===null)&&e.append(s===!0?Bi([y],x,n):s===null?y:y+"[]",l(A))}),!1}return Xr(f)?!0:(e.append(Bi(w,y,n),l(f)),!1)}let p=[],g=Object.assign(nc,{defaultVisitor:u,convertValue:l,isVisitable:Xr});function b(f,y){if(!d.isUndefined(f)){if(p.indexOf(f)!==-1)throw Error("Circular reference detected in "+y.join("."));p.push(f),d.forEach(f,function(v,D){(!(d.isUndefined(v)||v===null)&&i.call(e,v,d.isString(D)?D.trim():D,y,g))===!0&&b(v,y?y.concat(D):[D])}),p.pop()}}if(!d.isObject(t))throw new TypeError("data must be an object");return b(t),e}var Ce=ac;function Wi(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(o){return e[o]})}function Hi(t,e){this._pairs=[],t&&Ce(t,this,e)}var Gi=Hi.prototype;Gi.append=function(e,r){this._pairs.push([e,r])};Gi.toString=function(e){let r=e?function(o){return e.call(this,o,Wi)}:Wi;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var $i=Hi;function lc(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ve(t,e,r){if(!e)return t;let o=r&&r.encode||lc;d.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,n;if(i?n=i(e,r):n=d.isURLSearchParams(e)?e.toString():new $i(e,r).toString(o),n){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t}var eo=class{constructor(){this.handlers=[]}use(e,r,o){return this.handlers.push({fulfilled:e,rejected:r,synchronous:o?o.synchronous:!1,runWhen:o?o.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){d.forEach(this.handlers,function(o){o!==null&&e(o)})}},to=eo;var nt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};import uc from"crypto";import cc from"url";var Qi=cc.URLSearchParams;var ro="abcdefghijklmnopqrstuvwxyz",Ki="0123456789",Ji={DIGIT:Ki,ALPHA:ro,ALPHA_DIGIT:ro+ro.toUpperCase()+Ki},dc=(t=16,e=Ji.ALPHA_DIGIT)=>{let r="",{length:o}=e,i=new Uint32Array(t);uc.randomFillSync(i);for(let n=0;n<t;n++)r+=e[i[n]%o];return r},Zi={isNode:!0,classes:{URLSearchParams:Qi,FormData:dr,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Ji,generateString:dc,protocols:["http","https","file","data"]};var so={};Ra(so,{hasBrowserEnv:()=>io,hasStandardBrowserEnv:()=>pc,hasStandardBrowserWebWorkerEnv:()=>mc,navigator:()=>oo,origin:()=>fc});var io=typeof window<"u"&&typeof document<"u",oo=typeof navigator=="object"&&navigator||void 0,pc=io&&(!oo||["ReactNative","NativeScript","NS"].indexOf(oo.product)<0),mc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",fc=io&&window.location.href||"http://localhost";var L={...so,...Zi};function no(t,e){return Ce(t,new L.classes.URLSearchParams,{visitor:function(r,o,i,n){return L.isNode&&d.isBuffer(r)?(this.append(o,r.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...e})}function hc(t){return d.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function gc(t){let e={},r=Object.keys(t),o,i=r.length,n;for(o=0;o<i;o++)n=r[o],e[n]=t[n];return e}function bc(t){function e(r,o,i,n){let s=r[n++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),c=n>=r.length;return s=!s&&d.isArray(i)?i.length:s,c?(d.hasOwnProp(i,s)?i[s]=[i[s],o]:i[s]=o,!a):((!i[s]||!d.isObject(i[s]))&&(i[s]=[]),e(r,o,i[s],n)&&d.isArray(i[s])&&(i[s]=gc(i[s])),!a)}if(d.isFormData(t)&&d.isFunction(t.entries)){let r={};return d.forEachEntry(t,(o,i)=>{e(hc(o),i,r,0)}),r}return null}var pr=bc;function yc(t,e,r){if(d.isString(t))try{return(e||JSON.parse)(t),d.trim(t)}catch(o){if(o.name!=="SyntaxError")throw o}return(r||JSON.stringify)(t)}var ao={transitional:nt,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){let o=r.getContentType()||"",i=o.indexOf("application/json")>-1,n=d.isObject(e);if(n&&d.isHTMLForm(e)&&(e=new FormData(e)),d.isFormData(e))return i?JSON.stringify(pr(e)):e;if(d.isArrayBuffer(e)||d.isBuffer(e)||d.isStream(e)||d.isFile(e)||d.isBlob(e)||d.isReadableStream(e))return e;if(d.isArrayBufferView(e))return e.buffer;if(d.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(n){if(o.indexOf("application/x-www-form-urlencoded")>-1)return no(e,this.formSerializer).toString();if((a=d.isFileList(e))||o.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return Ce(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return n||i?(r.setContentType("application/json",!1),yc(e)):e}],transformResponse:[function(e){let r=this.transitional||ao.transitional,o=r&&r.forcedJSONParsing,i=this.responseType==="json";if(d.isResponse(e)||d.isReadableStream(e))return e;if(e&&d.isString(e)&&(o&&!this.responseType||i)){let s=!(r&&r.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(a){if(s)throw a.name==="SyntaxError"?T.from(a,T.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:L.classes.FormData,Blob:L.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};d.forEach(["delete","get","head","post","put","patch"],t=>{ao.headers[t]={}});var at=ao;var wc=d.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Yi=t=>{let e={},r,o,i;return t&&t.split(`
|
|
6
|
+
`).forEach(function(s){i=s.indexOf(":"),r=s.substring(0,i).trim().toLowerCase(),o=s.substring(i+1).trim(),!(!r||e[r]&&wc[r])&&(r==="set-cookie"?e[r]?e[r].push(o):e[r]=[o]:e[r]=e[r]?e[r]+", "+o:o)}),e};var Xi=Symbol("internals");function Pt(t){return t&&String(t).trim().toLowerCase()}function mr(t){return t===!1||t==null?t:d.isArray(t)?t.map(mr):String(t)}function Tc(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,o;for(;o=r.exec(t);)e[o[1]]=o[2];return e}var Ac=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function lo(t,e,r,o,i){if(d.isFunction(o))return o.call(this,e,r);if(i&&(e=r),!!d.isString(e)){if(d.isString(o))return e.indexOf(o)!==-1;if(d.isRegExp(o))return o.test(e)}}function Ec(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,o)=>r.toUpperCase()+o)}function _c(t,e){let r=d.toCamelCase(" "+e);["get","set","has"].forEach(o=>{Object.defineProperty(t,o+r,{value:function(i,n,s){return this[o].call(this,e,i,n,s)},configurable:!0})})}var lt=class{constructor(e){e&&this.set(e)}set(e,r,o){let i=this;function n(a,c,l){let u=Pt(c);if(!u)throw new Error("header name must be a non-empty string");let p=d.findKey(i,u);(!p||i[p]===void 0||l===!0||l===void 0&&i[p]!==!1)&&(i[p||c]=mr(a))}let s=(a,c)=>d.forEach(a,(l,u)=>n(l,u,c));if(d.isPlainObject(e)||e instanceof this.constructor)s(e,r);else if(d.isString(e)&&(e=e.trim())&&!Ac(e))s(Yi(e),r);else if(d.isObject(e)&&d.isIterable(e)){let a={},c,l;for(let u of e){if(!d.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[l=u[0]]=(c=a[l])?d.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}s(a,r)}else e!=null&&n(r,e,o);return this}get(e,r){if(e=Pt(e),e){let o=d.findKey(this,e);if(o){let i=this[o];if(!r)return i;if(r===!0)return Tc(i);if(d.isFunction(r))return r.call(this,i,o);if(d.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=Pt(e),e){let o=d.findKey(this,e);return!!(o&&this[o]!==void 0&&(!r||lo(this,this[o],o,r)))}return!1}delete(e,r){let o=this,i=!1;function n(s){if(s=Pt(s),s){let a=d.findKey(o,s);a&&(!r||lo(o,o[a],a,r))&&(delete o[a],i=!0)}}return d.isArray(e)?e.forEach(n):n(e),i}clear(e){let r=Object.keys(this),o=r.length,i=!1;for(;o--;){let n=r[o];(!e||lo(this,this[n],n,e,!0))&&(delete this[n],i=!0)}return i}normalize(e){let r=this,o={};return d.forEach(this,(i,n)=>{let s=d.findKey(o,n);if(s){r[s]=mr(i),delete r[n];return}let a=e?Ec(n):String(n).trim();a!==n&&delete r[n],r[a]=mr(i),o[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return d.forEach(this,(o,i)=>{o!=null&&o!==!1&&(r[i]=e&&d.isArray(o)?o.join(", "):o)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(`
|
|
7
|
+
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let o=new this(e);return r.forEach(i=>o.set(i)),o}static accessor(e){let o=(this[Xi]=this[Xi]={accessors:{}}).accessors,i=this.prototype;function n(s){let a=Pt(s);o[a]||(_c(i,s),o[a]=!0)}return d.isArray(e)?e.forEach(n):n(e),this}};lt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);d.reduceDescriptors(lt.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(o){this[r]=o}}});d.freezeMethods(lt);var V=lt;function Dt(t,e){let r=this||at,o=e||r,i=V.from(o.headers),n=o.data;return d.forEach(t,function(a){n=a.call(r,n,i.normalize(),e?e.status:void 0)}),i.normalize(),n}function Lt(t){return!!(t&&t.__CANCEL__)}function es(t,e,r){T.call(this,t??"canceled",T.ERR_CANCELED,e,r),this.name="CanceledError"}d.inherits(es,T,{__CANCEL__:!0});var ne=es;function we(t,e,r){let o=r.config.validateStatus;!r.status||!o||o(r.status)?t(r):e(new T("Request failed with status code "+r.status,[T.ERR_BAD_REQUEST,T.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function co(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function uo(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Be(t,e,r){let o=!co(e);return t&&(o||r==!1)?uo(t,e):e}import Fc from"proxy-from-env";import Uc from"http";import qc from"https";import jc from"util";import Vc from"follow-redirects";import Re from"zlib";var ze="1.12.1";function Ot(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}var Sc=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function po(t,e,r){let o=r&&r.Blob||L.classes.Blob,i=Ot(t);if(e===void 0&&o&&(e=!0),i==="data"){t=i.length?t.slice(i.length+1):t;let n=Sc.exec(t);if(!n)throw new T("Invalid URL",T.ERR_INVALID_URL);let s=n[1],a=n[2],c=n[3],l=Buffer.from(decodeURIComponent(c),a?"base64":"utf8");if(e){if(!o)throw new T("Blob is not supported",T.ERR_NOT_SUPPORT);return new o([l],{type:s})}return l}throw new T("Unsupported protocol "+i,T.ERR_NOT_SUPPORT)}import dt from"stream";import vc from"stream";var mo=Symbol("internals"),fo=class extends vc.Transform{constructor(e){e=d.toFlatObject(e,{maxRate:0,chunkSize:64*1024,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,(o,i)=>!d.isUndefined(i[o])),super({readableHighWaterMark:e.chunkSize});let r=this[mo]={timeWindow:e.timeWindow,chunkSize:e.chunkSize,maxRate:e.maxRate,minChunkSize:e.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null};this.on("newListener",o=>{o==="progress"&&(r.isCaptured||(r.isCaptured=!0))})}_read(e){let r=this[mo];return r.onReadCallback&&r.onReadCallback(),super._read(e)}_transform(e,r,o){let i=this[mo],n=i.maxRate,s=this.readableHighWaterMark,a=i.timeWindow,c=1e3/a,l=n/c,u=i.minChunkSize!==!1?Math.max(i.minChunkSize,l*.01):0,p=(b,f)=>{let y=Buffer.byteLength(b);i.bytesSeen+=y,i.bytes+=y,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(b)?process.nextTick(f):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(f)}},g=(b,f)=>{let y=Buffer.byteLength(b),w=null,v=s,D,A=0;if(n){let x=Date.now();(!i.ts||(A=x-i.ts)>=a)&&(i.ts=x,D=l-i.bytes,i.bytes=D<0?-D:0,A=0),D=l-i.bytes}if(n){if(D<=0)return setTimeout(()=>{f(null,b)},a-A);D<v&&(v=D)}v&&y>v&&y-v>u&&(w=b.subarray(v),b=b.subarray(0,v)),p(b,w?()=>{process.nextTick(f,null,w)}:f)};g(e,function b(f,y){if(f)return o(f);y?g(y,b):o(null)})}},ho=fo;import{EventEmitter as Bc}from"events";import Rc from"util";import{Readable as xc}from"stream";var{asyncIterator:ts}=Symbol,Cc=async function*(t){t.stream?yield*t.stream():t.arrayBuffer?yield await t.arrayBuffer():t[ts]?yield*t[ts]():yield t},fr=Cc;var Ic=L.ALPHABET.ALPHA_DIGIT+"-_",Mt=typeof TextEncoder=="function"?new TextEncoder:new Rc.TextEncoder,We=`\r
|
|
8
|
+
`,kc=Mt.encode(We),Pc=2,go=class{constructor(e,r){let{escapeName:o}=this.constructor,i=d.isString(r),n=`Content-Disposition: form-data; name="${o(e)}"${!i&&r.name?`; filename="${o(r.name)}"`:""}${We}`;i?r=Mt.encode(String(r).replace(/\r?\n|\r\n?/g,We)):n+=`Content-Type: ${r.type||"application/octet-stream"}${We}`,this.headers=Mt.encode(n+We),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+Pc,this.name=e,this.value=r}async*encode(){yield this.headers;let{value:e}=this;d.isTypedArray(e)?yield e:yield*fr(e),yield kc}static escapeName(e){return String(e).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},Dc=(t,e,r)=>{let{tag:o="form-data-boundary",size:i=25,boundary:n=o+"-"+L.generateString(i,Ic)}=r||{};if(!d.isFormData(t))throw TypeError("FormData instance required");if(n.length<1||n.length>70)throw Error("boundary must be 10-70 characters long");let s=Mt.encode("--"+n+We),a=Mt.encode("--"+n+"--"+We),c=a.byteLength,l=Array.from(t.entries()).map(([p,g])=>{let b=new go(p,g);return c+=b.size,b});c+=s.byteLength*l.length,c=d.toFiniteNumber(c);let u={"Content-Type":`multipart/form-data; boundary=${n}`};return Number.isFinite(c)&&(u["Content-Length"]=c),e&&e(u),xc.from(async function*(){for(let p of l)yield s,yield*p.encode();yield a}())},rs=Dc;import Lc from"stream";var bo=class extends Lc.Transform{__transform(e,r,o){this.push(e),o()}_transform(e,r,o){if(e.length!==0&&(this._transform=this.__transform,e[0]!==120)){let i=Buffer.alloc(2);i[0]=120,i[1]=156,this.push(i,r)}this.__transform(e,r,o)}},os=bo;var Oc=(t,e)=>d.isAsyncFn(t)?function(...r){let o=r.pop();t.apply(this,r).then(i=>{try{e?o(null,...e(i)):o(null,i)}catch(n){o(n)}},o)}:t,is=Oc;function Mc(t,e){t=t||10;let r=new Array(t),o=new Array(t),i=0,n=0,s;return e=e!==void 0?e:1e3,function(c){let l=Date.now(),u=o[n];s||(s=l),r[i]=c,o[i]=l;let p=n,g=0;for(;p!==i;)g+=r[p++],p=p%t;if(i=(i+1)%t,i===n&&(n=(n+1)%t),l-s<e)return;let b=u&&l-u;return b?Math.round(g*1e3/b):void 0}}var ss=Mc;function Nc(t,e){let r=0,o=1e3/e,i,n,s=(l,u=Date.now())=>{r=u,i=null,n&&(clearTimeout(n),n=null),t(...l)};return[(...l)=>{let u=Date.now(),p=u-r;p>=o?s(l,u):(i=l,n||(n=setTimeout(()=>{n=null,s(i)},o-p)))},()=>i&&s(i)]}var ns=Nc;var Ee=(t,e,r=3)=>{let o=0,i=ss(50,250);return ns(n=>{let s=n.loaded,a=n.lengthComputable?n.total:void 0,c=s-o,l=i(c),u=s<=a;o=s;let p={loaded:s,total:a,progress:a?s/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&u?(a-s)/l:void 0,event:n,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(p)},r)},ct=(t,e)=>{let r=t!=null;return[o=>e[0]({lengthComputable:r,total:t,loaded:o}),e[1]]},ut=t=>(...e)=>d.asap(()=>t(...e));function yo(t){if(!t||typeof t!="string"||!t.startsWith("data:"))return 0;let e=t.indexOf(",");if(e<0)return 0;let r=t.slice(5,e),o=t.slice(e+1);if(/;base64/i.test(r)){let n=o.length,s=o.length;for(let g=0;g<s;g++)if(o.charCodeAt(g)===37&&g+2<s){let b=o.charCodeAt(g+1),f=o.charCodeAt(g+2);(b>=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(f>=48&&f<=57||f>=65&&f<=70||f>=97&&f<=102)&&(n-=2,g+=2)}let a=0,c=s-1,l=g=>g>=2&&o.charCodeAt(g-2)===37&&o.charCodeAt(g-1)===51&&(o.charCodeAt(g)===68||o.charCodeAt(g)===100);c>=0&&(o.charCodeAt(c)===61?(a++,c--):l(c)&&(a++,c-=3)),a===1&&c>=0&&(o.charCodeAt(c)===61||l(c))&&a++;let p=Math.floor(n/4)*3-(a||0);return p>0?p:0}return Buffer.byteLength(o,"utf8")}var as={flush:Re.constants.Z_SYNC_FLUSH,finishFlush:Re.constants.Z_SYNC_FLUSH},zc={flush:Re.constants.BROTLI_OPERATION_FLUSH,finishFlush:Re.constants.BROTLI_OPERATION_FLUSH},ls=d.isFunction(Re.createBrotliDecompress),{http:Wc,https:Hc}=Vc,Gc=/https:?/,cs=L.protocols.map(t=>t+":"),us=(t,[e,r])=>(t.on("end",r).on("error",r),e);function $c(t,e){t.beforeRedirects.proxy&&t.beforeRedirects.proxy(t),t.beforeRedirects.config&&t.beforeRedirects.config(t,e)}function ps(t,e,r){let o=e;if(!o&&o!==!1){let i=Fc.getProxyForUrl(r);i&&(o=new URL(i))}if(o){if(o.username&&(o.auth=(o.username||"")+":"+(o.password||"")),o.auth){(o.auth.username||o.auth.password)&&(o.auth=(o.auth.username||"")+":"+(o.auth.password||""));let n=Buffer.from(o.auth,"utf8").toString("base64");t.headers["Proxy-Authorization"]="Basic "+n}t.headers.host=t.hostname+(t.port?":"+t.port:"");let i=o.hostname||o.host;t.hostname=i,t.host=i,t.port=o.port,t.path=r,o.protocol&&(t.protocol=o.protocol.includes(":")?o.protocol:`${o.protocol}:`)}t.beforeRedirects.proxy=function(n){ps(n,e,n.href)}}var Qc=typeof process<"u"&&d.kindOf(process)==="process",Kc=t=>new Promise((e,r)=>{let o,i,n=(c,l)=>{i||(i=!0,o&&o(c,l))},s=c=>{n(c),e(c)},a=c=>{n(c,!0),r(c)};t(s,a,c=>o=c).catch(a)}),Jc=({address:t,family:e})=>{if(!d.isString(t))throw TypeError("address must be a string");return{address:t,family:e||(t.indexOf(".")<0?6:4)}},ds=(t,e)=>Jc(d.isObject(t)?t:{address:t,family:e}),ms=Qc&&function(e){return Kc(async function(o,i,n){let{data:s,lookup:a,family:c}=e,{responseType:l,responseEncoding:u}=e,p=e.method.toUpperCase(),g,b=!1,f;if(a){let S=is(a,_=>d.isArray(_)?_:[_]);a=(_,z,K)=>{S(_,z,(U,te,me)=>{if(U)return K(U);let Y=d.isArray(te)?te.map(re=>ds(re)):[ds(te,me)];z.all?K(U,Y):K(U,Y[0].address,Y[0].family)})}}let y=new Bc,w=()=>{e.cancelToken&&e.cancelToken.unsubscribe(v),e.signal&&e.signal.removeEventListener("abort",v),y.removeAllListeners()};n((S,_)=>{g=!0,_&&(b=!0,w())});function v(S){y.emit("abort",!S||S.type?new ne(null,e,f):S)}y.once("abort",i),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(v),e.signal&&(e.signal.aborted?v():e.signal.addEventListener("abort",v)));let D=Be(e.baseURL,e.url,e.allowAbsoluteUrls),A=new URL(D,L.hasBrowserEnv?L.origin:void 0),x=A.protocol||cs[0];if(x==="data:"){if(e.maxContentLength>-1){let _=String(e.url||D||"");if(yo(_)>e.maxContentLength)return i(new T("maxContentLength size of "+e.maxContentLength+" exceeded",T.ERR_BAD_RESPONSE,e))}let S;if(p!=="GET")return we(o,i,{status:405,statusText:"method not allowed",headers:{},config:e});try{S=po(e.url,l==="blob",{Blob:e.env&&e.env.Blob})}catch(_){throw T.from(_,T.ERR_BAD_REQUEST,e)}return l==="text"?(S=S.toString(u),(!u||u==="utf8")&&(S=d.stripBOM(S))):l==="stream"&&(S=dt.Readable.from(S)),we(o,i,{data:S,status:200,statusText:"OK",headers:new V,config:e})}if(cs.indexOf(x)===-1)return i(new T("Unsupported protocol "+x,T.ERR_BAD_REQUEST,e));let R=V.from(e.headers).normalize();R.set("User-Agent","axios/"+ze,!1);let{onUploadProgress:j,onDownloadProgress:F}=e,ae=e.maxRate,pe,Ae;if(d.isSpecCompliantForm(s)){let S=R.getContentType(/boundary=([-_\w\d]{10,70})/i);s=rs(s,_=>{R.set(_)},{tag:`axios-${ze}-boundary`,boundary:S&&S[1]||void 0})}else if(d.isFormData(s)&&d.isFunction(s.getHeaders)){if(R.set(s.getHeaders()),!R.hasContentLength())try{let S=await jc.promisify(s.getLength).call(s);Number.isFinite(S)&&S>=0&&R.setContentLength(S)}catch{}}else if(d.isBlob(s)||d.isFile(s))s.size&&R.setContentType(s.type||"application/octet-stream"),R.setContentLength(s.size||0),s=dt.Readable.from(fr(s));else if(s&&!d.isStream(s)){if(!Buffer.isBuffer(s))if(d.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(d.isString(s))s=Buffer.from(s,"utf-8");else return i(new T("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",T.ERR_BAD_REQUEST,e));if(R.setContentLength(s.length,!1),e.maxBodyLength>-1&&s.length>e.maxBodyLength)return i(new T("Request body larger than maxBodyLength limit",T.ERR_BAD_REQUEST,e))}let _e=d.toFiniteNumber(R.getContentLength());d.isArray(ae)?(pe=ae[0],Ae=ae[1]):pe=Ae=ae,s&&(j||pe)&&(d.isStream(s)||(s=dt.Readable.from(s,{objectMode:!1})),s=dt.pipeline([s,new ho({maxRate:d.toFiniteNumber(pe)})],d.noop),j&&s.on("progress",us(s,ct(_e,Ee(ut(j),!1,3)))));let se;if(e.auth){let S=e.auth.username||"",_=e.auth.password||"";se=S+":"+_}if(!se&&A.username){let S=A.username,_=A.password;se=S+":"+_}se&&R.delete("authorization");let le;try{le=Ve(A.pathname+A.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(S){let _=new Error(S.message);return _.config=e,_.url=e.url,_.exists=!0,i(_)}R.set("Accept-Encoding","gzip, compress, deflate"+(ls?", br":""),!1);let $={path:le,method:p,headers:R.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:se,protocol:x,family:c,beforeRedirect:$c,beforeRedirects:{}};!d.isUndefined(a)&&($.lookup=a),e.socketPath?$.socketPath=e.socketPath:($.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,$.port=A.port,ps($,e.proxy,x+"//"+A.hostname+(A.port?":"+A.port:"")+$.path));let J,Se=Gc.test($.protocol);if($.agent=Se?e.httpsAgent:e.httpAgent,e.transport?J=e.transport:e.maxRedirects===0?J=Se?qc:Uc:(e.maxRedirects&&($.maxRedirects=e.maxRedirects),e.beforeRedirect&&($.beforeRedirects.config=e.beforeRedirect),J=Se?Hc:Wc),e.maxBodyLength>-1?$.maxBodyLength=e.maxBodyLength:$.maxBodyLength=1/0,e.insecureHTTPParser&&($.insecureHTTPParser=e.insecureHTTPParser),f=J.request($,function(_){if(f.destroyed)return;let z=[_],K=+_.headers["content-length"];if(F||Ae){let re=new ho({maxRate:d.toFiniteNumber(Ae)});F&&re.on("progress",us(re,ct(K,Ee(ut(F),!0,3)))),z.push(re)}let U=_,te=_.req||f;if(e.decompress!==!1&&_.headers["content-encoding"])switch((p==="HEAD"||_.statusCode===204)&&delete _.headers["content-encoding"],(_.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":z.push(Re.createUnzip(as)),delete _.headers["content-encoding"];break;case"deflate":z.push(new os),z.push(Re.createUnzip(as)),delete _.headers["content-encoding"];break;case"br":ls&&(z.push(Re.createBrotliDecompress(zc)),delete _.headers["content-encoding"])}U=z.length>1?dt.pipeline(z,d.noop):z[0];let me=dt.finished(U,()=>{me(),w()}),Y={status:_.statusCode,statusText:_.statusMessage,headers:new V(_.headers),config:e,request:te};if(l==="stream")Y.data=U,we(o,i,Y);else{let re=[],er=0;U.on("data",function(Q){re.push(Q),er+=Q.length,e.maxContentLength>-1&&er>e.maxContentLength&&(b=!0,U.destroy(),i(new T("maxContentLength size of "+e.maxContentLength+" exceeded",T.ERR_BAD_RESPONSE,e,te)))}),U.on("aborted",function(){if(b)return;let Q=new T("stream has been aborted",T.ERR_BAD_RESPONSE,e,te);U.destroy(Q),i(Q)}),U.on("error",function(Q){f.destroyed||i(T.from(Q,null,e,te))}),U.on("end",function(){try{let Q=re.length===1?re[0]:Buffer.concat(re);l!=="arraybuffer"&&(Q=Q.toString(u),(!u||u==="utf8")&&(Q=d.stripBOM(Q))),Y.data=Q}catch(Q){return i(T.from(Q,null,e,Y.request,Y))}we(o,i,Y)})}y.once("abort",re=>{U.destroyed||(U.emit("error",re),U.destroy())})}),y.once("abort",S=>{i(S),f.destroy(S)}),f.on("error",function(_){i(T.from(_,null,e,f))}),f.on("socket",function(_){_.setKeepAlive(!0,1e3*60)}),e.timeout){let S=parseInt(e.timeout,10);if(Number.isNaN(S)){i(new T("error trying to parse `config.timeout` to int",T.ERR_BAD_OPTION_VALUE,e,f));return}f.setTimeout(S,function(){if(g)return;let z=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",K=e.transitional||nt;e.timeoutErrorMessage&&(z=e.timeoutErrorMessage),i(new T(z,K.clarifyTimeoutError?T.ETIMEDOUT:T.ECONNABORTED,e,f)),v()})}if(d.isStream(s)){let S=!1,_=!1;s.on("end",()=>{S=!0}),s.once("error",z=>{_=!0,f.destroy(z)}),s.on("close",()=>{!S&&!_&&v(new ne("Request stream has been aborted",e,f))}),s.pipe(f)}else f.end(s)})};var fs=L.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,L.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(L.origin),L.navigator&&/(msie|trident)/i.test(L.navigator.userAgent)):()=>!0;var hs=L.hasStandardBrowserEnv?{write(t,e,r,o,i,n){let s=[t+"="+encodeURIComponent(e)];d.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),d.isString(o)&&s.push("path="+o),d.isString(i)&&s.push("domain="+i),n===!0&&s.push("secure"),document.cookie=s.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};var gs=t=>t instanceof V?{...t}:t;function ge(t,e){e=e||{};let r={};function o(l,u,p,g){return d.isPlainObject(l)&&d.isPlainObject(u)?d.merge.call({caseless:g},l,u):d.isPlainObject(u)?d.merge({},u):d.isArray(u)?u.slice():u}function i(l,u,p,g){if(d.isUndefined(u)){if(!d.isUndefined(l))return o(void 0,l,p,g)}else return o(l,u,p,g)}function n(l,u){if(!d.isUndefined(u))return o(void 0,u)}function s(l,u){if(d.isUndefined(u)){if(!d.isUndefined(l))return o(void 0,l)}else return o(void 0,u)}function a(l,u,p){if(p in e)return o(l,u);if(p in t)return o(void 0,l)}let c={url:n,method:n,data:n,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(l,u,p)=>i(gs(l),gs(u),p,!0)};return d.forEach(Object.keys({...t,...e}),function(u){let p=c[u]||i,g=p(t[u],e[u],u);d.isUndefined(g)&&p!==a||(r[u]=g)}),r}var hr=t=>{let e=ge({},t),{data:r,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:n,headers:s,auth:a}=e;if(e.headers=s=V.from(s),e.url=Ve(Be(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),d.isFormData(r)){if(L.hasStandardBrowserEnv||L.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(d.isFunction(r.getHeaders)){let c=r.getHeaders(),l=["content-type","content-length"];Object.entries(c).forEach(([u,p])=>{l.includes(u.toLowerCase())&&s.set(u,p)})}}if(L.hasStandardBrowserEnv&&(o&&d.isFunction(o)&&(o=o(e)),o||o!==!1&&fs(e.url))){let c=i&&n&&hs.read(n);c&&s.set(i,c)}return e};var Zc=typeof XMLHttpRequest<"u",bs=Zc&&function(t){return new Promise(function(r,o){let i=hr(t),n=i.data,s=V.from(i.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:l}=i,u,p,g,b,f;function y(){b&&b(),f&&f(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function v(){if(!w)return;let A=V.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),R={data:!a||a==="text"||a==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:A,config:t,request:w};we(function(F){r(F),y()},function(F){o(F),y()},R),w=null}"onloadend"in w?w.onloadend=v:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(v)},w.onabort=function(){w&&(o(new T("Request aborted",T.ECONNABORTED,t,w)),w=null)},w.onerror=function(x){let R=x&&x.message?x.message:"Network Error",j=new T(R,T.ERR_NETWORK,t,w);j.event=x||null,o(j),w=null},w.ontimeout=function(){let x=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",R=i.transitional||nt;i.timeoutErrorMessage&&(x=i.timeoutErrorMessage),o(new T(x,R.clarifyTimeoutError?T.ETIMEDOUT:T.ECONNABORTED,t,w)),w=null},n===void 0&&s.setContentType(null),"setRequestHeader"in w&&d.forEach(s.toJSON(),function(x,R){w.setRequestHeader(R,x)}),d.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),a&&a!=="json"&&(w.responseType=i.responseType),l&&([g,f]=Ee(l,!0),w.addEventListener("progress",g)),c&&w.upload&&([p,b]=Ee(c),w.upload.addEventListener("progress",p),w.upload.addEventListener("loadend",b)),(i.cancelToken||i.signal)&&(u=A=>{w&&(o(!A||A.type?new ne(null,t,w):A),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));let D=Ot(i.url);if(D&&L.protocols.indexOf(D)===-1){o(new T("Unsupported protocol "+D+":",T.ERR_BAD_REQUEST,t));return}w.send(n||null)})};var Yc=(t,e)=>{let{length:r}=t=t?t.filter(Boolean):[];if(e||r){let o=new AbortController,i,n=function(l){if(!i){i=!0,a();let u=l instanceof Error?l:this.reason;o.abort(u instanceof T?u:new ne(u instanceof Error?u.message:u))}},s=e&&setTimeout(()=>{s=null,n(new T(`timeout ${e} of ms exceeded`,T.ETIMEDOUT))},e),a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(n):l.removeEventListener("abort",n)}),t=null)};t.forEach(l=>l.addEventListener("abort",n));let{signal:c}=o;return c.unsubscribe=()=>d.asap(a),c}},ys=Yc;var Xc=function*(t,e){let r=t.byteLength;if(!e||r<e){yield t;return}let o=0,i;for(;o<r;)i=o+e,yield t.slice(o,i),o=i},eu=async function*(t,e){for await(let r of tu(t))yield*Xc(r,e)},tu=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}let e=t.getReader();try{for(;;){let{done:r,value:o}=await e.read();if(r)break;yield o}}finally{await e.cancel()}},wo=(t,e,r,o)=>{let i=eu(t,e),n=0,s,a=c=>{s||(s=!0,o&&o(c))};return new ReadableStream({async pull(c){try{let{done:l,value:u}=await i.next();if(l){a(),c.close();return}let p=u.byteLength;if(r){let g=n+=p;r(g)}c.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}},cancel(c){return a(c),i.return()}},{highWaterMark:2})};var ws=64*1024,{isFunction:gr}=d,_s=(({fetch:t,Request:e,Response:r})=>({fetch:t,Request:e,Response:r}))(d.global),{ReadableStream:Ts,TextEncoder:As}=d.global,Es=(t,...e)=>{try{return!!t(...e)}catch{return!1}},ru=t=>{let{fetch:e,Request:r,Response:o}=Object.assign({},_s,t),i=gr(e),n=gr(r),s=gr(o);if(!i)return!1;let a=i&&gr(Ts),c=i&&(typeof As=="function"?(f=>y=>f.encode(y))(new As):async f=>new Uint8Array(await new r(f).arrayBuffer())),l=n&&a&&Es(()=>{let f=!1,y=new r(L.origin,{body:new Ts,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!y}),u=s&&a&&Es(()=>d.isReadableStream(new o("").body)),p={stream:u&&(f=>f.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!p[f]&&(p[f]=(y,w)=>{let v=y&&y[f];if(v)return v.call(y);throw new T(`Response type '${f}' is not supported`,T.ERR_NOT_SUPPORT,w)})});let g=async f=>{if(f==null)return 0;if(d.isBlob(f))return f.size;if(d.isSpecCompliantForm(f))return(await new r(L.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(d.isArrayBufferView(f)||d.isArrayBuffer(f))return f.byteLength;if(d.isURLSearchParams(f)&&(f=f+""),d.isString(f))return(await c(f)).byteLength},b=async(f,y)=>{let w=d.toFiniteNumber(f.getContentLength());return w??g(y)};return async f=>{let{url:y,method:w,data:v,signal:D,cancelToken:A,timeout:x,onDownloadProgress:R,onUploadProgress:j,responseType:F,headers:ae,withCredentials:pe="same-origin",fetchOptions:Ae}=hr(f);F=F?(F+"").toLowerCase():"text";let _e=ys([D,A&&A.toAbortSignal()],x),se=null,le=_e&&_e.unsubscribe&&(()=>{_e.unsubscribe()}),$;try{if(j&&l&&w!=="get"&&w!=="head"&&($=await b(ae,v))!==0){let K=new r(y,{method:"POST",body:v,duplex:"half"}),U;if(d.isFormData(v)&&(U=K.headers.get("content-type"))&&ae.setContentType(U),K.body){let[te,me]=ct($,Ee(ut(j)));v=wo(K.body,ws,te,me)}}d.isString(pe)||(pe=pe?"include":"omit");let J=n&&"credentials"in r.prototype,Se={...Ae,signal:_e,method:w.toUpperCase(),headers:ae.normalize().toJSON(),body:v,duplex:"half",credentials:J?pe:void 0};se=n&&new r(y,Se);let S=await(n?e(se,Ae):e(y,Se)),_=u&&(F==="stream"||F==="response");if(u&&(R||_&&le)){let K={};["status","statusText","headers"].forEach(Y=>{K[Y]=S[Y]});let U=d.toFiniteNumber(S.headers.get("content-length")),[te,me]=R&&ct(U,Ee(ut(R),!0))||[];S=new o(wo(S.body,ws,te,()=>{me&&me(),le&&le()}),K)}F=F||"text";let z=await p[d.findKey(p,F)||"text"](S,f);return!_&&le&&le(),await new Promise((K,U)=>{we(K,U,{data:z,headers:V.from(S.headers),status:S.status,statusText:S.statusText,config:f,request:se})})}catch(J){throw le&&le(),J&&J.name==="TypeError"&&/Load failed|fetch/i.test(J.message)?Object.assign(new T("Network Error",T.ERR_NETWORK,f,se),{cause:J.cause||J}):T.from(J,J&&J.code,f,se)}}},ou=new Map,To=t=>{let e=d.merge.call({skipUndefined:!0},_s,t?t.env:null),{fetch:r,Request:o,Response:i}=e,n=[o,i,r],s=n.length,a=s,c,l,u=ou;for(;a--;)c=n[a],l=u.get(c),l===void 0&&u.set(c,l=a?new Map:ru(e)),u=l;return l},zb=To();var Ao={http:ms,xhr:bs,fetch:{get:To}};d.forEach(Ao,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var Ss=t=>`- ${t}`,su=t=>d.isFunction(t)||t===null||t===!1,br={getAdapter:(t,e)=>{t=d.isArray(t)?t:[t];let{length:r}=t,o,i,n={};for(let s=0;s<r;s++){o=t[s];let a;if(i=o,!su(o)&&(i=Ao[(a=String(o)).toLowerCase()],i===void 0))throw new T(`Unknown adapter '${a}'`);if(i&&(d.isFunction(i)||(i=i.get(e))))break;n[a||"#"+s]=i}if(!i){let s=Object.entries(n).map(([c,l])=>`adapter ${c} `+(l===!1?"is not supported by the environment":"is not available in the build")),a=r?s.length>1?`since :
|
|
9
|
+
`+s.map(Ss).join(`
|
|
10
|
+
`):" "+Ss(s[0]):"as no adapter specified";throw new T("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i},adapters:Ao};function Eo(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ne(null,t)}function yr(t){return Eo(t),t.headers=V.from(t.headers),t.data=Dt.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),br.getAdapter(t.adapter||at.adapter,t)(t).then(function(o){return Eo(t),o.data=Dt.call(t,t.transformResponse,o),o.headers=V.from(o.headers),o},function(o){return Lt(o)||(Eo(t),o&&o.response&&(o.response.data=Dt.call(t,t.transformResponse,o.response),o.response.headers=V.from(o.response.headers))),Promise.reject(o)})}var wr={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{wr[t]=function(o){return typeof o===t||"a"+(e<1?"n ":" ")+t}});var vs={};wr.transitional=function(e,r,o){function i(n,s){return"[Axios v"+ze+"] Transitional option '"+n+"'"+s+(o?". "+o:"")}return(n,s,a)=>{if(e===!1)throw new T(i(s," has been removed"+(r?" in "+r:"")),T.ERR_DEPRECATED);return r&&!vs[s]&&(vs[s]=!0,console.warn(i(s," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(n,s,a):!0}};wr.spelling=function(e){return(r,o)=>(console.warn(`${o} is likely a misspelling of ${e}`),!0)};function nu(t,e,r){if(typeof t!="object")throw new T("options must be an object",T.ERR_BAD_OPTION_VALUE);let o=Object.keys(t),i=o.length;for(;i-- >0;){let n=o[i],s=e[n];if(s){let a=t[n],c=a===void 0||s(a,n,t);if(c!==!0)throw new T("option "+n+" must be "+c,T.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new T("Unknown option "+n,T.ERR_BAD_OPTION)}}var Nt={assertOptions:nu,validators:wr};var Te=Nt.validators,pt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new to,response:new to}}async request(e,r){try{return await this._request(e,r)}catch(o){if(o instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;let n=i.stack?i.stack.replace(/^.+\n/,""):"";try{o.stack?n&&!String(o.stack).endsWith(n.replace(/^.+\n.+\n/,""))&&(o.stack+=`
|
|
11
|
+
`+n):o.stack=n}catch{}}throw o}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=ge(this.defaults,r);let{transitional:o,paramsSerializer:i,headers:n}=r;o!==void 0&&Nt.assertOptions(o,{silentJSONParsing:Te.transitional(Te.boolean),forcedJSONParsing:Te.transitional(Te.boolean),clarifyTimeoutError:Te.transitional(Te.boolean)},!1),i!=null&&(d.isFunction(i)?r.paramsSerializer={serialize:i}:Nt.assertOptions(i,{encode:Te.function,serialize:Te.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Nt.assertOptions(r,{baseUrl:Te.spelling("baseURL"),withXsrfToken:Te.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=n&&d.merge(n.common,n[r.method]);n&&d.forEach(["delete","get","head","post","put","patch","common"],f=>{delete n[f]}),r.headers=V.concat(s,n);let a=[],c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});let l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let u,p=0,g;if(!c){let f=[yr.bind(this),void 0];for(f.unshift(...a),f.push(...l),g=f.length,u=Promise.resolve(r);p<g;)u=u.then(f[p++],f[p++]);return u}g=a.length;let b=r;for(p=0;p<g;){let f=a[p++],y=a[p++];try{b=f(b)}catch(w){y.call(this,w);break}}try{u=yr.call(this,b)}catch(f){return Promise.reject(f)}for(p=0,g=l.length;p<g;)u=u.then(l[p++],l[p++]);return u}getUri(e){e=ge(this.defaults,e);let r=Be(e.baseURL,e.url,e.allowAbsoluteUrls);return Ve(r,e.params,e.paramsSerializer)}};d.forEach(["delete","get","head","options"],function(e){pt.prototype[e]=function(r,o){return this.request(ge(o||{},{method:e,url:r,data:(o||{}).data}))}});d.forEach(["post","put","patch"],function(e){function r(o){return function(n,s,a){return this.request(ge(a||{},{method:e,headers:o?{"Content-Type":"multipart/form-data"}:{},url:n,data:s}))}}pt.prototype[e]=r(),pt.prototype[e+"Form"]=r(!0)});var Ft=pt;var _o=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(n){r=n});let o=this;this.promise.then(i=>{if(!o._listeners)return;let n=o._listeners.length;for(;n-- >0;)o._listeners[n](i);o._listeners=null}),this.promise.then=i=>{let n,s=new Promise(a=>{o.subscribe(a),n=a}).then(i);return s.cancel=function(){o.unsubscribe(n)},s},e(function(n,s,a){o.reason||(o.reason=new ne(n,s,a),r(o.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=o=>{e.abort(o)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(i){e=i}),cancel:e}}},Cs=_o;function So(t){return function(r){return t.apply(null,r)}}function vo(t){return d.isObject(t)&&t.isAxiosError===!0}var Co={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(Co).forEach(([t,e])=>{Co[e]=t});var Rs=Co;function xs(t){let e=new Ft(t),r=Rt(Ft.prototype.request,e);return d.extend(r,Ft.prototype,e,{allOwnKeys:!0}),d.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return xs(ge(t,i))},r}var G=xs(at);G.Axios=Ft;G.CanceledError=ne;G.CancelToken=Cs;G.isCancel=Lt;G.VERSION=ze;G.toFormData=Ce;G.AxiosError=T;G.Cancel=G.CanceledError;G.all=function(e){return Promise.all(e)};G.spread=So;G.isAxiosError=vo;G.mergeConfig=ge;G.AxiosHeaders=V;G.formToJSON=t=>pr(d.isHTMLForm(t)?new FormData(t):t);G.getAdapter=br.getAdapter;G.HttpStatusCode=Rs;G.default=G;var Is=G;var{Axios:qy,AxiosError:jy,CanceledError:Vy,isCancel:By,CancelToken:zy,VERSION:Wy,all:Hy,Cancel:Gy,isAxiosError:xe,spread:$y,toFormData:Qy,AxiosHeaders:Ky,HttpStatusCode:Jy,formToJSON:Zy,getAdapter:Yy,mergeConfig:Xy}=Is;import{makeApi as gu,makeEndpoint as mt}from"@zodios/core";import{z as M}from"zod";import{z as h}from"zod";var au=h.object({name:h.string(),description:h.string(),id:h.string(),schema_version:h.string(),metric_version:h.coerce.number(),definition_version:h.coerce.number(),last_updated_user:h.object({id:h.string()}).optional()}),lu=h.object({id:h.string()}),ks=h.object({field:h.string(),operator:h.string(),categorical_values:h.array(h.object({string_value:h.string().optional(),bool_value:h.boolean().optional(),null_value:h.string().optional()}))}),Tr=h.object({measure:h.object({field:h.string(),aggregation:h.string()}),time_dimension:h.object({field:h.string()}),filters:h.array(ks)}),cu=h.object({datasource:lu,basic_specification:Tr.optional(),viz_state_specification:h.object({viz_state_string:h.string()}).optional(),is_running_total:h.boolean()}),Ps=h.object({allowed_dimensions:h.array(h.string()),allowed_granularities:h.array(h.string()),offset_from_today:h.number()}),Ds=h.object({filters:h.array(ks),measurement_period:h.object({granularity:h.string(),range:h.string()}),comparison:h.object({comparison:h.string()})}),Ls=h.object({target:h.object({value:h.number()}).optional()}),Ar=h.object({id:h.string(),specification:Ds,definition_id:h.string(),is_default:h.boolean(),schema_version:h.string(),metric_version:h.coerce.number(),goals:Ls.optional(),is_followed:h.boolean(),datasource_luid:h.string()}),Os=h.object({type:h.string(),number_units:h.object({singular_noun:h.string(),plural_noun:h.string()}),sentiment_type:h.string(),row_level_id_field:h.object({identifier_col:h.string()}),row_level_entity_names:h.object({entity_name_singular:h.string().optional(),entity_name_plural:h.string().optional()}),row_level_name_field:h.object({name_col:h.string()}),currency_code:h.string()}),Ms=h.object({settings:h.array(h.object({type:h.string(),disabled:h.boolean()}))}),uu=h.object({comparisons:h.array(h.object({compare_config:h.object({comparison:h.string()}),index:h.coerce.number()}))}),du=h.array(h.object({basic_specification:Tr.optional(),threshold_basic_specification:Tr.optional(),threshold_viz_state_specification:h.object({viz_state_string:h.string()}).optional(),viz_state_specification:h.object({viz_state_string:h.string()}).optional(),minimum_granularity:h.string(),benchmark_sentiment_type:h.string(),name:h.string()})),Ro=h.object({metadata:au,specification:cu,extension_options:Ps,metrics:h.array(Ar),total_metrics:h.coerce.number(),representation_options:Os,insights_options:Ms,comparisons:uu,datasource_goals:du}),Ns=h.object({id:h.string(),metric_id:h.string()}),pu=h.enum(["LANGUAGE_UNSPECIFIED","LANGUAGE_DE_DE","LANGUAGE_EN_US","LANGUAGE_EN_GB","LANGUAGE_ES_ES","LANGUAGE_FR_FR","LANGUAGE_FR_CA","LANGUAGE_GA_IE","LANGUAGE_IT_IT","LANGUAGE_JA_JP","LANGUAGE_KO_KR","LANGUAGE_NL_NL","LANGUAGE_PT_BR","LANGUAGE_SV_SE","LANGUAGE_TH_TH","LANGUAGE_ZH_CN","LANGUAGE_ZH_TW"]),mu=h.enum(["LOCALE_UNSPECIFIED","LOCALE_AR_AE","LOCALE_AR_BH","LOCALE_AR_DZ","LOCALE_AR_EG","LOCALE_AR_IQ","LOCALE_AR_JO","LOCALE_AR_KW","LOCALE_AR_LB","LOCALE_AR_LY","LOCALE_AR_MA","LOCALE_AR_OM","LOCALE_AR_QA","LOCALE_AR_SA","LOCALE_AR_SD","LOCALE_AR_SY","LOCALE_AR_TN","LOCALE_AR_YE","LOCALE_BE_BY","LOCALE_BG_BG","LOCALE_CA_ES","LOCALE_CS_CZ","LOCALE_DA_DK","LOCALE_DE_AT","LOCALE_DE_CH","LOCALE_DE_DE","LOCALE_DE_LU","LOCALE_EL_CY","LOCALE_EL_GR","LOCALE_EN_AU","LOCALE_EN_CA","LOCALE_EN_GB","LOCALE_EN_IE","LOCALE_EN_IN","LOCALE_EN_MT","LOCALE_EN_NZ","LOCALE_EN_PH","LOCALE_EN_SG","LOCALE_EN_US","LOCALE_EN_ZA","LOCALE_ES_AR","LOCALE_ES_BO","LOCALE_ES_CL","LOCALE_ES_CO","LOCALE_ES_CR","LOCALE_ES_DO","LOCALE_ES_EC","LOCALE_ES_ES","LOCALE_ES_GT","LOCALE_ES_HN","LOCALE_ES_MX","LOCALE_ES_NI","LOCALE_ES_PA","LOCALE_ES_PE","LOCALE_ES_PR","LOCALE_ES_PY","LOCALE_ES_SV","LOCALE_ES_US","LOCALE_ES_UY","LOCALE_ES_VE","LOCALE_ET_EE","LOCALE_FI_FI","LOCALE_FR_BE","LOCALE_FR_CA","LOCALE_FR_CH","LOCALE_FR_FR","LOCALE_FR_LU","LOCALE_GA_IE","LOCALE_HE_IL","LOCALE_HI_IN","LOCALE_HR_HR","LOCALE_HU_HU","LOCALE_ID_ID","LOCALE_IN_ID","LOCALE_IS_IS","LOCALE_IT_CH","LOCALE_IT_IT","LOCALE_IW_IL","LOCALE_JA_JP","LOCALE_KO_KR","LOCALE_LT_LT","LOCALE_LV_LV","LOCALE_MK_MK","LOCALE_MS_MY","LOCALE_MT_MT","LOCALE_NL_BE","LOCALE_NL_NL","LOCALE_NB_NO","LOCALE_NO_NO","LOCALE_PL_PL","LOCALE_PT_BR","LOCALE_PT_PT","LOCALE_RO_RO","LOCALE_RU_RU","LOCALE_SK_SK","LOCALE_SL_SI","LOCALE_SQ_AL","LOCALE_SR_BA","LOCALE_SR_ME","LOCALE_SR_RS","LOCALE_SV_SE","LOCALE_TH_TH","LOCALE_TR_TR","LOCALE_UK_UA","LOCALE_VI_VN","LOCALE_ZH_CN","LOCALE_ZH_HK","LOCALE_ZH_SG","LOCALE_ZH_TW"]),fu=h.enum(["OUTPUT_FORMAT_UNSPECIFIED","OUTPUT_FORMAT_HTML","OUTPUT_FORMAT_TEXT"]),Er=h.object({bundle_request:h.object({version:h.number(),options:h.object({output_format:fu,time_zone:h.string(),language:pu,locale:mu}),input:h.object({metadata:h.object({name:h.string().nonempty(),metric_id:h.string().nonempty(),definition_id:h.string().nonempty()}),metric:h.object({definition:h.object({datasource:h.object({id:h.string()}),basic_specification:Tr,is_running_total:h.boolean()}),metric_specification:Ds,extension_options:Ps,representation_options:Os,insights_options:Ms,goals:Ls.optional()})})})}),hu=h.object({type:h.string(),insights:h.array(h.object({result:h.object({type:h.string(),version:h.number(),content:h.string().optional(),markup:h.string().optional(),viz:h.any().optional(),facts:h.any().optional(),characterization:h.string().optional(),question:h.string(),score:h.number()}),insight_type:h.string()})),summaries:h.array(h.object({result:h.object({id:h.string(),markup:h.string().optional(),viz:h.any().optional(),generation_id:h.string(),timestamp:h.string().optional(),last_attempted_timestamp:h.string().optional()})}))}),Fs=h.object({bundle_response:h.object({result:h.object({insight_groups:h.array(hu),has_errors:h.boolean(),characterization:h.string()})})}),_r=["ban","springboard","basic","detail"],He=["DEFINITION_VIEW_BASIC","DEFINITION_VIEW_FULL","DEFINITION_VIEW_DEFAULT"];var bu=mt({method:"get",path:"/pulse/definitions",alias:"listAllPulseMetricDefinitions",description:"Returns a list of all published Pulse Metric Definitions on the specified site.",parameters:[{name:"view",type:"Query",schema:M.optional(M.enum(He)),description:`The range of metrics to return for a definition. The default is 'DEFINITION_VIEW_BASIC' if not specified.
|
|
12
12
|
- 'DEFINITION_VIEW_BASIC' - Return only the specified metric definition.
|
|
13
13
|
- 'DEFINITION_VIEW_FULL' - Return the metric definition and the specified number of metrics.
|
|
14
|
-
- 'DEFINITION_VIEW_DEFAULT' - Return the metric definition and the default metric.`}],response:
|
|
14
|
+
- 'DEFINITION_VIEW_DEFAULT' - Return the metric definition and the default metric.`},{name:"page_size",type:"Query",schema:M.optional(M.coerce.number().int().positive()),description:"Specifies the number of results in a paged response."},{name:"page_token",type:"Query",schema:M.optional(M.string()),description:"Token for retrieving the next page of results. Omit for the first page."}],response:M.object({definitions:M.array(Ro),next_page_token:M.string().optional(),offset:M.coerce.number(),total_available:M.coerce.number()})}),yu=mt({method:"post",path:"/pulse/definitions%3AbatchGet",alias:"listPulseMetricDefinitionsFromMetricDefinitionIds",description:"Returns a list of published Pulse Metric Definitions from a list of metric definition IDs.",parameters:[{name:"definition_ids",type:"Body",schema:M.object({definition_ids:M.array(M.string().nonempty()).min(1)}),description:"A list of metric definition IDs to retrieve."},{name:"view",type:"Query",schema:M.optional(M.enum(He)),description:`The range of metrics to return for a definition. The default is 'DEFINITION_VIEW_BASIC' if not specified.
|
|
15
15
|
- 'DEFINITION_VIEW_BASIC' - Return only the specified metric definition.
|
|
16
16
|
- 'DEFINITION_VIEW_FULL' - Return the metric definition and the specified number of metrics.
|
|
17
|
-
- 'DEFINITION_VIEW_DEFAULT' - Return the metric definition and the default metric.`}],response:k.object({definitions:k.array(Jr)})}),$l=Ye({method:"get",path:"/pulse/definitions/:pulseMetricDefinitionID/metrics",alias:"listPulseMetricsFromMetricDefinitionId",description:"Returns a list of published Pulse Metrics for a specific Pulse Metric Definition.",parameters:[{name:"pulseMetricDefinitionID",type:"Path",schema:k.string().nonempty()}],response:k.object({metrics:k.array(Yt),total_available:k.number()})}),Zl=Ye({method:"post",path:"/pulse/metrics%3AbatchGet",alias:"listPulseMetricsFromMetricIds",description:"Returns a list of Pulse Metrics for a list of metric IDs.",parameters:[{name:"metric_ids",type:"Body",schema:k.object({metric_ids:k.array(k.string().nonempty())})}],response:k.object({metrics:k.array(Yt)})}),Jl=Ye({method:"get",path:"/pulse/subscriptions",alias:"listPulseMetricSubscriptionsForCurrentUser",description:"Returns a list of Pulse Subscriptions for the current user.",parameters:[{name:"user_id",type:"Query",schema:k.string().nonempty()}],response:k.object({subscriptions:k.array(Go)})}),Kl=Ye({method:"post",path:"/pulse/insights/:bundle_type",alias:"generatePulseMetricValueInsightBundle",description:"Generates a bundle for the current aggregated value for the Pulse metric.",parameters:[{name:"bundle_request",type:"Body",schema:Xt},{name:"bundle_type",type:"Path",schema:k.enum(er)}],response:Qo}),Yl=Hl([Kl,Gl,Ql,$l,Jl,Zl]),$o=[...Yl];var Et=class extends W{constructor(e,r){super(new Xl(e,$o),r)}listAllPulseMetricDefinitions=async e=>await Xe(async()=>(await this._apiClient.listAllPulseMetricDefinitions({queries:{view:e},...this.authHeader})).definitions??[]);listPulseMetricDefinitionsFromMetricDefinitionIds=async(e,r)=>await Xe(async()=>(await this._apiClient.listPulseMetricDefinitionsFromMetricDefinitionIds({definition_ids:e},{queries:{view:r},...this.authHeader})).definitions??[]);listPulseMetricsFromMetricDefinitionId=async e=>await Xe(async()=>(await this._apiClient.listPulseMetricsFromMetricDefinitionId({params:{pulseMetricDefinitionID:e},...this.authHeader})).metrics??[]);listPulseMetricsFromMetricIds=async e=>await Xe(async()=>(await this._apiClient.listPulseMetricsFromMetricIds({metric_ids:e},{...this.authHeader})).metrics??[]);listPulseMetricSubscriptionsForCurrentUser=async()=>await Xe(async()=>(await this._apiClient.listPulseMetricSubscriptionsForCurrentUser({queries:{user_id:this.userId},...this.authHeader})).subscriptions??[]);generatePulseMetricValueInsightBundle=async(e,r)=>await Xe(async()=>await this._apiClient.generatePulseMetricValueInsightBundle({bundle_request:e.bundle_request},{params:{bundle_type:r},...this.authHeader})??{})};async function Xe(t){try{return new ec(await t())}catch(e){if(Ke(e)){if(e.response?.status===404)return new Zo("tableau-server");if(e.response?.status===400&&e.response.headers.tableau_error_code==="0xd3408984"&&e.response.headers.validation_code==="400999")return new Zo("pulse-disabled")}throw e}}import{Zodios as ac}from"@zodios/core";import{makeApi as tc,makeEndpoint as tr}from"@zodios/core";import{z as K}from"zod";import{z as H}from"zod";var At=H.object({id:H.string(),name:H.string(),createdAt:H.string(),updatedAt:H.string(),workbook:H.object({id:H.string()}).optional(),owner:H.object({id:H.string()}).optional(),project:H.object({id:H.string()}).optional(),tags:H.object({tag:H.array(H.object({label:H.string()})).optional()}),usage:H.object({totalViewCount:H.coerce.number()}).optional()});var rc=tr({method:"get",path:"/sites/:siteId/views/:viewId/data",alias:"queryViewData",description:"Returns a specified view rendered as data in comma separated value (CSV) format.",response:K.string()}),ic=tr({method:"get",path:"/sites/:siteId/views/:viewId/image",alias:"queryViewImage",description:"Returns an image of the specified view.",parameters:[{name:"vizWidth",type:"Query",schema:K.number().optional(),description:"The width of the rendered image in pixels that, along with the value of vizHeight determine its resolution and aspect ratio."},{name:"vizHeight",type:"Query",schema:K.number().optional(),description:"The height of the rendered image in pixels that, along with the value of vizWidth determine its resolution and aspect ratio."},{name:"resolution",type:"Query",schema:K.literal("high").optional(),description:"The resolution of the image. Image width and actual pixel density are determined by the display context of the image. Aspect ratio is always preserved. Set the value to high to ensure maximum pixel density."}],response:K.string()}),oc=tr({method:"get",path:"/sites/:siteId/workbooks/:workbookId/views",alias:"queryViewsForWorkbook",description:"Returns all the views for the specified workbook, optionally including usage statistics.",parameters:[{name:"includeUsageStatistics",type:"Query",schema:K.boolean().optional(),description:"true to return usage statistics. The default is false."}],response:K.object({views:K.object({view:K.array(At)})})}),sc=tr({method:"get",path:"/sites/:siteId/views",alias:"queryViewsForSite",description:"Returns all the views for the specified site, optionally including usage statistics.",parameters:[...Ue,{name:"includeUsageStatistics",type:"Query",schema:K.boolean().optional(),description:"true to return usage statistics. The default is false."},{name:"filter",type:"Query",schema:K.string().optional(),description:"An expression that lets you specify a subset of views to return. You can filter on predefined fields such as name, tags, and createdAt. You can include multiple filter expressions."}],response:K.object({pagination:qe,views:K.object({view:K.array(At).optional()})})}),nc=tc([rc,ic,oc,sc]),Jo=[...nc];var St=class extends W{constructor(e,r){super(new ac(e,Jo),r)}queryViewData=async({viewId:e,siteId:r})=>await this._apiClient.queryViewData({params:{siteId:r,viewId:e},...this.authHeader});queryViewImage=async({viewId:e,siteId:r,width:i,height:o,resolution:n})=>await this._apiClient.queryViewImage({params:{siteId:r,viewId:e},queries:{vizWidth:i,vizHeight:o,resolution:n},...this.authHeader,responseType:"arraybuffer"});queryViewsForWorkbook=async({workbookId:e,siteId:r,includeUsageStatistics:i})=>(await this._apiClient.queryViewsForWorkbook({params:{siteId:r,workbookId:e},queries:{includeUsageStatistics:i},...this.authHeader})).views.view;queryViewsForSite=async({siteId:e,includeUsageStatistics:r,filter:i,pageSize:o,pageNumber:n})=>{let s=await this._apiClient.queryViewsForSite({params:{siteId:e},queries:{includeUsageStatistics:r,filter:i,pageSize:o,pageNumber:n},...this.authHeader});return{pagination:s.pagination,views:s.views.view??[]}}};import{isErrorFromAlias as os,Zodios as Lc,ZodiosError as Dc}from"@zodios/core";import{Err as ir,Ok as ss}from"ts-results-es";import{makeApi as lc}from"@zodios/core";import{z as d}from"zod";var cc=d.object({connectionLuid:d.string().optional(),connectionUsername:d.string(),connectionPassword:d.string()}),Ko=d.object({datasourceLuid:d.string().nonempty(),connections:d.array(cc).optional()}),uc=d.enum(["OBJECTS","ARRAYS"]),Yo=d.object({returnFormat:uc,debug:d.boolean().default(!1)}).partial().passthrough(),dc=d.object({datasource:Ko,options:Yo.optional()}).passthrough(),Xr=d.enum(["SUM","AVG","MEDIAN","COUNT","COUNTD","MIN","MAX","STDEV","VAR","COLLECT","YEAR","QUARTER","MONTH","WEEK","DAY","TRUNC_YEAR","TRUNC_QUARTER","TRUNC_MONTH","TRUNC_WEEK","TRUNC_DAY","AGG","NONE","UNSPECIFIED"]),Xo=d.enum(["INTEGER","REAL","STRING","DATETIME","BOOLEAN","DATE","SPATIAL","UNKNOWN"]),es=d.enum(["MINUTES","HOURS","DAYS","WEEKS","MONTHS","QUARTERS","YEARS"]),pc=d.object({fieldName:d.string(),fieldCaption:d.string(),dataType:Xo,defaultAggregation:Xr,columnClass:d.enum(["COLUMN","BIN","GROUP","CALCULATION","TABLE_CALCULATION"]),formula:d.string(),logicalTableId:d.string()}).partial().passthrough(),ts=d.union([d.number(),d.string(),d.boolean(),d.null()]),rr=d.object({parameterCaption:d.string(),dataType:Xo.exclude(["DATETIME","SPATIAL","UNKNOWN"]),parameterName:d.string().optional(),value:ts}),mc=d.discriminatedUnion("parameterType",[rr.extend({parameterType:d.literal("ANY_VALUE")}).strict(),rr.extend({parameterType:d.literal("LIST"),members:d.array(ts)}).strict(),rr.extend({parameterType:d.literal("QUANTITATIVE_DATE"),value:d.string().nullable(),minDate:d.string().nullish(),maxDate:d.string().nullish(),periodValue:d.number().nullish(),periodType:es.nullish()}).strict(),rr.extend({parameterType:d.literal("QUANTITATIVE_RANGE"),value:d.number().nullable(),min:d.number().nullish(),max:d.number().nullish(),step:d.number().nullish()}).strict()]),fc=d.object({data:d.array(pc),extraData:d.object({parameters:d.array(mc)})}).partial().passthrough(),hc=d.object({errorCode:d.string(),message:d.string(),datetime:d.string().datetime({offset:!0}),debug:d.object({}).partial().passthrough(),"tab-error-code":d.string()}).partial().passthrough(),gc=d.enum(["ASC","DESC"]),Kr=d.object({fieldCaption:d.string(),fieldAlias:d.string().optional(),maxDecimalPlaces:d.number().int().optional(),sortDirection:gc.optional(),sortPriority:d.number().int().optional()}),yc=d.union([Kr.strict(),Kr.extend({function:Xr}).strict(),Kr.extend({calculation:d.string()}).strict()]),rs=d.union([d.object({fieldCaption:d.string()}).strict(),d.object({fieldCaption:d.string(),function:Xr}).strict(),d.object({calculation:d.string()}).strict()]),ei=d.object({field:rs,context:d.boolean().optional()}),ti=d.object({field:d.object({fieldCaption:d.string()}).strict(),context:d.boolean().optional()}),bc=ti.extend({filterType:d.literal("SET"),values:d.union([d.array(d.string()),d.array(d.number()),d.array(d.boolean())]),exclude:d.boolean().optional()}),et=ti.extend({filterType:d.literal("DATE"),periodType:es,anchorDate:d.string().optional(),includeNulls:d.boolean().optional()}),Tc=d.discriminatedUnion("dateRangeType",[et.extend({dateRangeType:d.literal("CURRENT")}).strict(),et.extend({dateRangeType:d.literal("LAST")}).strict(),et.extend({dateRangeType:d.literal("NEXT")}).strict(),et.extend({dateRangeType:d.literal("TODATE")}).strict(),et.extend({dateRangeType:d.literal("LASTN"),rangeN:d.number().int()}).strict(),et.extend({dateRangeType:d.literal("NEXTN"),rangeN:d.number().int()}).strict()]),Yr=ti.extend({filterType:d.literal("MATCH"),startsWith:d.string().optional(),endsWith:d.string().optional(),contains:d.string().optional(),exclude:d.boolean().optional()}),wc=d.union([Yr.extend({startsWith:d.string()}).strict(),Yr.extend({endsWith:d.string()}).strict(),Yr.extend({contains:d.string()}).strict()]),_t=ei.extend({filterType:d.literal("QUANTITATIVE_NUMERICAL")}),Ec=d.discriminatedUnion("quantitativeFilterType",[_t.extend({quantitativeFilterType:d.literal("RANGE"),min:d.number(),max:d.number(),includeNulls:d.boolean().optional()}).strict(),_t.extend({quantitativeFilterType:d.literal("MIN"),min:d.number(),includeNulls:d.boolean().optional()}).strict(),_t.extend({quantitativeFilterType:d.literal("MAX"),max:d.number(),includeNulls:d.boolean().optional()}).strict(),_t.extend({quantitativeFilterType:d.literal("ONLY_NULL")}).strict(),_t.extend({quantitativeFilterType:d.literal("ONLY_NON_NULL")}).strict()]),Ct=ei.extend({filterType:d.literal("QUANTITATIVE_DATE")}),Ac=d.discriminatedUnion("quantitativeFilterType",[Ct.extend({quantitativeFilterType:d.literal("RANGE"),minDate:d.string(),maxDate:d.string(),includeNulls:d.boolean().optional()}).strict(),Ct.extend({quantitativeFilterType:d.literal("MIN"),minDate:d.string(),includeNulls:d.boolean().optional()}).strict(),Ct.extend({quantitativeFilterType:d.literal("MAX"),maxDate:d.string(),includeNulls:d.boolean().optional()}).strict(),Ct.extend({quantitativeFilterType:d.literal("ONLY_NULL")}).strict(),Ct.extend({quantitativeFilterType:d.literal("ONLY_NON_NULL")}).strict()]),Sc=ei.extend({filterType:d.literal("TOP"),howMany:d.number().int(),fieldToMeasure:rs,direction:d.enum(["TOP","BOTTOM"]).optional().default("TOP")}),_c=d.union([bc.strict(),Sc.strict(),...wc.options,...Ec.options,...Ac.options,...Tc.options]),Rt=d.strictObject({fields:d.array(yc),filters:d.array(_c).optional()}),Cc=Yo.and(d.object({disaggregate:d.boolean()}).partial().passthrough()),Rc=d.object({datasource:Ko,query:Rt,options:Cc.optional()}).passthrough(),xc=d.object({data:d.array(d.unknown())}).partial().passthrough(),vc=lc([{method:"post",path:"/query-datasource",alias:"queryDatasource",description:"Queries a specific data source and returns the resulting data.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:Rc}],response:xc,errors:[{status:"default",schema:hc},{status:404,schema:d.any()}]},{method:"post",path:"/read-metadata",alias:"readMetadata",description:"Requests metadata for a specific data source. The metadata provides information about the data fields, such as field names, data types, and descriptions.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:dc}],response:fc,errors:[{status:404,schema:d.any()}]},{method:"get",path:"/simple-request",alias:"simpleRequest",description:"Sends a request that can be used for testing or doing a health check.",requestFormat:"json",response:d.string()}]),is=[...vc];var xt=class extends W{constructor(e,r){super(new Lc(e,is),r)}queryDatasource=async e=>{try{return ss(await this._apiClient.queryDatasource(e,{...this.authHeader}))}catch(r){if(os(this._apiClient.api,"queryDatasource",r))return r.response.status===404?ir("feature-disabled"):ir(r.response.data);if(r instanceof Dc)return ir(r);throw r}};readMetadata=async e=>{try{return ss(await this._apiClient.readMetadata(e,{...this.authHeader}))}catch(r){if(os(this._apiClient.api,"readMetadata",r)&&r.response.status===404)return ir("feature-disabled");throw r}}};import{Zodios as Fc}from"@zodios/core";import{makeApi as Ic,makeEndpoint as ns}from"@zodios/core";import{z as Oe}from"zod";import{z as Z}from"zod";var ri=Z.object({id:Z.string(),name:Z.string(),description:Z.string().optional(),webpageUrl:Z.string().optional(),contentUrl:Z.string(),project:kt.optional(),showTabs:Z.coerce.boolean(),defaultViewId:Z.string().optional(),tags:Z.object({tag:Z.array(Z.object({label:Z.string()})).optional()}),views:Z.optional(Z.object({view:Z.array(At)}))});var Oc=ns({method:"get",path:"/sites/:siteId/workbooks/:workbookId",alias:"getWorkbook",description:"Returns information about the specified workbook, including information about views and tags.",response:Oe.object({workbook:ri})}),Pc=ns({method:"get",path:"/sites/:siteId/workbooks",alias:"queryWorkbooksForSite",description:"Returns the workbooks on a site.",parameters:[...Ue,{name:"siteId",type:"Path",schema:Oe.string()},{name:"filter",type:"Query",schema:Oe.string().optional(),description:"An expression that lets you specify a subset of workbooks to return. You can filter on predefined fields such as name, tags, and createdAt. You can include multiple filter expressions."}],response:Oe.object({pagination:qe,workbooks:Oe.object({workbook:Oe.optional(Oe.array(ri))})})}),Nc=Ic([Pc,Oc]),as=[...Nc];var vt=class extends W{constructor(e,r){super(new Fc(e,as),r)}getWorkbook=async({workbookId:e,siteId:r})=>(await this._apiClient.getWorkbook({params:{siteId:r,workbookId:e},...this.authHeader})).workbook;queryWorkbooksForSite=async({siteId:e,filter:r,pageSize:i,pageNumber:o})=>{let n=await this._apiClient.queryWorkbooksForSite({params:{siteId:e},queries:{filter:r,pageSize:i,pageNumber:o},...this.authHeader});return{pagination:n.pagination,workbooks:n.workbooks.workbook??[]}}};var Lt=class t{_creds;_host;_baseUrl;_baseUrlWithoutVersion;_authenticationMethods;_authenticatedAuthenticationMethods;_contentExplorationMethods;_datasourcesMethods;_metadataMethods;_pulseMethods;_vizqlDataServiceMethods;_viewsMethods;_workbooksMethods;static _version="3.24";_requestInterceptor;_responseInterceptor;constructor(e,r){this._host=e,this._baseUrl=`${this._host}/api/${t._version}`,this._baseUrlWithoutVersion=`${this._host}/api/-`,this._requestInterceptor=r?.requestInterceptor,this._responseInterceptor=r?.responseInterceptor}get creds(){if(!this._creds)throw new Error("No credentials found. Authenticate by calling signIn() first.");return this._creds}get siteId(){return this.creds.site.id}get authenticationMethods(){return this._authenticationMethods||(this._authenticationMethods=new nt(this._baseUrl),this._addInterceptors(this._baseUrl,this._authenticationMethods.interceptors)),this._authenticationMethods}get authenticatedAuthenticationMethods(){return this._authenticatedAuthenticationMethods||(this._authenticatedAuthenticationMethods=new Ft(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._authenticatedAuthenticationMethods.interceptors)),this._authenticatedAuthenticationMethods}get contentExplorationMethods(){return this._contentExplorationMethods||(this._contentExplorationMethods=new at(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._contentExplorationMethods.interceptors)),this._contentExplorationMethods}get datasourcesMethods(){return this._datasourcesMethods||(this._datasourcesMethods=new lt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._datasourcesMethods.interceptors)),this._datasourcesMethods}get metadataMethods(){if(!this._metadataMethods){let e=`${this._host}/api/metadata`;this._metadataMethods=new ct(e,this.creds),this._addInterceptors(e,this._metadataMethods.interceptors)}return this._metadataMethods}get pulseMethods(){return this._pulseMethods||(this._pulseMethods=new Et(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._pulseMethods.interceptors)),this._pulseMethods}get vizqlDataServiceMethods(){if(!this._vizqlDataServiceMethods){let e=`${this._host}/api/v1/vizql-data-service`;this._vizqlDataServiceMethods=new xt(e,this.creds),this._addInterceptors(e,this._vizqlDataServiceMethods.interceptors)}return this._vizqlDataServiceMethods}get viewsMethods(){return this._viewsMethods||(this._viewsMethods=new St(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._viewsMethods.interceptors)),this._viewsMethods}get workbooksMethods(){return this._workbooksMethods||(this._workbooksMethods=new vt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._workbooksMethods.interceptors)),this._workbooksMethods}signIn=async e=>{this._creds=await this.authenticationMethods.signIn(e)};signOut=async()=>{await this.authenticatedAuthenticationMethods.signOut(),this._creds=void 0};_addInterceptors=(e,r)=>{r.request.use(i=>(this._requestInterceptor?.[0]({baseUrl:e,...Pt(i)}),i),i=>(this._requestInterceptor?.[1]?.(i,e),Promise.reject(i))),r.response.use(i=>(this._responseInterceptor?.[0]({baseUrl:e,...Nt(i)}),i),i=>(this._responseInterceptor?.[1]?.(i,e),Promise.reject(i)))}};var kc=async(t,e,r,i)=>{let o=new Lt(t.server,{requestInterceptor:[Mc(r,e),qc(r,e)],responseInterceptor:[Uc(r,e),jc(r,e)]});return t.auth==="pat"?await o.signIn({type:"pat",patName:t.patName,patValue:t.patValue,siteName:t.siteName}):t.auth==="direct-trust"&&await o.signIn({type:"direct-trust",siteName:t.siteName,username:Bc(t),clientId:t.connectedAppClientId,secretId:t.connectedAppSecretId,secretValue:t.connectedAppSecretValue,scopes:i,additionalPayload:Vc(t)}),o},P=async({config:t,requestId:e,server:r,callback:i,jwtScopes:o})=>{let n=await kc(t,e,r,new Set(o));try{return await i(n)}finally{await n.signOut()}},Mc=(t,e)=>r=>(r.headers["User-Agent"]=`${t.name}/${t.version}`,ls(t,r,e),r),qc=(t,e)=>(r,i)=>{if(!Ke(r)||!r.request){oe.error(t,`Request ${e} failed with error: ${ae(r)}`,{logger:"rest-api",requestId:e});return}let{request:o}=r;ls(t,{baseUrl:i,...Pt(o)},e)},Uc=(t,e)=>r=>(cs(t,r,e),r),jc=(t,e)=>(r,i)=>{if(!Ke(r)||!r.response){oe.error(t,`Response from request ${e} failed with error: ${ae(r)}`,{logger:"rest-api",requestId:e});return}let{response:o}=r;cs(t,{baseUrl:i,...Nt(o)},e)};function ls(t,e,r){let o=R().disableLogMasking?e:_i(e),n=new URL(o.url??"",o.baseUrl);e.params&&Object.keys(e.params).length>0&&(n.search=new URLSearchParams(e.params).toString());let s={type:"request",requestId:r,method:o.method,url:n.toString(),...Ae("debug")&&{headers:o.headers,data:o.data,params:o.params}};oe.info(t,s,{logger:"rest-api",requestId:r})}function cs(t,e,r){let o=R().disableLogMasking?e:Ci(e),n=new URL(o.url??"",o.baseUrl);e.request?.params&&Object.keys(e.request.params).length>0&&(n.search=new URLSearchParams(e.request.params).toString());let s={type:"response",requestId:r,url:n.toString(),status:o.status,...Ae("debug")&&{headers:o.headers,data:o.data}};oe.info(t,s,{logger:"rest-api",requestId:r})}function Bc(t){return t.jwtSubClaim}function Vc(t){let e=t.jwtAdditionalPayload;return JSON.parse(e||"{}")}import{ZodiosError as us}from"@zodios/core";import{fromError as zc,isZodErrorLike as Wc}from"zod-validation-error";var O=class{server;name;description;paramsSchema;annotations;argsValidator;callback;constructor({server:e,name:r,description:i,paramsSchema:o,annotations:n,argsValidator:s,callback:l}){this.server=e,this.name=r,this.description=i,this.paramsSchema=o,this.annotations=n,this.argsValidator=s,this.callback=l}logInvocation({requestId:e,args:r}){oe.debug(this.server,Ei({requestId:e,toolName:this.name,args:r}))}async logAndExecute({requestId:e,args:r,callback:i,getSuccessResult:o,getErrorText:n}){if(this.logInvocation({requestId:e,args:r}),r)try{this.argsValidator?.(r)}catch(s){return or(e,s)}try{let s=await i();return s.isOk()?o?o(s.value):{isError:!1,content:[{type:"text",text:JSON.stringify(s.value)}]}:s.error instanceof us?or(e,s.error):n?{isError:!0,content:[{type:"text",text:n(s.error)}]}:or(e,s.error)}catch(s){return or(e,s)}}};function or(t,e){if(e instanceof us&&Wc(e.cause)){let r=zc(e.cause);return{isError:!1,content:[{type:"text",text:JSON.stringify({data:e.data,warning:r.toString()})}]}}return{isError:!0,content:[{type:"text",text:`requestId: ${t}, error: ${ae(e)}`}]}}function ds(t){let e=new Set;return t.flatMap(r=>e.has(r.method)?[]:(e.add(r.method),r.method+(r.sortDirection?`:${r.sortDirection}`:""))).join(",")}function ps(t){let e=[];if(t.contentTypes)if(t.contentTypes.length===1)e.push(`type:eq:${t.contentTypes[0]}`);else{let r=new Set;for(let i of t.contentTypes)r.add(i);e.push(`type:in:[${Array.from(r).join(",")}]`)}if(t.ownerIds)if(t.ownerIds.length===1)e.push(`ownerId:eq:${t.ownerIds[0]}`);else{let r=new Set;for(let i of t.ownerIds)r.add(i);e.push(`ownerId:in:[${Array.from(r).join(",")}]`)}if(t.modifiedTime)if(Array.isArray(t.modifiedTime))if(t.modifiedTime.length===1)e.push(`modifiedTime:eq:${t.modifiedTime[0]}`);else{let r=new Set;for(let i of t.modifiedTime)r.add(i);e.push(`modifiedTime:in:[${Array.from(r).join(",")}]`)}else if(t.modifiedTime.startDate&&t.modifiedTime.endDate){let r=t.modifiedTime.startDate,i=t.modifiedTime.endDate;r>i&&(r=t.modifiedTime.endDate,i=t.modifiedTime.startDate),e.push(`modifiedTime:gte:${r}`),e.push(`modifiedTime:lte:${i}`)}else t.modifiedTime.startDate?e.push(`modifiedTime:gte:${t.modifiedTime.startDate}`):t.modifiedTime.endDate&&e.push(`modifiedTime:lte:${t.modifiedTime.endDate}`);return e.join(",")}function ms(t){let e=[];if(t.items)for(let r of t.items)e.push(Hc(r.content));return e}function Hc(t){let e={};return t.modifiedTime&&(e.modifiedTime=t.modifiedTime),t.sheetType&&(e.sheetType=t.sheetType),t.caption&&(e.caption=t.caption),t.workbookDescription&&(e.workbookDescription=t.workbookDescription),t.type&&(e.type=t.type),t.ownerId&&(e.ownerId=t.ownerId),t.title&&(e.title=t.title),t.ownerName&&(e.ownerName=t.ownerName),t.containerName&&(t.type==="view"?e.parentWorkbookName=t.containerName:e.containerName=t.containerName),t.luid&&(e.luid=t.luid),t.locationName&&(e.locationName=t.locationName),t.comments?.length&&(e.comments=t.comments),t.hitsTotal!=null&&(e.totalViewCount=t.hitsTotal),t.favoritesTotal!=null&&(e.favoritesTotal=t.favoritesTotal),t.tags?.length&&(e.tags=t.tags),t.projectName&&(e.projectName=t.projectName),t.hitsSmallSpanTotal!=null&&(e.viewCountLastMonth=t.hitsSmallSpanTotal),t.downstreamWorkbookCount!=null&&(e.downstreamWorkbookCount=t.downstreamWorkbookCount),t.isConnectable!=null&&(e.isConnectable=t.isConnectable),t.datasourceIsPublished!=null&&(e.datasourceIsPublished=t.datasourceIsPublished),t.connectionType&&(e.connectionType=t.connectionType),t.isCertified!=null&&(e.isCertified=t.isCertified),t.hasExtracts!=null&&(e.hasExtracts=t.hasExtracts),t.extractRefreshedAt&&(e.extractRefreshedAt=t.extractRefreshedAt),t.extractUpdatedAt&&(e.extractUpdatedAt=t.extractUpdatedAt),t.connectedWorkbooksCount!=null&&(e.connectedWorkbooksCount=t.connectedWorkbooksCount),t.extractCreationPending!=null&&(e.extractCreationPending=t.extractCreationPending),t.hasSevereDataQualityWarning!=null&&(e.hasSevereDataQualityWarning=t.hasSevereDataQualityWarning),t.datasourceLuid&&(e.datasourceLuid=t.datasourceLuid),t.hasActiveDataQualityWarning!=null&&(e.hasActiveDataQualityWarning=t.hasActiveDataQualityWarning),e}var Qc={terms:fs.string().trim().nonempty().optional(),limit:fs.number().int().min(1).max(2e3).default(100).optional(),orderBy:Ii.optional(),filter:Ni.optional()},hs=t=>{let e=new O({server:t,name:"search-content",description:"\nThis tool searches across all supported content types for objects relevant to the search expression specified by search terms and filters.\n\n**Parameters:**\n\n- `terms` (optional): A string containing one or more search terms that the search uses as the basis for determining which items are relevant to return. If the terms parameter is not provided, it searches for everything bound by the specified filters.\n\n- `filter` (optional): Allows you to limit search results based on:\n - `contentTypes`: Filter by content types. Supported types are: 'lens', 'datasource', 'virtualconnection', 'collection', 'project', 'flow', 'datarole', 'table', 'database', 'view', 'workbook'\n - `ownerIds`: Filter by specific owner IDs (array of integers)\n - `modifiedTime`: Filter by last modified times using ISO 8601 date-time strings. Can be either a range (with startDate/endDate) or an array of specific date-times to include\n\n- `limit` (optional): The number of items to return in the search response (default: 100, max: 2000)\n\n- `orderBy` (optional): Determines the sorting method for returned items. Available sorting methods:\n - `hitsTotal`: Number of times a content item has been viewed since it was created\n - `hitsSmallSpanTotal`: Number of times a content item was viewed in the last month\n - `hitsMediumSpanTotal`: Number of times a content item was viewed in the last 3 months\n - `hitsLargeSpanTotal`: Number of times a content item was viewed in the last year\n - `downstreamWorkbookCount`: Number of workbooks in a given project. This value is only available when the content type filter includes 'database' or 'table'\n \n For each sort method, you can specify a sort direction: 'asc' for ascending or 'desc' for descending (default: 'asc'). The orderBy parameter is an array of objects containing the sorting method and direction. The first element determines primary sorting, with subsequent elements used as tiebreakers.\n\n**Important Notes:**\n- If `orderBy` is omitted, the search will sort items by their \"relevance score\" in descending order, which is Tableau's internal algorithm for providing the most relevant results",paramsSchema:Qc,annotations:{title:"Search Content",readOnlyHint:!0,openWorldHint:!1},callback:async({terms:r,limit:i,orderBy:o,filter:n},{requestId:s})=>{let l=R(),u=o?ds(o):void 0,m=n?ps(n):void 0;return await e.logAndExecute({requestId:s,args:{},callback:async()=>new Gc(await P({config:l,requestId:s,server:t,jwtScopes:["tableau:content:read"],callback:async c=>{let h=await c.contentExplorationMethods.searchContent({terms:r,page:0,limit:l.maxResultLimit?Math.min(l.maxResultLimit,i??100):i??100,orderBy:u,filter:m});return ms(h)}}))})}});return e};import{Err as Jc,Ok as oi}from"ts-results-es";import{z as Kc}from"zod";function sr(){return["The VizQL Data Service is disabled on this Tableau Server.","To enable it, use TSM using the instructions at https://help.tableau.com/current/server-linux/en-us/cli_configuration-set_tsm.htm#featuresvizqldataservicedeploywithtsm."].join(" ")}function nr({datasourceLuid:t}){if(!t)throw new Error("datasourceLuid must be a non-empty string.")}import{z as _}from"zod";var $c=_.object({name:_.string(),columnClass:_.string(),dataType:_.string().nullable(),defaultAggregation:_.string().nullable(),description:_.string().nullable(),descriptionInherited:_.array(_.object({attribute:_.string(),value:_.string().nullable()}).nullable()).nullable(),dataCategory:_.string().nullable(),role:_.string().nullable(),defaultFormat:_.string().nullable(),semanticRole:_.string().nullable(),aggregation:_.string().nullable(),aggregationParam:_.string().nullable(),formula:_.string().nullable(),isAutoGenerated:_.boolean().nullable(),hasUserReference:_.boolean().nullable(),binSize:_.number().nullable()}).partial(),Zc=_.object({name:_.string(),parameterType:_.string(),dataType:_.string().nullable(),value:_.union([_.number(),_.string(),_.boolean(),_.null()]),members:_.array(_.union([_.number(),_.string(),_.boolean(),_.null()])),min:_.number().nullable(),max:_.number().nullable(),step:_.number().nullable(),minDate:_.string().nullable(),maxDate:_.string().nullable(),periodValue:_.number().nullable(),periodType:_.string().nullable()}).partial(),Pb=_.object({fields:_.array($c),parameters:_.array(Zc)});function ii(t){let e={fields:[],parameters:[]};if(!t.data)return e;for(let r of t.data){let i={name:r.fieldCaption,dataType:r.dataType,columnClass:r.columnClass};r.defaultAggregation&&(i.defaultAggregation=r.defaultAggregation),r.formula&&(i.formula=r.formula),e.fields.push(i)}if(t.extraData?.parameters)for(let r of t.extraData.parameters){let i={name:r.parameterCaption,parameterType:r.parameterType,dataType:r.dataType,value:r.value};r.parameterType==="LIST"&&r.members?i.members=r.members:r.parameterType==="QUANTITATIVE_DATE"?(i.minDate=r.minDate,i.maxDate=r.maxDate,i.periodValue=r.periodValue,i.periodType=r.periodType):r.parameterType==="QUANTITATIVE_RANGE"&&(i.min=r.min,i.max=r.max,i.step=r.step),e.parameters.push(i)}return e}function ys(t,e){let r={fields:[],parameters:[]};if(!t.data){if(e.data.publishedDatasources[0]?.fields.length)for(let i of e.data.publishedDatasources[0].fields){let o={name:i.name};i.dataType&&(o.dataType=i.dataType),i.aggregation&&(o.defaultAggregation=i.aggregation),gs(i,o),r.fields.push(o)}return r}for(let i of t.data){let o={name:i.fieldCaption,dataType:i.dataType,columnClass:i.columnClass};i.defaultAggregation&&(o.defaultAggregation=i.defaultAggregation),i.formula&&(o.formula=i.formula),r.fields.push(o)}if(t.extraData?.parameters)for(let i of t.extraData.parameters){let o={name:i.parameterCaption,parameterType:i.parameterType,dataType:i.dataType,value:i.value};i.parameterType==="LIST"&&i.members?o.members=i.members:i.parameterType==="QUANTITATIVE_DATE"?(o.minDate=i.minDate,o.maxDate=i.maxDate,o.periodValue=i.periodValue,o.periodType=i.periodType):i.parameterType==="QUANTITATIVE_RANGE"&&(o.min=i.min,o.max=i.max,o.step=i.step),r.parameters.push(o)}if(!e.data.publishedDatasources[0]?.fields.length)return r;for(let i of r.fields){let o=e.data.publishedDatasources[0].fields.find(n=>n.name===i.name);o&&gs(o,i)}return r}function gs(t,e){t.description&&(e.description=t.description),t.descriptionInherited?.length&&(e.descriptionInherited=t.descriptionInherited),t.dataCategory&&(e.dataCategory=t.dataCategory),t.role&&(e.role=t.role),t.defaultFormat&&(e.defaultFormat=t.defaultFormat),t.formula&&(e.formula=t.formula,t.isAutoGenerated!=null&&(e.isAutoGenerated=t.isAutoGenerated),t.hasUserReference!=null&&(e.hasUserReference=t.hasUserReference)),t.binSize!=null&&(e.binSize=t.binSize)}var Yc=t=>`
|
|
17
|
+
- 'DEFINITION_VIEW_DEFAULT' - Return the metric definition and the default metric.`}],response:M.object({definitions:M.array(Ro)})}),wu=mt({method:"get",path:"/pulse/definitions/:pulseMetricDefinitionID/metrics",alias:"listPulseMetricsFromMetricDefinitionId",description:"Returns a list of published Pulse Metrics for a specific Pulse Metric Definition.",parameters:[{name:"pulseMetricDefinitionID",type:"Path",schema:M.string().nonempty()}],response:M.object({metrics:M.array(Ar),total_available:M.number()})}),Tu=mt({method:"post",path:"/pulse/metrics%3AbatchGet",alias:"listPulseMetricsFromMetricIds",description:"Returns a list of Pulse Metrics for a list of metric IDs.",parameters:[{name:"metric_ids",type:"Body",schema:M.object({metric_ids:M.array(M.string().nonempty())})}],response:M.object({metrics:M.array(Ar)})}),Au=mt({method:"get",path:"/pulse/subscriptions",alias:"listPulseMetricSubscriptionsForCurrentUser",description:"Returns a list of Pulse Subscriptions for the current user.",parameters:[{name:"user_id",type:"Query",schema:M.string().nonempty()}],response:M.object({subscriptions:M.array(Ns)})}),Eu=mt({method:"post",path:"/pulse/insights/:bundle_type",alias:"generatePulseMetricValueInsightBundle",description:"Generates a bundle for the current aggregated value for the Pulse metric.",parameters:[{name:"bundle_request",type:"Body",schema:Er},{name:"bundle_type",type:"Path",schema:M.enum(_r)}],response:Fs}),_u=gu([Eu,bu,yu,wu,Au,Tu]),Us=[..._u];var Ut=class extends H{constructor(e,r){super(new Su(e,Us),r)}listAllPulseMetricDefinitions=async(e,r,o)=>await ft(async()=>{let i=await this._apiClient.listAllPulseMetricDefinitions({queries:{view:e,page_token:r,page_size:o},...this.authHeader});return{pagination:{next_page_token:i.next_page_token,offset:i.offset,total_available:i.total_available},definitions:i.definitions??[]}});listPulseMetricDefinitionsFromMetricDefinitionIds=async(e,r)=>await ft(async()=>(await this._apiClient.listPulseMetricDefinitionsFromMetricDefinitionIds({definition_ids:e},{queries:{view:r},...this.authHeader})).definitions??[]);listPulseMetricsFromMetricDefinitionId=async e=>await ft(async()=>(await this._apiClient.listPulseMetricsFromMetricDefinitionId({params:{pulseMetricDefinitionID:e},...this.authHeader})).metrics??[]);listPulseMetricsFromMetricIds=async e=>await ft(async()=>(await this._apiClient.listPulseMetricsFromMetricIds({metric_ids:e},{...this.authHeader})).metrics??[]);listPulseMetricSubscriptionsForCurrentUser=async()=>await ft(async()=>(await this._apiClient.listPulseMetricSubscriptionsForCurrentUser({queries:{user_id:this.userId},...this.authHeader})).subscriptions??[]);generatePulseMetricValueInsightBundle=async(e,r)=>await ft(async()=>await this._apiClient.generatePulseMetricValueInsightBundle({bundle_request:e.bundle_request},{params:{bundle_type:r},...this.authHeader})??{})};async function ft(t){try{return new vu(await t())}catch(e){if(xe(e)){if(e.response?.status===404)return new qs("tableau-server");if(e.response?.status===400&&e.response.headers.tableau_error_code==="0xd3408984"&&e.response.headers.validation_code==="400999")return new qs("pulse-disabled")}throw e}}import{isErrorFromAlias as Pu,Zodios as Du}from"@zodios/core";import{Err as ko,Ok as Lu}from"ts-results-es";import{makeApi as Cu,makeEndpoint as zs}from"@zodios/core";import{z as Ie}from"zod";import{z as qt}from"zod";var js=qt.object({productVersion:qt.object({value:qt.string(),build:qt.string()}),restApiVersion:qt.string()});import{z as xo}from"zod";var Vs=xo.object({id:xo.string(),name:xo.string()});import{z as Io}from"zod";var Bs=Io.object({id:Io.string(),name:Io.string()});var Ru=Ie.object({site:Vs,user:Bs}),xu=zs({method:"get",path:"/serverinfo",alias:"getServerInfo",description:"Returns the version of Tableau Server and the supported version of the REST API.",response:Ie.object({serverInfo:js})}),Iu=zs({method:"get",path:"/sessions/current",alias:"getCurrentServerSession",description:"Returns details of the current session of Tableau Server.",response:Ie.object({session:Ru}),errors:[{status:401,schema:Ie.object({error:Ie.object({code:Ie.string(),summary:Ie.string(),detail:Ie.string()})})}]}),ku=Cu([xu,Iu]),Ws=[...ku];var jt=class extends H{constructor(e,r){super(new Du(e,Ws),r)}getServerInfo=async()=>(await this._apiClient.getServerInfo()).serverInfo;getCurrentServerSession=async()=>{try{let e=await this._apiClient.getCurrentServerSession({...this.authHeader});return Lu(e.session)}catch(e){return Pu(this._apiClient.api,"getCurrentServerSession",e)?ko({type:"unauthorized",message:e.response.data.error}):xe(e)&&e.response?ko({type:"unknown",message:e.response.data}):ko({type:"unknown",message:W(e)})}}};import{Zodios as Vu}from"@zodios/core";import{makeApi as Ou,makeEndpoint as Vt}from"@zodios/core";import{z as X}from"zod";import{z as Z}from"zod";var ht=Z.object({id:Z.string(),name:Z.string(),createdAt:Z.string(),updatedAt:Z.string(),workbook:Z.object({id:Z.string()}).optional(),owner:Z.object({id:Z.string()}).optional(),project:Z.object({id:Z.string()}).optional(),tags:Z.object({tag:Z.array(Z.object({label:Z.string()})).optional()}),usage:Z.object({totalViewCount:Z.coerce.number()}).optional()});var Mu=Vt({method:"get",path:"/sites/:siteId/views/:viewId",alias:"getView",description:"Gets the details of a specific view.",response:X.object({view:ht})}),Nu=Vt({method:"get",path:"/sites/:siteId/views/:viewId/data",alias:"queryViewData",description:"Returns a specified view rendered as data in comma separated value (CSV) format.",response:X.string()}),Fu=Vt({method:"get",path:"/sites/:siteId/views/:viewId/image",alias:"queryViewImage",description:"Returns an image of the specified view.",parameters:[{name:"vizWidth",type:"Query",schema:X.number().optional(),description:"The width of the rendered image in pixels that, along with the value of vizHeight determine its resolution and aspect ratio."},{name:"vizHeight",type:"Query",schema:X.number().optional(),description:"The height of the rendered image in pixels that, along with the value of vizWidth determine its resolution and aspect ratio."},{name:"resolution",type:"Query",schema:X.literal("high").optional(),description:"The resolution of the image. Image width and actual pixel density are determined by the display context of the image. Aspect ratio is always preserved. Set the value to high to ensure maximum pixel density."}],response:X.string()}),Uu=Vt({method:"get",path:"/sites/:siteId/workbooks/:workbookId/views",alias:"queryViewsForWorkbook",description:"Returns all the views for the specified workbook, optionally including usage statistics.",parameters:[{name:"includeUsageStatistics",type:"Query",schema:X.boolean().optional(),description:"true to return usage statistics. The default is false."}],response:X.object({views:X.object({view:X.array(ht)})})}),qu=Vt({method:"get",path:"/sites/:siteId/views",alias:"queryViewsForSite",description:"Returns all the views for the specified site, optionally including usage statistics.",parameters:[...rt,{name:"includeUsageStatistics",type:"Query",schema:X.boolean().optional(),description:"true to return usage statistics. The default is false."},{name:"filter",type:"Query",schema:X.string().optional(),description:"An expression that lets you specify a subset of views to return. You can filter on predefined fields such as name, tags, and createdAt. You can include multiple filter expressions."}],response:X.object({pagination:tt,views:X.object({view:X.array(ht).optional()})})}),ju=Ou([Mu,Nu,Fu,Uu,qu]),Hs=[...ju];var Bt=class extends H{constructor(e,r){super(new Vu(e,Hs),r)}getView=async({viewId:e,siteId:r})=>(await this._apiClient.getView({params:{siteId:r,viewId:e},...this.authHeader})).view;queryViewData=async({viewId:e,siteId:r})=>await this._apiClient.queryViewData({params:{siteId:r,viewId:e},...this.authHeader});queryViewImage=async({viewId:e,siteId:r,width:o,height:i,resolution:n})=>await this._apiClient.queryViewImage({params:{siteId:r,viewId:e},queries:{vizWidth:o,vizHeight:i,resolution:n},...this.authHeader,responseType:"arraybuffer"});queryViewsForWorkbook=async({workbookId:e,siteId:r,includeUsageStatistics:o})=>(await this._apiClient.queryViewsForWorkbook({params:{siteId:r,workbookId:e},queries:{includeUsageStatistics:o},...this.authHeader})).views.view;queryViewsForSite=async({siteId:e,includeUsageStatistics:r,filter:o,pageSize:i,pageNumber:n})=>{let s=await this._apiClient.queryViewsForSite({params:{siteId:e},queries:{includeUsageStatistics:r,filter:o,pageSize:i,pageNumber:n},...this.authHeader});return{pagination:s.pagination,views:s.views.view??[]}}};import{isErrorFromAlias as Xs,Zodios as cd,ZodiosError as ud}from"@zodios/core";import{Err as vr,Ok as en}from"ts-results-es";import{makeApi as Bu}from"@zodios/core";import{z as m}from"zod";var zu=m.object({connectionLuid:m.string().optional(),connectionUsername:m.string(),connectionPassword:m.string()}),Gs=m.object({datasourceLuid:m.string().nonempty(),connections:m.array(zu).optional()}),Wu=m.enum(["OBJECTS","ARRAYS"]),$s=m.object({returnFormat:Wu,debug:m.boolean().default(!1)}).partial().passthrough(),Hu=m.object({datasource:Gs,options:$s.optional()}).passthrough(),Lo=m.enum(["SUM","AVG","MEDIAN","COUNT","COUNTD","MIN","MAX","STDEV","VAR","COLLECT","YEAR","QUARTER","MONTH","WEEK","DAY","TRUNC_YEAR","TRUNC_QUARTER","TRUNC_MONTH","TRUNC_WEEK","TRUNC_DAY","AGG","NONE","UNSPECIFIED"]),Qs=m.enum(["INTEGER","REAL","STRING","DATETIME","BOOLEAN","DATE","SPATIAL","UNKNOWN"]),Ks=m.enum(["MINUTES","HOURS","DAYS","WEEKS","MONTHS","QUARTERS","YEARS"]),Gu=m.object({fieldName:m.string(),fieldCaption:m.string(),dataType:Qs,defaultAggregation:Lo,columnClass:m.enum(["COLUMN","BIN","GROUP","CALCULATION","TABLE_CALCULATION"]),formula:m.string(),logicalTableId:m.string()}).partial().passthrough(),Js=m.union([m.number(),m.string(),m.boolean(),m.null()]),Sr=m.object({parameterCaption:m.string(),dataType:Qs.exclude(["DATETIME","SPATIAL","UNKNOWN"]),parameterName:m.string().optional(),value:Js}),$u=m.discriminatedUnion("parameterType",[Sr.extend({parameterType:m.literal("ANY_VALUE")}).strict(),Sr.extend({parameterType:m.literal("LIST"),members:m.array(Js)}).strict(),Sr.extend({parameterType:m.literal("QUANTITATIVE_DATE"),value:m.string().nullable(),minDate:m.string().nullish(),maxDate:m.string().nullish(),periodValue:m.number().nullish(),periodType:Ks.nullish()}).strict(),Sr.extend({parameterType:m.literal("QUANTITATIVE_RANGE"),value:m.number().nullable(),min:m.number().nullish(),max:m.number().nullish(),step:m.number().nullish()}).strict()]),Qu=m.object({data:m.array(Gu),extraData:m.object({parameters:m.array($u)})}).partial().passthrough(),Ku=m.object({errorCode:m.string(),message:m.string(),datetime:m.string().datetime({offset:!0}),debug:m.object({}).partial().passthrough(),"tab-error-code":m.string()}).partial().passthrough(),Ju=m.enum(["ASC","DESC"]),Po=m.object({fieldCaption:m.string(),fieldAlias:m.string().optional(),maxDecimalPlaces:m.number().int().optional(),sortDirection:Ju.optional(),sortPriority:m.number().int().optional()}),Zu=m.union([Po.strict(),Po.extend({function:Lo}).strict(),Po.extend({calculation:m.string()}).strict()]),Zs=m.union([m.object({fieldCaption:m.string()}).strict(),m.object({fieldCaption:m.string(),function:Lo}).strict(),m.object({calculation:m.string()}).strict()]),Oo=m.object({field:Zs,context:m.boolean().optional()}),Mo=m.object({field:m.object({fieldCaption:m.string()}).strict(),context:m.boolean().optional()}),Yu=Mo.extend({filterType:m.literal("SET"),values:m.union([m.array(m.string()),m.array(m.number()),m.array(m.boolean())]),exclude:m.boolean().optional()}),gt=Mo.extend({filterType:m.literal("DATE"),periodType:Ks,anchorDate:m.string().optional(),includeNulls:m.boolean().optional()}),Xu=m.discriminatedUnion("dateRangeType",[gt.extend({dateRangeType:m.literal("CURRENT")}).strict(),gt.extend({dateRangeType:m.literal("LAST")}).strict(),gt.extend({dateRangeType:m.literal("NEXT")}).strict(),gt.extend({dateRangeType:m.literal("TODATE")}).strict(),gt.extend({dateRangeType:m.literal("LASTN"),rangeN:m.number().int()}).strict(),gt.extend({dateRangeType:m.literal("NEXTN"),rangeN:m.number().int()}).strict()]),Do=Mo.extend({filterType:m.literal("MATCH"),startsWith:m.string().optional(),endsWith:m.string().optional(),contains:m.string().optional(),exclude:m.boolean().optional()}),ed=m.union([Do.extend({startsWith:m.string()}).strict(),Do.extend({endsWith:m.string()}).strict(),Do.extend({contains:m.string()}).strict()]),zt=Oo.extend({filterType:m.literal("QUANTITATIVE_NUMERICAL")}),td=m.discriminatedUnion("quantitativeFilterType",[zt.extend({quantitativeFilterType:m.literal("RANGE"),min:m.number(),max:m.number(),includeNulls:m.boolean().optional()}).strict(),zt.extend({quantitativeFilterType:m.literal("MIN"),min:m.number(),includeNulls:m.boolean().optional()}).strict(),zt.extend({quantitativeFilterType:m.literal("MAX"),max:m.number(),includeNulls:m.boolean().optional()}).strict(),zt.extend({quantitativeFilterType:m.literal("ONLY_NULL")}).strict(),zt.extend({quantitativeFilterType:m.literal("ONLY_NON_NULL")}).strict()]),Wt=Oo.extend({filterType:m.literal("QUANTITATIVE_DATE")}),rd=m.discriminatedUnion("quantitativeFilterType",[Wt.extend({quantitativeFilterType:m.literal("RANGE"),minDate:m.string(),maxDate:m.string(),includeNulls:m.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:m.literal("MIN"),minDate:m.string(),includeNulls:m.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:m.literal("MAX"),maxDate:m.string(),includeNulls:m.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:m.literal("ONLY_NULL")}).strict(),Wt.extend({quantitativeFilterType:m.literal("ONLY_NON_NULL")}).strict()]),od=Oo.extend({filterType:m.literal("TOP"),howMany:m.number().int(),fieldToMeasure:Zs,direction:m.enum(["TOP","BOTTOM"]).optional().default("TOP")}),id=m.union([Yu.strict(),od.strict(),...ed.options,...td.options,...rd.options,...Xu.options]),Ht=m.strictObject({fields:m.array(Zu),filters:m.array(id).optional()}),sd=$s.and(m.object({disaggregate:m.boolean()}).partial().passthrough()),nd=m.object({datasource:Gs,query:Ht,options:sd.optional()}).passthrough(),ad=m.object({data:m.array(m.unknown())}).partial().passthrough(),ld=Bu([{method:"post",path:"/query-datasource",alias:"queryDatasource",description:"Queries a specific data source and returns the resulting data.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:nd}],response:ad,errors:[{status:"default",schema:Ku},{status:404,schema:m.any()}]},{method:"post",path:"/read-metadata",alias:"readMetadata",description:"Requests metadata for a specific data source. The metadata provides information about the data fields, such as field names, data types, and descriptions.",requestFormat:"json",parameters:[{name:"body",type:"Body",schema:Hu}],response:Qu,errors:[{status:404,schema:m.any()}]},{method:"get",path:"/simple-request",alias:"simpleRequest",description:"Sends a request that can be used for testing or doing a health check.",requestFormat:"json",response:m.string()}]),Ys=[...ld];var Gt=class extends H{constructor(e,r){super(new cd(e,Ys),r)}queryDatasource=async e=>{try{return en(await this._apiClient.queryDatasource(e,{...this.authHeader}))}catch(r){if(Xs(this._apiClient.api,"queryDatasource",r))return r.response.status===404?vr("feature-disabled"):vr(r.response.data);if(r instanceof ud)return vr(r);throw r}};readMetadata=async e=>{try{return en(await this._apiClient.readMetadata(e,{...this.authHeader}))}catch(r){if(Xs(this._apiClient.api,"readMetadata",r)&&r.response.status===404)return vr("feature-disabled");throw r}}};import{Zodios as hd}from"@zodios/core";import{makeApi as dd,makeEndpoint as tn}from"@zodios/core";import{z as Ge}from"zod";import{z as ee}from"zod";var No=ee.object({id:ee.string(),name:ee.string(),description:ee.string().optional(),webpageUrl:ee.string().optional(),contentUrl:ee.string(),project:sr.optional(),showTabs:ee.coerce.boolean(),defaultViewId:ee.string().optional(),tags:ee.object({tag:ee.array(ee.object({label:ee.string()})).optional()}),views:ee.optional(ee.object({view:ee.array(ht)}))});var pd=tn({method:"get",path:"/sites/:siteId/workbooks/:workbookId",alias:"getWorkbook",description:"Returns information about the specified workbook, including information about views and tags.",response:Ge.object({workbook:No})}),md=tn({method:"get",path:"/sites/:siteId/workbooks",alias:"queryWorkbooksForSite",description:"Returns the workbooks on a site.",parameters:[...rt,{name:"siteId",type:"Path",schema:Ge.string()},{name:"filter",type:"Query",schema:Ge.string().optional(),description:"An expression that lets you specify a subset of workbooks to return. You can filter on predefined fields such as name, tags, and createdAt. You can include multiple filter expressions."}],response:Ge.object({pagination:tt,workbooks:Ge.object({workbook:Ge.optional(Ge.array(No))})})}),fd=dd([md,pd]),rn=[...fd];var $t=class extends H{constructor(e,r){super(new hd(e,rn),r)}getWorkbook=async({workbookId:e,siteId:r})=>(await this._apiClient.getWorkbook({params:{siteId:r,workbookId:e},...this.authHeader})).workbook;queryWorkbooksForSite=async({siteId:e,filter:r,pageSize:o,pageNumber:i})=>{let n=await this._apiClient.queryWorkbooksForSite({params:{siteId:e},queries:{filter:r,pageSize:o,pageNumber:i},...this.authHeader});return{pagination:n.pagination,workbooks:n.workbooks.workbook??[]}}};var bt=class t{_creds;_host;_baseUrl;_baseUrlWithoutVersion;_authenticationMethods;_authenticatedAuthenticationMethods;_contentExplorationMethods;_datasourcesMethods;_metadataMethods;_pulseMethods;_serverMethods;_vizqlDataServiceMethods;_viewsMethods;_workbooksMethods;static _version="3.24";_requestInterceptor;_responseInterceptor;constructor(e,r){this._host=e,this._baseUrl=`${this._host}/api/${t._version}`,this._baseUrlWithoutVersion=`${this._host}/api/-`,this._requestInterceptor=r?.requestInterceptor,this._responseInterceptor=r?.responseInterceptor}get creds(){if(!this._creds)throw new Error("No credentials found. Authenticate by calling signIn() first.");return this._creds}get siteId(){return this.creds.site.id}get authenticationMethods(){return this._authenticationMethods||(this._authenticationMethods=new _t(this._baseUrl),this._addInterceptors(this._baseUrl,this._authenticationMethods.interceptors)),this._authenticationMethods}get authenticatedAuthenticationMethods(){return this._authenticatedAuthenticationMethods||(this._authenticatedAuthenticationMethods=new ir(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._authenticatedAuthenticationMethods.interceptors)),this._authenticatedAuthenticationMethods}get contentExplorationMethods(){return this._contentExplorationMethods||(this._contentExplorationMethods=new St(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._contentExplorationMethods.interceptors)),this._contentExplorationMethods}get datasourcesMethods(){return this._datasourcesMethods||(this._datasourcesMethods=new vt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._datasourcesMethods.interceptors)),this._datasourcesMethods}get metadataMethods(){if(!this._metadataMethods){let e=`${this._host}/api/metadata`;this._metadataMethods=new Ct(e,this.creds),this._addInterceptors(e,this._metadataMethods.interceptors)}return this._metadataMethods}get pulseMethods(){return this._pulseMethods||(this._pulseMethods=new Ut(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._pulseMethods.interceptors)),this._pulseMethods}get serverMethods(){return this._serverMethods||(this._serverMethods=new jt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._serverMethods.interceptors)),this._serverMethods}get vizqlDataServiceMethods(){if(!this._vizqlDataServiceMethods){let e=`${this._host}/api/v1/vizql-data-service`;this._vizqlDataServiceMethods=new Gt(e,this.creds),this._addInterceptors(e,this._vizqlDataServiceMethods.interceptors)}return this._vizqlDataServiceMethods}get viewsMethods(){return this._viewsMethods||(this._viewsMethods=new Bt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._viewsMethods.interceptors)),this._viewsMethods}get workbooksMethods(){return this._workbooksMethods||(this._workbooksMethods=new $t(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._workbooksMethods.interceptors)),this._workbooksMethods}signIn=async e=>{this._creds=await this.authenticationMethods.signIn(e)};signOut=async()=>{await this.authenticatedAuthenticationMethods.signOut(),this._creds=void 0};setCredentials=(e,r)=>{let o=e.split("|");if(o.length<3)throw new Error("Could not determine site ID. Access token must have 3 parts.");let i=o[2];this._creds={site:{id:i},user:{id:r},token:e}};_addInterceptors=(e,r)=>{r.request.use(o=>(this._requestInterceptor?.[0]({baseUrl:e,...rr(o)}),o),o=>(this._requestInterceptor?.[1]?.(o,e),Promise.reject(o))),r.response.use(o=>(this._responseInterceptor?.[0]({baseUrl:e,...or(o)}),o),o=>(this._responseInterceptor?.[1]?.(o,e),Promise.reject(o)))}};var gd=async(t,e,r,o,i)=>{let n=t.server||i?.server;ce(n,"Tableau server could not be determined");let s=new bt(n,{requestInterceptor:[bd(r,e),yd(r,e)],responseInterceptor:[wd(r,e),Td(r,e)]});if(t.auth==="pat")await s.signIn({type:"pat",patName:t.patName,patValue:t.patValue,siteName:t.siteName});else if(t.auth==="direct-trust")await s.signIn({type:"direct-trust",siteName:t.siteName,username:Ed(t,i),clientId:t.connectedAppClientId,secretId:t.connectedAppSecretId,secretValue:t.connectedAppSecretValue,scopes:o,additionalPayload:_d(t,i)});else{if(!i?.accessToken||!i?.userId)throw new Error("Auth info is required when not signing in first.");s.setCredentials(i.accessToken,i.userId)}return s},I=async({config:t,requestId:e,server:r,callback:o,jwtScopes:i,authInfo:n})=>{let s=await gd(t,e,r,new Set(i),n);try{return await o(s)}finally{t.auth!=="oauth"&&await s.signOut()}},bd=(t,e)=>r=>(r.headers["User-Agent"]=Ad(t),on(t,r,e),r),yd=(t,e)=>(r,o)=>{if(!xe(r)||!r.request){ue.error(t,`Request ${e} failed with error: ${W(r)}`,{logger:"rest-api",requestId:e});return}let{request:i}=r;on(t,{baseUrl:o,...rr(i)},e)},wd=(t,e)=>r=>(sn(t,r,e),r),Td=(t,e)=>(r,o)=>{if(!xe(r)||!r.response){ue.error(t,`Response from request ${e} failed with error: ${W(r)}`,{logger:"rest-api",requestId:e});return}let{response:i}=r;sn(t,{baseUrl:o,...or(i)},e)};function on(t,e,r){let i=E().disableLogMasking?e:hi(e),n=new URL(i.url??"",i.baseUrl);e.params&&Object.keys(e.params).length>0&&(n.search=new URLSearchParams(e.params).toString());let s={type:"request",requestId:r,method:i.method,url:n.toString(),...Oe("debug")&&{headers:i.headers,data:i.data,params:i.params}};ue.info(t,s,{logger:"rest-api",requestId:r})}function sn(t,e,r){let i=E().disableLogMasking?e:gi(e),n=new URL(i.url??"",i.baseUrl);e.request?.params&&Object.keys(e.request.params).length>0&&(n.search=new URLSearchParams(e.request.params).toString());let s={type:"response",requestId:r,url:n.toString(),status:i.status,...Oe("debug")&&{headers:i.headers,data:i.data}};ue.info(t,s,{logger:"rest-api",requestId:r})}function Ad(t){let e=[Cr];if(t.clientInfo){let{name:r,version:o}=t.clientInfo;r&&e.push(o?`(${r} ${o})`:`(${r})`)}return e.join(" ")}function Ed(t,e){return t.jwtSubClaim.replaceAll("{OAUTH_USERNAME}",e?.username??"")}function _d(t,e){let r=t.jwtAdditionalPayload.replaceAll("{OAUTH_USERNAME}",e?.username??"");return JSON.parse(r||"{}")}import{z as q}from"zod";import{z as Sd}from"zod";var B=t=>Sd.string({message:`${t} is required`}).nonempty({message:`${t} must be non-empty`});var nn=q.object({client_id:B("client_id"),redirect_uri:B("redirect_uri"),response_type:B("response_type"),code_challenge:B("code_challenge"),code_challenge_method:B("code_challenge_method"),state:q.string().optional()}).transform(t=>({clientId:t.client_id,redirectUri:t.redirect_uri,responseType:t.response_type,codeChallenge:t.code_challenge,codeChallengeMethod:t.code_challenge_method,state:t.state})),an=q.discriminatedUnion("grant_type",[q.object({grant_type:q.literal("authorization_code"),code:B("code"),redirect_uri:B("redirect_uri"),code_verifier:B("code_verifier")}),q.object({grant_type:q.literal("refresh_token"),refresh_token:B("refresh_token")}),q.object({grant_type:q.literal("client_credentials")})],{errorMap:(t,e)=>({message:t.code==="invalid_union_discriminator"?`grant_type must be ${t.options.map(r=>`'${String(r)}'`).join(" | ")}, got '${e.data.grant_type}'.`:e.defaultError})}).and(q.object({client_id:q.string().optional(),client_secret:q.string().optional()})).transform(t=>{let{client_id:e,client_secret:r}=t,o={clientId:e,clientSecret:r};return t.grant_type==="authorization_code"?{grantType:t.grant_type,code:t.code,redirectUri:t.redirect_uri,codeVerifier:t.code_verifier,...o}:t.grant_type==="refresh_token"?{grantType:t.grant_type,refreshToken:t.refresh_token,...o}:{grantType:t.grant_type,...o}}),ln=q.object({code:q.string().optional(),state:q.string().optional(),error:q.string().optional()}),Fo=q.object({iss:B("iss"),aud:B("aud"),exp:q.number().int().nonnegative(),sub:B("sub"),clientId:B("clientId"),tableauServer:B("tableauServer"),tableauUserId:q.string().optional()}),cn=Fo.extend({tableauAccessToken:B("tableauAccessToken"),tableauRefreshToken:B("tableauRefreshToken"),tableauExpiresAt:q.number().int().nonnegative(),tableauUserId:B("tableauUserId")}),Rr=q.object({username:q.string(),userId:q.string(),server:q.string(),accessToken:q.string(),refreshToken:q.string()}).partial();var N=t=>{if(!t)return;let e=Rr.safeParse(t.extra);if(e.success)return e.data};import{ZodiosError as un}from"@zodios/core";import{fromError as vd,isZodErrorLike as Cd}from"zod-validation-error";var ke=class{_provider;constructor(e){this._provider=e}get(){return this._provider()}};var O=class{server;name;description;paramsSchema;annotations;argsValidator;callback;constructor({server:e,name:r,description:o,paramsSchema:i,annotations:n,argsValidator:s,callback:a}){this.server=e,this.name=r,this.description=o instanceof ke?o.get():o,this.paramsSchema=i instanceof ke?i.get():i,this.annotations=n instanceof ke?n.get():n,this.argsValidator=s instanceof ke?s.get():s,this.callback=a instanceof ke?a.get():a}logInvocation({requestId:e,args:r,username:o}){ue.debug(this.server,pi({requestId:e,toolName:this.name,args:r,username:o}))}async logAndExecute({requestId:e,args:r,authInfo:o,callback:i,getSuccessResult:n,getErrorText:s,constrainSuccessResult:a}){let c=o?.extra?Rr.safeParse(o.extra).data?.username:void 0;if(this.logInvocation({requestId:e,args:r,username:c}),r)try{this.argsValidator?.(r)}catch(l){return xr(e,l)}try{let l=await i();if(l.isOk()){let u=await a(l.value);return u.type!=="success"?{isError:u.type==="error",content:[{type:"text",text:u.message}]}:n?n(u.result):{isError:!1,content:[{type:"text",text:JSON.stringify(u.result)}]}}return l.error instanceof un?xr(e,l.error):s?{isError:!0,content:[{type:"text",text:s(l.error)}]}:xr(e,l.error)}catch(l){return xr(e,l)}}};function xr(t,e){if(e instanceof un&&Cd(e.cause)){let r=vd(e.cause);return{isError:!1,content:[{type:"text",text:JSON.stringify({data:e.data,warning:r.toString()})}]}}return{isError:!0,content:[{type:"text",text:`requestId: ${t}, error: ${W(e)}`}]}}function dn(t){let e=new Set;return t.flatMap(r=>e.has(r.method)?[]:(e.add(r.method),r.method+(r.sortDirection?`:${r.sortDirection}`:""))).join(",")}function pn(t){let e=[];if(t.contentTypes)if(t.contentTypes.length===1)e.push(`type:eq:${t.contentTypes[0]}`);else{let r=new Set;for(let o of t.contentTypes)r.add(o);e.push(`type:in:[${Array.from(r).join(",")}]`)}if(t.ownerIds)if(t.ownerIds.length===1)e.push(`ownerId:eq:${t.ownerIds[0]}`);else{let r=new Set;for(let o of t.ownerIds)r.add(o);e.push(`ownerId:in:[${Array.from(r).join(",")}]`)}if(t.modifiedTime)if(Array.isArray(t.modifiedTime))if(t.modifiedTime.length===1)e.push(`modifiedTime:eq:${t.modifiedTime[0]}`);else{let r=new Set;for(let o of t.modifiedTime)r.add(o);e.push(`modifiedTime:in:[${Array.from(r).join(",")}]`)}else if(t.modifiedTime.startDate&&t.modifiedTime.endDate){let r=t.modifiedTime.startDate,o=t.modifiedTime.endDate;r>o&&(r=t.modifiedTime.endDate,o=t.modifiedTime.startDate),e.push(`modifiedTime:gte:${r}`),e.push(`modifiedTime:lte:${o}`)}else t.modifiedTime.startDate?e.push(`modifiedTime:gte:${t.modifiedTime.startDate}`):t.modifiedTime.endDate&&e.push(`modifiedTime:lte:${t.modifiedTime.endDate}`);return e.join(",")}function mn(t){let e=[];if(t.items)for(let o of t.items)e.push(Rd(o.content));let r=new Set(e.filter(o=>o.type==="unifieddatasource").map(o=>o.datasourceLuid).filter(o=>typeof o=="string"));e=e.filter(o=>o.type==="datasource"?typeof o.luid=="string"&&!r.has(o.luid):!0);for(let o of e)o.type==="unifieddatasource"&&(o.type="datasource",o.luid=o.datasourceLuid,delete o.datasourceLuid);return e}function Rd(t){let e={};return t.modifiedTime&&(e.modifiedTime=t.modifiedTime),t.sheetType&&(e.sheetType=t.sheetType),t.caption&&(e.caption=t.caption),t.workbookDescription&&(e.workbookDescription=t.workbookDescription),t.type&&(e.type=t.type),t.ownerId&&(e.ownerId=t.ownerId),t.title&&(e.title=t.title),t.ownerName&&(e.ownerName=t.ownerName),t.containerName&&(t.type==="view"?e.parentWorkbookName=t.containerName:e.containerName=t.containerName),t.luid&&(e.luid=t.luid),t.locationName&&(e.locationName=t.locationName),t.comments?.length&&(e.comments=t.comments),t.hitsTotal!=null&&(e.totalViewCount=t.hitsTotal),t.favoritesTotal!=null&&(e.favoritesTotal=t.favoritesTotal),t.tags?.length&&(e.tags=t.tags),t.projectId&&(e.projectId=t.projectId),t.projectName&&(e.projectName=t.projectName),t.hitsSmallSpanTotal!=null&&(e.viewCountLastMonth=t.hitsSmallSpanTotal),t.downstreamWorkbookCount!=null&&(e.downstreamWorkbookCount=t.downstreamWorkbookCount),t.isConnectable!=null&&(e.isConnectable=t.isConnectable),t.datasourceIsPublished!=null&&(e.datasourceIsPublished=t.datasourceIsPublished),t.connectionType&&(e.connectionType=t.connectionType),t.isCertified!=null&&(e.isCertified=t.isCertified),t.hasExtracts!=null&&(e.hasExtracts=t.hasExtracts),t.extractRefreshedAt&&(e.extractRefreshedAt=t.extractRefreshedAt),t.extractUpdatedAt&&(e.extractUpdatedAt=t.extractUpdatedAt),t.connectedWorkbooksCount!=null&&(e.connectedWorkbooksCount=t.connectedWorkbooksCount),t.extractCreationPending!=null&&(e.extractCreationPending=t.extractCreationPending),t.hasSevereDataQualityWarning!=null&&(e.hasSevereDataQualityWarning=t.hasSevereDataQualityWarning),t.datasourceLuid&&(e.datasourceLuid=t.datasourceLuid),t.hasActiveDataQualityWarning!=null&&(e.hasActiveDataQualityWarning=t.hasActiveDataQualityWarning),e}function fn({items:t,boundedContext:e}){if(t.length===0)return{type:"empty",message:"No search results were found. Either none exist or you do not have permission to view them."};let{projectIds:r,datasourceIds:o,workbookIds:i}=e;return r&&(t=t.filter(n=>!!(typeof n.projectId=="number"&&r.has(n.projectId.toString())))),o&&(t=t.filter(n=>!(n.type==="datasource"&&typeof n.luid=="string"&&!o.has(n.luid)))),i&&(t=t.filter(n=>!(n.type==="workbook"&&typeof n.luid=="string"&&!i.has(n.luid)))),t.length===0?{type:"empty",message:["The set of allowed content that can be queried is limited by the server configuration.","While search results were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}var Id={terms:hn.string().trim().nonempty().optional(),limit:hn.number().int().min(1).max(2e3).default(100).optional(),orderBy:Ei.optional(),filter:vi.optional()},gn=t=>{let e=new O({server:t,name:"search-content",description:"\nThis tool searches across all supported content types for objects relevant to the search expression specified by search terms and filters.\n\n**Parameters:**\n\n- `terms` (optional): A string containing one or more search terms that the search uses as the basis for determining which items are relevant to return. If the terms parameter is not provided, it searches for everything bound by the specified filters.\n\n- `filter` (optional): Allows you to limit search results based on:\n - `contentTypes`: Filter by content types. Supported types are: 'lens', 'datasource', 'virtualconnection', 'collection', 'project', 'flow', 'datarole', 'table', 'database', 'view', 'workbook'\n - `ownerIds`: Filter by specific owner IDs (array of integers)\n - `modifiedTime`: Filter by last modified times using ISO 8601 date-time strings. Can be either a range (with startDate/endDate) or an array of specific date-times to include\n\n- `limit` (optional): The number of items to return in the search response (default: 100, max: 2000)\n\n- `orderBy` (optional): Determines the sorting method for returned items. Available sorting methods:\n - `hitsTotal`: Number of times a content item has been viewed since it was created\n - `hitsSmallSpanTotal`: Number of times a content item was viewed in the last month\n - `hitsMediumSpanTotal`: Number of times a content item was viewed in the last 3 months\n - `hitsLargeSpanTotal`: Number of times a content item was viewed in the last year\n - `downstreamWorkbookCount`: Number of workbooks in a given project. This value is only available when the content type filter includes 'database' or 'table'\n \n For each sort method, you can specify a sort direction: 'asc' for ascending or 'desc' for descending (default: 'asc'). The orderBy parameter is an array of objects containing the sorting method and direction. The first element determines primary sorting, with subsequent elements used as tiebreakers.\n\n**Important Notes:**\n- If `orderBy` is omitted, the search will sort items by their \"relevance score\" in descending order, which is Tableau's internal algorithm for providing the most relevant results",paramsSchema:Id,annotations:{title:"Search Content",readOnlyHint:!0,openWorldHint:!1},callback:async({terms:r,limit:o,orderBy:i,filter:n},{requestId:s,authInfo:a})=>{let c=E(),l=i?dn(i):void 0,u=n?pn(n):void 0;return await e.logAndExecute({requestId:s,authInfo:a,args:{},callback:async()=>new xd(await I({config:c,requestId:s,server:t,jwtScopes:["tableau:content:read"],authInfo:N(a),callback:async p=>{let g=await p.contentExplorationMethods.searchContent({terms:r,page:0,limit:c.maxResultLimit?Math.min(c.maxResultLimit,o??100):o??100,orderBy:l,filter:u});return mn(g)}})),constrainSuccessResult:p=>fn({items:p,boundedContext:c.boundedContext})})}});return e};import{Err as wn,Ok as qo}from"ts-results-es";import{z as Dd}from"zod";function Ir(){return["The VizQL Data Service is disabled on this Tableau Server.","To enable it, use TSM using the instructions at https://help.tableau.com/current/server-linux/en-us/cli_configuration-set_tsm.htm#featuresvizqldataservicedeploywithtsm."].join(" ")}var Qt=class t{_allowedProjectIds;_allowedDatasourceIds;_allowedWorkbookIds;_cachedDatasourceIds;_cachedWorkbookIds;_cachedViewIds;static create(){return new t}static createForTesting(e){return new t(e)}constructor(e){this._allowedProjectIds=e?.projectIds,this._allowedDatasourceIds=e?.datasourceIds,this._allowedWorkbookIds=e?.workbookIds,this._cachedDatasourceIds=new Map,this._cachedWorkbookIds=new Map,this._cachedViewIds=new Map}get allowedProjectIds(){return this._allowedProjectIds===void 0&&(this._allowedProjectIds=E().boundedContext.projectIds),this._allowedProjectIds}get allowedDatasourceIds(){return this._allowedDatasourceIds===void 0&&(this._allowedDatasourceIds=E().boundedContext.datasourceIds),this._allowedDatasourceIds}get allowedWorkbookIds(){return this._allowedWorkbookIds===void 0&&(this._allowedWorkbookIds=E().boundedContext.workbookIds),this._allowedWorkbookIds}async isDatasourceAllowed({datasourceLuid:e,restApiArgs:r}){let o=await this._isDatasourceAllowed({datasourceLuid:e,restApiArgs:r});return this.allowedProjectIds||this._cachedDatasourceIds.set(e,o),o}async isWorkbookAllowed({workbookId:e,restApiArgs:r}){let o=await this._isWorkbookAllowed({workbookId:e,restApiArgs:r});return this.allowedProjectIds||this._cachedWorkbookIds.set(e,o),o}async isViewAllowed({viewId:e,restApiArgs:r}){let o=await this._isViewAllowed({viewId:e,restApiArgs:r});return this.allowedProjectIds||this._cachedViewIds.set(e,o),o}async _isDatasourceAllowed({datasourceLuid:e,restApiArgs:{config:r,requestId:o,server:i}}){let n=this._cachedDatasourceIds.get(e);if(n)return n;if(this.allowedDatasourceIds&&!this.allowedDatasourceIds.has(e))return{allowed:!1,message:["The set of allowed data sources that can be queried is limited by the server configuration.",`Querying the datasource with LUID ${e} is not allowed.`].join(" ")};if(this.allowedProjectIds)try{let s=await I({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async a=>(await a.datasourcesMethods.queryDatasource({siteId:a.siteId,datasourceId:e})).project.id});if(!this.allowedProjectIds.has(s))return{allowed:!1,message:["The set of allowed data sources that can be queried is limited by the server configuration.",`The datasource with LUID ${e} cannot be queried because it does not belong to an allowed project.`].join(" ")}}catch(s){return{allowed:!1,message:["The set of allowed data sources that can be queried is limited by the server configuration.",`An error occurred while checking if the datasource with LUID ${e} is in an allowed project:`,W(s)].join(" ")}}return{allowed:!0}}async _isWorkbookAllowed({workbookId:e,restApiArgs:{config:r,requestId:o,server:i}}){let n=this._cachedWorkbookIds.get(e);if(n)return n;if(this.allowedWorkbookIds&&!this.allowedWorkbookIds.has(e))return{allowed:!1,message:["The set of allowed workbooks that can be queried is limited by the server configuration.",`Querying the workbook with LUID ${e} is not allowed.`].join(" ")};let s;if(this.allowedProjectIds)try{if(s=await I({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async a=>await a.workbooksMethods.getWorkbook({siteId:a.siteId,workbookId:e})}),!this.allowedProjectIds.has(s.project?.id??""))return{allowed:!1,message:["The set of allowed workbooks that can be queried is limited by the server configuration.",`The workbook with LUID ${e} cannot be queried because it does not belong to an allowed project.`].join(" ")}}catch(a){return{allowed:!1,message:["The set of allowed workbooks that can be queried is limited by the server configuration.",`An error occurred while checking if the workbook with LUID ${e} is in an allowed project:`,W(a)].join(" ")}}return{allowed:!0,content:s}}async _isViewAllowed({viewId:e,restApiArgs:{config:r,requestId:o,server:i}}){let n=this._cachedViewIds.get(e);if(n)return n;let s="",a="";if(this.allowedWorkbookIds)try{let c=await I({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async l=>await l.viewsMethods.getView({siteId:l.siteId,viewId:e})});if(s=c.workbook?.id??"",a=c.project?.id??"",!this.allowedWorkbookIds.has(s))return{allowed:!1,message:["The set of allowed workbooks that can be queried is limited by the server configuration.",`The view with LUID ${e} cannot be queried because it does not belong to an allowed workbook.`].join(" ")}}catch(c){return{allowed:!1,message:["The set of allowed workbooks that can be queried is limited by the server configuration.",`An error occurred while checking if the workbook containing the view with LUID ${e} is in an allowed workbook:`,W(c)].join(" ")}}if(this.allowedProjectIds)try{if(a=a||await I({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async c=>(await c.viewsMethods.getView({siteId:c.siteId,viewId:e})).project?.id??""}),!this.allowedProjectIds.has(a))return{allowed:!1,message:["The set of allowed views that can be queried is limited by the server configuration.",`The view with LUID ${e} cannot be queried because it does not belong to an allowed project.`].join(" ")}}catch(c){return{allowed:!1,message:["The set of allowed views that can be queried is limited by the server configuration.",`An error occurred while checking if the workbook containing the view with LUID ${e} is in an allowed project:`,W(c)].join(" ")}}return{allowed:!0}}},be=Qt.create(),jA={createResourceAccessChecker:Qt.createForTesting,resetResourceAccessCheckerSingleton:()=>{be=Qt.create()}};function kr({datasourceLuid:t}){if(!t)throw new Error("datasourceLuid must be a non-empty string.")}import{z as C}from"zod";var kd=C.object({name:C.string(),columnClass:C.string(),dataType:C.string().nullable(),defaultAggregation:C.string().nullable(),description:C.string().nullable(),descriptionInherited:C.array(C.object({attribute:C.string(),value:C.string().nullable()}).nullable()).nullable(),dataCategory:C.string().nullable(),role:C.string().nullable(),defaultFormat:C.string().nullable(),semanticRole:C.string().nullable(),aggregation:C.string().nullable(),aggregationParam:C.string().nullable(),formula:C.string().nullable(),isAutoGenerated:C.boolean().nullable(),hasUserReference:C.boolean().nullable(),binSize:C.number().nullable()}).partial(),Pd=C.object({name:C.string(),parameterType:C.string(),dataType:C.string().nullable(),value:C.union([C.number(),C.string(),C.boolean(),C.null()]),members:C.array(C.union([C.number(),C.string(),C.boolean(),C.null()])),min:C.number().nullable(),max:C.number().nullable(),step:C.number().nullable(),minDate:C.string().nullable(),maxDate:C.string().nullable(),periodValue:C.number().nullable(),periodType:C.string().nullable()}).partial(),WA=C.object({fields:C.array(kd),parameters:C.array(Pd)});function Uo(t){let e={fields:[],parameters:[]};if(!t.data)return e;for(let r of t.data){let o={name:r.fieldCaption,dataType:r.dataType,columnClass:r.columnClass};r.defaultAggregation&&(o.defaultAggregation=r.defaultAggregation),r.formula&&(o.formula=r.formula),e.fields.push(o)}if(t.extraData?.parameters)for(let r of t.extraData.parameters){let o={name:r.parameterCaption,parameterType:r.parameterType,dataType:r.dataType,value:r.value};r.parameterType==="LIST"&&r.members?o.members=r.members:r.parameterType==="QUANTITATIVE_DATE"?(o.minDate=r.minDate,o.maxDate=r.maxDate,o.periodValue=r.periodValue,o.periodType=r.periodType):r.parameterType==="QUANTITATIVE_RANGE"&&(o.min=r.min,o.max=r.max,o.step=r.step),e.parameters.push(o)}return e}function yn(t,e){let r={fields:[],parameters:[]};if(!t.data){if(e.data.publishedDatasources[0]?.fields.length)for(let o of e.data.publishedDatasources[0].fields){let i={name:o.name};o.dataType&&(i.dataType=o.dataType),o.aggregation&&(i.defaultAggregation=o.aggregation),bn(o,i),r.fields.push(i)}return r}for(let o of t.data){let i={name:o.fieldCaption,dataType:o.dataType,columnClass:o.columnClass};o.defaultAggregation&&(i.defaultAggregation=o.defaultAggregation),o.formula&&(i.formula=o.formula),r.fields.push(i)}if(t.extraData?.parameters)for(let o of t.extraData.parameters){let i={name:o.parameterCaption,parameterType:o.parameterType,dataType:o.dataType,value:o.value};o.parameterType==="LIST"&&o.members?i.members=o.members:o.parameterType==="QUANTITATIVE_DATE"?(i.minDate=o.minDate,i.maxDate=o.maxDate,i.periodValue=o.periodValue,i.periodType=o.periodType):o.parameterType==="QUANTITATIVE_RANGE"&&(i.min=o.min,i.max=o.max,i.step=o.step),r.parameters.push(i)}if(!e.data.publishedDatasources[0]?.fields.length)return r;for(let o of r.fields){let i=e.data.publishedDatasources[0].fields.find(n=>n.name===o.name);i&&bn(i,o)}return r}function bn(t,e){t.description&&(e.description=t.description),t.descriptionInherited?.length&&(e.descriptionInherited=t.descriptionInherited),t.dataCategory&&(e.dataCategory=t.dataCategory),t.role&&(e.role=t.role),t.defaultFormat&&(e.defaultFormat=t.defaultFormat),t.formula&&(e.formula=t.formula,t.isAutoGenerated!=null&&(e.isAutoGenerated=t.isAutoGenerated),t.hasUserReference!=null&&(e.hasUserReference=t.hasUserReference)),t.binSize!=null&&(e.binSize=t.binSize)}var Ld=t=>`
|
|
18
18
|
query datasourceFieldInfo {
|
|
19
19
|
publishedDatasources(filter: { luid: "${t}" }) {
|
|
20
20
|
name
|
|
@@ -75,11 +75,11 @@ var nn=Object.defineProperty;var an=(t,e)=>{for(var r in e)nn(t,r,{get:e[r],enum
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
-
}`,
|
|
78
|
+
}`,Od={datasourceLuid:Dd.string().nonempty()},Tn=t=>{let e=new O({server:t,name:"get-datasource-metadata",description:`
|
|
79
79
|
This tool retrieves field metadata for a specified datasource by taking the basic, high level, metadata results from Tableau's VizQL Data Service and enriches them with additional context provided by Tableau's Metadata API.
|
|
80
80
|
The fields provided by this tool will contain properties such as name and dataType, but may also expose richer context such as descriptions, dataCategories, roles, etc.
|
|
81
81
|
This tool should be used for getting the metadata to ground the use of a tool that queries Tableau published data sources.
|
|
82
|
-
`,paramsSchema:
|
|
82
|
+
`,paramsSchema:Od,annotations:{title:"Get Datasource Metadata",readOnlyHint:!0,openWorldHint:!1},argsValidator:kr,callback:async({datasourceLuid:r},{requestId:o,authInfo:i})=>{let n=E(),s=Ld(r);return await e.logAndExecute({requestId:o,authInfo:i,args:{datasourceLuid:r},callback:async()=>{let a=await be.isDatasourceAllowed({datasourceLuid:r,restApiArgs:{config:n,requestId:o,server:t}});return a.allowed?await I({config:n,requestId:o,server:t,jwtScopes:["tableau:content:read","tableau:viz_data_service:read"],authInfo:N(i),callback:async c=>{let l=await c.vizqlDataServiceMethods.readMetadata({datasource:{datasourceLuid:r}});if(l.isErr())return wn({type:"feature-disabled"});if(n.disableMetadataApiRequests)return qo(Uo(l.value));let u;try{u=await c.metadataMethods.graphql(s)}catch{return qo(Uo(l.value))}return qo(yn(l.value,u))}}):new wn({type:"datasource-not-allowed",message:a.message})},constrainSuccessResult:a=>({type:"success",result:a}),getErrorText:a=>{switch(a.type){case"feature-disabled":return Ir();case"datasource-not-allowed":return a.message}}})}});return e};import{Ok as Bd}from"ts-results-es";import{z as Vo}from"zod";import{Ok as Md}from"ts-results-es";import{z as $e}from"zod";var Nd=$e.object({pageSize:$e.coerce.number().gt(0),pageNumber:$e.coerce.number().gt(0),limit:$e.coerce.number().gt(0)}).partial();async function yt({pageConfig:t,getDataFn:e}){let{pageSize:r,limit:o}=Nd.parse(t),{pagination:i,data:n}=await e(t),s=[...n],{totalAvailable:a,pageNumber:c}=i;for(;a>s.length&&(!o||o>s.length);){let{pagination:l,data:u}=await e({pageSize:r,pageNumber:c+1,limit:o});if(u.length===0)throw new Error(`No more data available. Last fetched page number: ${c}, Total available: ${a}, Total fetched: ${s.length}`);({totalAvailable:a,pageNumber:c}=l),s.push(...u)}return o&&o<s.length&&(s.length=o),s}var Fd=$e.object({limit:$e.coerce.number().gt(0).optional(),pageSize:$e.coerce.number().gt(0).optional()}).optional();async function An({config:t,getDataFn:e}){let r=Fd.parse(t),o=r?.limit,i=r?.pageSize,n=await e(void 0,i);if(n.isErr())return n;let{pagination:s,data:a}=n.value,c=[...a],l=s.total_available,u=s.next_page_token;for(!i&&l&&(i=Math.min(l-c.length,o?o-c.length:Number.MAX_SAFE_INTEGER));u&&(!o||o>c.length);){let p=await e(u,i);if(p.isErr())return p;let{pagination:g,data:b}=p.value;if(b.length===0)throw new Error(`No more data available. Total fetched: ${c.length}`);({next_page_token:u}=g),c.push(...b)}return o&&o<c.length&&(c.length=o),new Md(c)}var wt="**Supported Operators**\n - `eq`: equals\n - `gt`: greater than\n - `gte`: greater than or equal\n - `in`: any of [list] (for searching tags)\n - `lt`: less than\n - `lte`: less than or equal\n \n **Filter Expression Notes**\n - Filter expressions can't contain ampersand (&) or comma (,) characters even if those characters are encoded.\n - Operators are delimited with colons (:). For example: `filter=name:eq:Project Views`\n - Field names, operator names, and values are case-sensitive.\n - To filter on multiple fields, combine expressions using a comma: `filter=lastLogin:gte:2016-01-01T00:00:00Z,siteRole:eq:Publisher`\n - Multiple expressions are combined using a logical AND.\n - If you include the same field multiple times, only the last reference is used.\n - For date-time values, use ISO 8601 format (e.g., `2016-05-04T21:24:49Z`).\n - Wildcard searches (starts with, ends with, contains) are supported in recent Tableau versions:\n - Starts with: `?filter=name:eq:mark*`\n - Ends with: `?filter=name:eq:*-ample`\n - Contains: `?filter=name:eq:mark*ex*`";import{z as jo}from"zod";import Ud from"zod";var Qe=Ud.enum(["eq","in","gt","gte","lt","lte"]);function qd(t){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(t)}var jd=["createdAt","updatedAt"];function Tt({filterString:t,allowedOperatorsByField:e,filterFieldSchema:r}){function o(s,a){return e[s].includes(a)}let i=t.split(",").map(s=>s.trim()).filter(Boolean),n={};for(let s of i){let[a,c,...l]=s.split(":");if(!a||!c||l.length===0)throw new Error(`Invalid filter expression format: "${s}"`);let u=l.join(":"),p=r.parse(a),g=Qe.parse(c);if(!o(p,g))throw new Error(`Operator '${g}' is not allowed for field '${p}'. Allowed operators: ${e[p].join(", ")}`);if(jd.includes(p)&&!qd(u))throw new Error(`Value for field '${p}' must be a valid ISO 8601 date-time string (e.g., 2016-05-04T21:24:49Z)`);n[p]={field:p,operator:g,value:u}}return Object.values(n).map(s=>`${s.field}:${s.operator}:${s.value}`).join(",")}var En=jo.enum(["authenticationType","connectedWorkbookType","connectionTo","connectionType","contentUrl","createdAt","databaseName","databaseUserName","description","favoritesTotal","hasAlert","hasEmbeddedPassword","hasExtracts","isCertified","isConnectable","isDefaultPort","isHierarchical","isPublished","name","ownerDomain","ownerEmail","ownerName","projectName","serverName","serverPort","size","tableName","tags","type","updatedAt"]),Vd={authenticationType:["eq","in"],connectedWorkbookType:["eq","gt","gte","lt","lte"],connectionTo:["eq","in"],connectionType:["eq","in"],contentUrl:["eq","in"],createdAt:["eq","gt","gte","lt","lte"],databaseName:["eq","in"],databaseUserName:["eq","in"],description:["eq","in"],favoritesTotal:["eq","gt","gte","lt","lte"],hasAlert:["eq"],hasEmbeddedPassword:["eq"],hasExtracts:["eq"],isCertified:["eq"],isConnectable:["eq"],isDefaultPort:["eq"],isHierarchical:["eq"],isPublished:["eq"],name:["eq","in"],ownerDomain:["eq","in"],ownerEmail:["eq"],ownerName:["eq","in"],projectName:["eq","in"],serverName:["eq","in"],serverPort:["eq"],size:["eq","gt","gte","lt","lte"],tableName:["eq","in"],tags:["eq","in"],type:["eq"],updatedAt:["eq","gt","gte","lt","lte"]},mE=jo.object({field:En,operator:Qe,value:jo.string()});function _n(t){return Tt({filterString:t,allowedOperatorsByField:Vd,filterFieldSchema:En})}var zd={filter:Vo.string().optional(),pageSize:Vo.number().gt(0).optional(),limit:Vo.number().gt(0).optional()},Sn=t=>{let e=new O({server:t,name:"list-datasources",description:`
|
|
83
83
|
Retrieves a list of published data sources from a specified Tableau site using the Tableau REST API. Supports optional filtering via field:operator:value expressions (e.g., name:eq:Views) for precise and flexible data source discovery. Use this tool when a user requests to list, search, or filter Tableau data sources on a site.
|
|
84
84
|
|
|
85
85
|
**Supported Filter Fields and Operators**
|
|
@@ -116,7 +116,7 @@ var nn=Object.defineProperty;var an=(t,e)=>{for(var r in e)nn(t,r,{get:e[r],enum
|
|
|
116
116
|
| type | eq |
|
|
117
117
|
| updatedAt | eq, gt, gte, lt, lte |
|
|
118
118
|
|
|
119
|
-
${
|
|
119
|
+
${wt}
|
|
120
120
|
|
|
121
121
|
**Example Usage:**
|
|
122
122
|
- List all data sources on a site
|
|
@@ -128,7 +128,7 @@ var nn=Object.defineProperty;var an=(t,e)=>{for(var r in e)nn(t,r,{get:e[r],enum
|
|
|
128
128
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
129
129
|
- List data sources with the name "Project Views" in the "Finance" project and created after January 1, 2023:
|
|
130
130
|
filter: "name:eq:Project Views,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"
|
|
131
|
-
`,paramsSchema:
|
|
131
|
+
`,paramsSchema:zd,annotations:{title:"List Datasources",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=E(),c=r?_n(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{filter:r,pageSize:o,limit:i},callback:async()=>{let l=await I({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:N(s),callback:async u=>await yt({pageConfig:{pageSize:o,limit:a.maxResultLimit?Math.min(a.maxResultLimit,i??Number.MAX_SAFE_INTEGER):i},getDataFn:async g=>{let{pagination:b,datasources:f}=await u.datasourcesMethods.listDatasources({siteId:u.siteId,filter:c??"",pageSize:g.pageSize,pageNumber:g.pageNumber});return{pagination:b,data:f}}})});return new Bd(l)},constrainSuccessResult:l=>Wd({datasources:l,boundedContext:a.boundedContext})})}});return e};function Wd({datasources:t,boundedContext:e}){if(t.length===0)return{type:"empty",message:"No datasources were found. Either none exist or you do not have permission to view them."};let{projectIds:r,datasourceIds:o}=e;return r&&(t=t.filter(i=>r.has(i.project.id))),o&&(t=t.filter(i=>o.has(i.id))),t.length===0?{type:"empty",message:["The set of allowed data sources that can be queried is limited by the server configuration.","While data sources were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}import{Err as vn}from"ts-results-es";import Cn from"zod";function de(t){switch(t){case"tableau-server":return["Pulse is not available on Tableau Server.","Consider disabling the Pulse MCP tools in your client or removing them using the EXCLUDE_TOOLS environment variable.","To enable Pulse on your Tableau Cloud site, please see the instructions at https://help.tableau.com/current/online/en-us/pulse_set_up.htm."].join(" ");case"pulse-disabled":return["Pulse is disabled on this Tableau Cloud site.","To enable Pulse, please see the instructions at https://help.tableau.com/current/online/en-us/pulse_set_up.htm."].join(" ")}}var Hd={bundleRequest:Er,bundleType:Cn.optional(Cn.enum(_r))},Rn=t=>{let e=new O({server:t,name:"generate-pulse-metric-value-insight-bundle",description:`
|
|
132
132
|
Generate an insight bundle for the current aggregated value for Pulse Metric using Tableau REST API. You need the full information of the Pulse Metric and Pulse Metric Definition to use this tool.
|
|
133
133
|
|
|
134
134
|
**Parameters:**
|
|
@@ -235,7 +235,7 @@ Generate an insight bundle for the current aggregated value for Pulse Metric usi
|
|
|
235
235
|
- Generate the detail insight bundle for the Pulse metric:
|
|
236
236
|
bundleType: 'detail',
|
|
237
237
|
bundleRequest: (See default example above)
|
|
238
|
-
`,paramsSchema:
|
|
238
|
+
`,paramsSchema:Hd,annotations:{title:"Generate Pulse Metric Value Insight Bundle",readOnlyHint:!0,openWorldHint:!1},callback:async({bundleRequest:r,bundleType:o},{requestId:i,authInfo:n})=>{let s=E();return await e.logAndExecute({requestId:i,authInfo:n,args:{bundleRequest:r,bundleType:o},callback:async()=>{let{datasourceIds:a}=s.boundedContext;if(a){let l=r.bundle_request.input.metric.definition.datasource.id;if(!a.has(l))return new vn({type:"datasource-not-allowed",message:["The set of allowed metric insights that can be queried is limited by the server configuration.","Generating the Pulse Metric Value Insight Bundle is not allowed because the definition is derived",`from the data source with LUID ${l}, which is not in the allowed set of data sources.`].join(" ")})}let c=await I({config:s,requestId:i,server:t,jwtScopes:["tableau:insights:read"],authInfo:N(n),callback:async l=>await l.pulseMethods.generatePulseMetricValueInsightBundle(r,o??"ban")});return c.isErr()?new vn({type:"feature-disabled",reason:c.error}):c},constrainSuccessResult:a=>({type:"success",result:a}),getErrorText:a=>{switch(a.type){case"feature-disabled":return de(a.reason);case"datasource-not-allowed":return a.message}}})}});return e};import{Ok as Gd}from"ts-results-es";import{z as Dr}from"zod";function Pr({boundedContext:t,definitions:e}){if(e.length===0)return{type:"empty",message:"No Pulse Metric Definitions were found. Either none exist or you do not have permission to view them."};let{datasourceIds:r}=t;return r&&(e=e.filter(o=>r.has(o.specification.datasource.id))),e.length===0?{type:"empty",message:["The set of allowed Pulse Metric Definitions that can be queried is limited by the server configuration.","While Pulse Metric Definitions were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:e}}var $d={view:Dr.optional(Dr.enum(He)),limit:Dr.coerce.number().gt(0).optional(),pageSize:Dr.coerce.number().gt(0).optional()},xn=t=>{let e=new O({server:t,name:"list-all-pulse-metric-definitions",description:`
|
|
239
239
|
Retrieves a list of all published Pulse Metric Definitions using the Tableau REST API. Use this tool when a user requests to list all Tableau Pulse Metric Definitions on the current site.
|
|
240
240
|
|
|
241
241
|
**Parameters:**
|
|
@@ -243,11 +243,15 @@ Retrieves a list of all published Pulse Metric Definitions using the Tableau RES
|
|
|
243
243
|
- \`DEFINITION_VIEW_BASIC\` - Return only the specified metric definition.
|
|
244
244
|
- \`DEFINITION_VIEW_FULL\` - Return the metric definition and the specified number of metrics.
|
|
245
245
|
- \`DEFINITION_VIEW_DEFAULT\` - Return the metric definition and the default metric.
|
|
246
|
+
- \`limit\` (optional): Maximum number of metric definitions to return. If not specified, all definitions are returned.
|
|
247
|
+
- \`pageSize\` (optional): Number of results per page. Controls how many definitions are fetched in each API request during pagination.
|
|
246
248
|
|
|
247
249
|
**Example Usage:**
|
|
248
250
|
- List all Pulse Metric Definitions on the current site
|
|
249
251
|
- List all Pulse Metric Definitions on the current site with the default view:
|
|
250
252
|
view: 'DEFINITION_VIEW_DEFAULT'
|
|
253
|
+
- List the first 50 Pulse Metric Definitions:
|
|
254
|
+
limit: 50
|
|
251
255
|
- List all Pulse Metric Definitions on the current site with the full view:
|
|
252
256
|
view: 'DEFINITION_VIEW_FULL'
|
|
253
257
|
In the response you will only get up to 5 metrics, so if you want to see more you need to retrieve all the Pulse Metrics from another tool.
|
|
@@ -256,7 +260,7 @@ Retrieves a list of all published Pulse Metric Definitions using the Tableau RES
|
|
|
256
260
|
- See all metrics for my Pulse Metric Definitions:
|
|
257
261
|
view: 'DEFINITION_VIEW_FULL'
|
|
258
262
|
In the response you will only get up to 5 metrics, so if you want to see more you need to retrieve all the Pulse Metrics from another tool.
|
|
259
|
-
`,paramsSchema
|
|
263
|
+
`,paramsSchema:$d,annotations:{title:"List All Pulse Metric Definitions",readOnlyHint:!0,openWorldHint:!1},callback:async({view:r,limit:o,pageSize:i},{requestId:n,authInfo:s})=>{let a=E();return await e.logAndExecute({requestId:n,authInfo:s,args:{view:r,limit:o,pageSize:i},callback:async()=>await I({config:a,requestId:n,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:N(s),callback:async c=>await An({config:{limit:a.maxResultLimit?Math.min(a.maxResultLimit,o??Number.MAX_SAFE_INTEGER):o,pageSize:i},getDataFn:async(u,p)=>{let g=await c.pulseMethods.listAllPulseMetricDefinitions(r,u,p);return g.isOk()?new Gd({pagination:g.value.pagination,data:g.value.definitions}):g}})}),constrainSuccessResult:c=>Pr({definitions:c,boundedContext:a.boundedContext}),getErrorText:de})}});return e};import{z as Lr}from"zod";var Qd={metricDefinitionIds:Lr.array(Lr.string().length(36)).min(1),view:Lr.optional(Lr.enum(He))},In=t=>{let e=new O({server:t,name:"list-pulse-metric-definitions-from-definition-ids",description:`
|
|
260
264
|
Retrieves a list of specific Pulse Metric Definitions using the Tableau REST API from a list of metric definition IDs. Use this tool when a user requests information about specific Pulse Metric Definitions on the current site.
|
|
261
265
|
|
|
262
266
|
**Parameters:**
|
|
@@ -285,7 +289,7 @@ Retrieves a list of specific Pulse Metric Definitions using the Tableau REST API
|
|
|
285
289
|
metricDefinitionIds: ['BBC908D8-29ED-48AB-A78E-ACF8A424C8C3', 'BBC908D8-29ED-48AB-A78E-ACF8A424C8C4'],
|
|
286
290
|
view: 'DEFINITION_VIEW_FULL'
|
|
287
291
|
In the response you will only get up to 5 metrics, so if you want to see more you need to retrieve all the Pulse Metrics from another tool.
|
|
288
|
-
`,paramsSchema:
|
|
292
|
+
`,paramsSchema:Qd,annotations:{title:"List Pulse Metric Definitions from Metric Definition IDs",readOnlyHint:!0,openWorldHint:!1},callback:async({view:r,metricDefinitionIds:o},{requestId:i,authInfo:n})=>{let s=E();return await e.logAndExecute({requestId:i,authInfo:n,args:{metricDefinitionIds:o,view:r},callback:async()=>await I({config:s,requestId:i,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:N(n),callback:async a=>await a.pulseMethods.listPulseMetricDefinitionsFromMetricDefinitionIds(o,r)}),constrainSuccessResult:a=>Pr({definitions:a,boundedContext:s.boundedContext}),getErrorText:de})}});return e};import{z as Kd}from"zod";function Or({metrics:t,boundedContext:e}){if(t.length===0)return{type:"empty",message:"No Pulse Metrics were found. Either none exist or you do not have permission to view them."};let{datasourceIds:r}=e;return r&&(t=t.filter(o=>r.has(o.datasource_luid))),t.length===0?{type:"empty",message:["The set of allowed Pulse Metrics that can be queried is limited by the server configuration.","While Pulse Metrics were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}var Jd={pulseMetricDefinitionID:Kd.string().length(36)},kn=t=>{let e=new O({server:t,name:"list-pulse-metrics-from-metric-definition-id",description:`
|
|
289
293
|
Retrieves a list of published Pulse Metrics from a Pulse Metric Definition using the Tableau REST API. Use this tool when a user requests to list Tableau Pulse Metrics for a specific Pulse Metric Definition on the current site.
|
|
290
294
|
|
|
291
295
|
**Parameters:**
|
|
@@ -293,7 +297,7 @@ Retrieves a list of published Pulse Metrics from a Pulse Metric Definition using
|
|
|
293
297
|
|
|
294
298
|
**Example Usage:**
|
|
295
299
|
- List all Pulse Metrics for this Pulse Metric Definition
|
|
296
|
-
`,paramsSchema:
|
|
300
|
+
`,paramsSchema:Jd,annotations:{title:"List Pulse Metrics from Metric Definition ID",readOnlyHint:!0,openWorldHint:!1},callback:async({pulseMetricDefinitionID:r},{requestId:o,authInfo:i})=>{let n=E();return await e.logAndExecute({requestId:o,authInfo:i,args:{pulseMetricDefinitionID:r},callback:async()=>await I({config:n,requestId:o,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:N(i),callback:async s=>await s.pulseMethods.listPulseMetricsFromMetricDefinitionId(r)}),constrainSuccessResult:s=>Or({metrics:s,boundedContext:n.boundedContext}),getErrorText:de})}});return e};import{z as Pn}from"zod";var Zd={metricIds:Pn.array(Pn.string().length(36))},Dn=t=>{let e=new O({server:t,name:"list-pulse-metrics-from-metric-ids",description:`
|
|
297
301
|
Retrieves a list of published Pulse Metrics from a list of metric IDs using the Tableau REST API. Use this tool when a user requests to list Tableau Pulse Metrics for a list of metric IDs on the current site.
|
|
298
302
|
|
|
299
303
|
**Parameters:**
|
|
@@ -307,7 +311,7 @@ Retrieves a list of published Pulse Metrics from a list of metric IDs using the
|
|
|
307
311
|
- This tool is recommended for use with data in Pulse Metric Subscriptions.
|
|
308
312
|
- 00000000-0000-0000-0000-000000000000 is not a valid datasource id.
|
|
309
313
|
- If you need a valid datasource id, you may need to retrieve the Pulse Metric Definition for the Pulse Metric which should have a valid datasource information.
|
|
310
|
-
`,paramsSchema:
|
|
314
|
+
`,paramsSchema:Zd,annotations:{title:"List Pulse Metrics from Metric IDs",readOnlyHint:!0,openWorldHint:!1},callback:async({metricIds:r},{requestId:o,authInfo:i})=>{let n=E();return await e.logAndExecute({requestId:o,authInfo:i,args:{metricIds:r},callback:async()=>await I({config:n,requestId:o,server:t,jwtScopes:["tableau:insight_metrics:read"],authInfo:N(i),callback:async s=>await s.pulseMethods.listPulseMetricsFromMetricIds(r)}),constrainSuccessResult:s=>Or({metrics:s,boundedContext:n.boundedContext}),getErrorText:de})}});return e};var Yd={},Ln=t=>{let e=new O({server:t,name:"list-pulse-metric-subscriptions",description:`
|
|
311
315
|
Retrieves a list of published Pulse Metric Subscriptions for the current user using the Tableau REST API. Use this tool when a user requests to list Tableau Pulse Metric Subscriptions for the current user.
|
|
312
316
|
|
|
313
317
|
**Example Usage:**
|
|
@@ -318,7 +322,7 @@ Retrieves a list of published Pulse Metric Subscriptions for the current user us
|
|
|
318
322
|
- This tool does not directly provide information about Pulse Metric Definitions. If you need to know information about Pulse Metric Defintiions associated with your subscriptions you need to:
|
|
319
323
|
1. Retrieve Pulse Metrics from the metric ids returned in the Pulse Metric Subscriptions.
|
|
320
324
|
2. Retrieve Pulse Metric Definitions from the metric definition id returned in the Pulse Metrics.
|
|
321
|
-
`,paramsSchema:mu,annotations:{title:"List Pulse Metric Subscriptions for Current User",readOnlyHint:!0,openWorldHint:!1},callback:async(r,{requestId:i})=>{let o=R();return await e.logAndExecute({requestId:i,args:{},callback:async()=>await P({config:o,requestId:i,server:t,jwtScopes:["tableau:metric_subscriptions:read"],callback:async n=>await n.pulseMethods.listPulseMetricSubscriptionsForCurrentUser()}),getErrorText:se})}});return e};import{ZodiosError as Au}from"@zodios/core";import{Err as Vs}from"ts-results-es";import{z as Su}from"zod";import{z as Ne}from"zod";var fu=Ne.record(Ne.string().nonempty(),Ne.array(Ne.object({luid:Ne.string().optional(),u:Ne.string().nonempty(),p:Ne.string().nonempty()}).transform(({luid:t,u:e,p:r})=>({connectionLuid:t,connectionUsername:e,connectionPassword:r})))),Is,Os=!1,Ps=t=>{if(!Os){Os=!0;let{datasourceCredentials:e}=R();if(!e)return;let r;try{r=JSON.parse(e)}catch(o){throw new Error(`Invalid datasource credentials format. Could not parse JSON string: ${e}`,{cause:o})}let i=fu.parse(r);Is=new Map(Object.entries(i))}return Is?.get(t)};function Ns(t){let e={...t};switch(t.errorCode){case"400000":e.condition="Bad request",e.details="The content of the request body is invalid. Check for missing or incomplete JSON.";break;case"400800":e.condition="Invalid formula for calculation",e.details="Invalid custom calculation syntax. For help, see https://help.tableau.com/current/pro/desktop/en-us/functions_operators.htm";break;case"400802":e.condition="Invalid API request",e.details="The incoming request isn't valid per the OpenAPI specification.";break;case"400803":e.condition="Validation failed",e.details="The incoming request isn't valid per the validation rules.";break;case"400804":e.condition="Response too large",e.details="The response value exceeds the limit. You must apply a filter in your request.";break;case"401001":e.condition="Login error",e.details="The login failed for the given user.";break;case"401002":e.condition="Invalid authorization credentials",e.details="The provided auth token is formatted incorrectly.";break;case"403157":e.condition="Feature disabled",e.details="The feature is disabled.";break;case"403800":e.condition="API access permission denied",e.details="The user doesn't have API Access granted on the given data source. Set the API Access capability for the given data source to Allowed. For help, see https://help.tableau.com/current/online/en-us/permissions_capabilities.htm";break;case"404934":e.condition="Unknown field",e.details="The requested field doesn't exist.";break;case"404950":e.condition="API endpoint not found",e.details="The request endpoint doesn't exist.";break;case"408000":e.condition="Request timeout",e.details="The request timed out.";break;case"409000":e.condition="User already on site",e.details="HTTP status conflict.";break;case"429000":e.condition="Too many requests",e.details="Too many requests in the allotted amount of time. For help, see https://help.tableau.com/current/api/vizql-data-service/en-us/docs/vds_limitations.html#licensing-and-data-transfer";break;case"500000":e.condition="Internal server error",e.details="The request could not be completed.";break;case"500810":e.condition="VDS empty table response",e.details="The underlying data engine returned empty data value response.";break;case"500811":e.condition="VDS missing table",e.details="The underlying data engine returned empty metadata associated with response.";break;case"500812":e.condition="Error while processing an error",e.details="Internal processing error.";break;case"501000":e.condition="Not implemented",e.details="Can't find response from upstream server.";break;case"503800":e.condition="VDS unavailable",e.details="The underlying data engine is unavailable.";break;case"503801":e.condition="VDS discovery error",e.details="The upstream service can't be found.";break;case"504000":e.condition="Gateway timeout",e.details="The upstream service response timed out.";break}return e}function Fs(t){if(t.length===0)throw new Error("The query must include at least one field. The fields property cannot be an empty array.");if(t.some(hu))throw new Error("The query must not include any fields with an empty fieldCaption.");{let e=t.reduce((i,o)=>(i[o.fieldCaption]||(i[o.fieldCaption]=0),i[o.fieldCaption]++,i),{}),r=Object.entries(e).filter(([i,o])=>o>1);if(r.length>0)throw new Error(`The query must not include duplicate fields. The following fields are duplicated: ${r.map(([i])=>i).join(", ")}.`)}{let e=t.reduce((i,o)=>(o.sortPriority===void 0||(i[o.sortPriority]||(i[o.sortPriority]=[]),i[o.sortPriority].push(o.fieldCaption)),i),{}),r=Object.entries(e).filter(([i,o])=>o.length>1);if(r.length>0){let i=r.reduce((o,[n,s])=>(o.push(`${s.map(l=>`"${l}"`).join(", ")} with a sort priority of ${n}`),o),[]);throw new Error(`The query must not include duplicate sort priorities. The following fields have sort priorities that are duplicated: ${i.join(". ")}.`)}}{let e=t.filter(ai).map(r=>r.fieldCaption);if(e.length>0)throw new Error(`The query must not include fields that contain both a function and a calculation. The following fields contain both a function and a calculation: ${e.join(", ")}.`)}{let e=t.filter(gu).map(r=>r.fieldCaption);if(e.length>0)throw new Error(`The query must not include fields that have a maxDecimalPlaces value that is less than 0. The following fields have a maxDecimalPlaces value that is less than 0: ${e.join(", ")}.`)}}function hu(t){return!t.fieldCaption}function ai(t){return!!("function"in t&&t.function&&"calculation"in t&&t.calculation)}function ks(t){return!!("fieldCaption"in t&&t.fieldCaption&&"calculation"in t&&t.calculation)}function gu(t){return t.maxDecimalPlaces!==void 0&&t.maxDecimalPlaces<0}import{Err as li,Ok as yu}from"ts-results-es";function qs(t){if(t){if(t.some(e=>!("field"in e)))throw new Error("The query must not include filters with invalid fields. The following field errors occurred: The filter must include a field property.");{let e=t.reduce((i,o)=>("fieldCaption"in o.field&&(i[o.field.fieldCaption]||(i[o.field.fieldCaption]=0),i[o.field.fieldCaption]++),i),{}),r=Object.entries(e).filter(([i,o])=>o>1);if(r.length>0)throw new Error(`The query must not include multiple filters for the following fields: ${r.map(([i])=>i).join(", ")}.`)}{let e=t.reduce((r,i)=>{if(!("field"in i))return r;let o=Ms(i.field);return o.isErr()&&r.push(o.error),r},[]);if(e.length>0)throw new Error(`The query must not include filters with invalid fields. The following field errors occurred: ${e.join(", ")}.`)}if(t.filter(r=>["SET","MATCH","DATE"].includes(r.filterType)&&("function"in r.field&&r.field.function||"calculation"in r.field&&r.field.calculation)).length>0)throw new Error("The query must not include Set Filters, Match Filters, or Relative Date Filters with functions or calculations.");if(t.filter(r=>r.filterType==="SET"&&r.values.length===0).length>0)throw new Error("The query must not include Set Filters with an empty values array.");if(t.filter(r=>{if(r.filterType!=="QUANTITATIVE_DATE")return!1;switch(r.quantitativeFilterType){case"RANGE":return isNaN(Date.parse(r.minDate))||isNaN(Date.parse(r.maxDate));case"MIN":return isNaN(Date.parse(r.minDate));case"MAX":return isNaN(Date.parse(r.maxDate))}}).length>0)throw new Error("The query must not include Quantitative Date Filters with invalid dates. Dates must use the RFC 3339 standard. Example: 2025-03-14");if(t.filter(r=>r.filterType==="DATE"&&r.anchorDate&&isNaN(Date.parse(r.anchorDate))).length>0)throw new Error("The query must not include Relative Date Filters with invalid anchor dates. Anchor dates must use the RFC 3339 standard. Example: 2025-03-14");{let e=t.reduce((r,i)=>{if(i.filterType!=="TOP")return r;let o=Ms(i.fieldToMeasure);return o.isErr()&&r.push(o.error),r},[]);if(e.length>0)throw new Error(`The query must not include Top N filters with invalid fields. The following field errors occurred: ${e.join(", ")}`)}{let e=t.reduce((r,i)=>(i.filterType!=="MATCH"||!i.startsWith&&!i.endsWith&&!i.contains&&r.push(`The match filter for field "${i.field.fieldCaption}" must include at least one of the following properties: startsWith, endsWith, or contains`),r),[]);if(e.length>0)throw new Error(`The query must not include Match Filters with invalid fields. The following field errors occurred: ${e.join(", ")}.`)}}}function Ms(t){if(bu(t))return new li("The fieldCaption property must be a non-empty string.");if(ks(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new li(`The field ${e} must not contain both a fieldCaption and a calculation.`.replace(" "," "))}if(ai(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new li(`The field ${e} must not contain both a function and a calculation.`.replace(" "," "))}return yu.EMPTY}function bu(t){return"fieldCaption"in t&&!t.fieldCaption}function Us({datasourceLuid:t,query:e}){nr({datasourceLuid:t});let{fields:r,filters:i}=e;if(Fs(r),qs(i),!Rt.safeParse(e).success)throw new Error("The query does not match the expected schema.")}var js=`# Query Tableau Data Source Tool
|
|
325
|
+
`,paramsSchema:Yd,annotations:{title:"List Pulse Metric Subscriptions for Current User",readOnlyHint:!0,openWorldHint:!1},callback:async(r,{requestId:o,authInfo:i})=>{let n=E();return await e.logAndExecute({requestId:o,authInfo:i,args:{},callback:async()=>await I({config:n,requestId:o,server:t,jwtScopes:["tableau:metric_subscriptions:read"],authInfo:N(i),callback:async s=>await s.pulseMethods.listPulseMetricSubscriptionsForCurrentUser()}),constrainSuccessResult:async s=>await Xd({subscriptions:s,boundedContext:n.boundedContext,restApiArgs:{config:n,requestId:o,server:t}}),getErrorText:de})}});return e};async function Xd({subscriptions:t,boundedContext:e,restApiArgs:r}){if(t.length===0)return{type:"empty",message:"No Pulse Metric Subscriptions were found. Either none exist or you do not have permission to view them."};let{datasourceIds:o}=e;if(!o)return{type:"success",result:t};let{config:i,requestId:n,server:s}=r;try{let a=await I({config:i,requestId:n,server:s,jwtScopes:["tableau:insight_metrics:read"],callback:async l=>await l.pulseMethods.listPulseMetricsFromMetricIds(t.map(u=>u.metric_id))});if(a.isErr())return{type:"error",message:["The set of allowed Pulse Metric Subscriptions that can be queried is limited by the server configuration.","While Pulse Metric Subscriptions were found, an error occurred while retrieving information about them to determine if they are allowed to be viewed.",W(a.error)].join(" ")};let c=new Set(a.value.filter(l=>o.has(l.datasource_luid)).map(l=>l.id));return t=t.filter(l=>c.has(l.metric_id)),t.length===0?{type:"empty",message:["The set of allowed Pulse Metric Subscriptions that can be queried is limited by the server configuration.","While Pulse Metric Subscriptions were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}catch(a){return{type:"error",message:["The set of allowed Pulse Metric Subscriptions that can be queried is limited by the server configuration.","While Pulse Metric Subscriptions were found, an error occurred while retrieving information about them to determine if they are allowed to be viewed.",W(a)].join(" ")}}}import{ZodiosError as lp}from"@zodios/core";import{Err as Ho}from"ts-results-es";import{z as cp}from"zod";import{z as Ke}from"zod";var ep=Ke.record(Ke.string().nonempty(),Ke.array(Ke.object({luid:Ke.string().optional(),u:Ke.string().nonempty(),p:Ke.string().nonempty()}).transform(({luid:t,u:e,p:r})=>({connectionLuid:t,connectionUsername:e,connectionPassword:r})))),On,Mn=!1,Nn=t=>{if(!Mn){Mn=!0;let{datasourceCredentials:e}=E();if(!e)return;let r;try{r=JSON.parse(e)}catch(i){throw new Error(`Invalid datasource credentials format. Could not parse JSON string: ${e}`,{cause:i})}let o=ep.parse(r);On=new Map(Object.entries(o))}return On?.get(t)};function Fn(t){let e={...t};switch(t.errorCode){case"400000":e.condition="Bad request",e.details="The content of the request body is invalid. Check for missing or incomplete JSON.";break;case"400800":e.condition="Invalid formula for calculation",e.details="Invalid custom calculation syntax. For help, see https://help.tableau.com/current/pro/desktop/en-us/functions_operators.htm";break;case"400802":e.condition="Invalid API request",e.details="The incoming request isn't valid per the OpenAPI specification.";break;case"400803":e.condition="Validation failed",e.details="The incoming request isn't valid per the validation rules.";break;case"400804":e.condition="Response too large",e.details="The response value exceeds the limit. You must apply a filter in your request.";break;case"401001":e.condition="Login error",e.details="The login failed for the given user.";break;case"401002":e.condition="Invalid authorization credentials",e.details="The provided auth token is formatted incorrectly.";break;case"403157":e.condition="Feature disabled",e.details="The feature is disabled.";break;case"403800":e.condition="API access permission denied",e.details="The user doesn't have API Access granted on the given data source. Set the API Access capability for the given data source to Allowed. For help, see https://help.tableau.com/current/online/en-us/permissions_capabilities.htm";break;case"404934":e.condition="Unknown field",e.details="The requested field doesn't exist.";break;case"404950":e.condition="API endpoint not found",e.details="The request endpoint doesn't exist.";break;case"408000":e.condition="Request timeout",e.details="The request timed out.";break;case"409000":e.condition="User already on site",e.details="HTTP status conflict.";break;case"429000":e.condition="Too many requests",e.details="Too many requests in the allotted amount of time. For help, see https://help.tableau.com/current/api/vizql-data-service/en-us/docs/vds_limitations.html#licensing-and-data-transfer";break;case"500000":e.condition="Internal server error",e.details="The request could not be completed.";break;case"500810":e.condition="VDS empty table response",e.details="The underlying data engine returned empty data value response.";break;case"500811":e.condition="VDS missing table",e.details="The underlying data engine returned empty metadata associated with response.";break;case"500812":e.condition="Error while processing an error",e.details="Internal processing error.";break;case"501000":e.condition="Not implemented",e.details="Can't find response from upstream server.";break;case"503800":e.condition="VDS unavailable",e.details="The underlying data engine is unavailable.";break;case"503801":e.condition="VDS discovery error",e.details="The upstream service can't be found.";break;case"504000":e.condition="Gateway timeout",e.details="The upstream service response timed out.";break}return e}function Un(t){if(t.length===0)throw new Error("The query must include at least one field. The fields property cannot be an empty array.");if(t.some(tp))throw new Error("The query must not include any fields with an empty fieldCaption.");{let e=t.reduce((o,i)=>(i.sortPriority===void 0||(o[i.sortPriority]||(o[i.sortPriority]=[]),o[i.sortPriority].push(i.fieldCaption)),o),{}),r=Object.entries(e).filter(([o,i])=>i.length>1);if(r.length>0){let o=r.reduce((i,[n,s])=>(i.push(`${s.map(a=>`"${a}"`).join(", ")} with a sort priority of ${n}`),i),[]);throw new Error(`The query must not include duplicate sort priorities. The following fields have sort priorities that are duplicated: ${o.join(". ")}.`)}}{let e=t.filter(Bo).map(r=>r.fieldCaption);if(e.length>0)throw new Error(`The query must not include fields that contain both a function and a calculation. The following fields contain both a function and a calculation: ${e.join(", ")}.`)}{let e=t.filter(rp).map(r=>r.fieldCaption);if(e.length>0)throw new Error(`The query must not include fields that have a maxDecimalPlaces value that is less than 0. The following fields have a maxDecimalPlaces value that is less than 0: ${e.join(", ")}.`)}}function tp(t){return!t.fieldCaption}function Bo(t){return!!("function"in t&&t.function&&"calculation"in t&&t.calculation)}function qn(t){return!!("fieldCaption"in t&&t.fieldCaption&&"calculation"in t&&t.calculation)}function rp(t){return t.maxDecimalPlaces!==void 0&&t.maxDecimalPlaces<0}import{Err as zo,Ok as op}from"ts-results-es";function Vn(t){if(t){if(t.some(e=>!("field"in e)))throw new Error("The query must not include filters with invalid fields. The following field errors occurred: The filter must include a field property.");{let e=t.reduce((o,i)=>("fieldCaption"in i.field&&(o[i.field.fieldCaption]||(o[i.field.fieldCaption]=0),o[i.field.fieldCaption]++),o),{}),r=Object.entries(e).filter(([o,i])=>i>1);if(r.length>0)throw new Error(`The query must not include multiple filters for the following fields: ${r.map(([o])=>o).join(", ")}.`)}{let e=t.reduce((r,o)=>{if(!("field"in o))return r;let i=jn(o.field);return i.isErr()&&r.push(i.error),r},[]);if(e.length>0)throw new Error(`The query must not include filters with invalid fields. The following field errors occurred: ${e.join(", ")}.`)}if(t.filter(r=>["SET","MATCH","DATE"].includes(r.filterType)&&("function"in r.field&&r.field.function||"calculation"in r.field&&r.field.calculation)).length>0)throw new Error("The query must not include Set Filters, Match Filters, or Relative Date Filters with functions or calculations.");if(t.filter(r=>r.filterType==="SET"&&r.values.length===0).length>0)throw new Error("The query must not include Set Filters with an empty values array.");if(t.filter(r=>{if(r.filterType!=="QUANTITATIVE_DATE")return!1;switch(r.quantitativeFilterType){case"RANGE":return isNaN(Date.parse(r.minDate))||isNaN(Date.parse(r.maxDate));case"MIN":return isNaN(Date.parse(r.minDate));case"MAX":return isNaN(Date.parse(r.maxDate))}}).length>0)throw new Error("The query must not include Quantitative Date Filters with invalid dates. Dates must use the RFC 3339 standard. Example: 2025-03-14");if(t.filter(r=>r.filterType==="DATE"&&r.anchorDate&&isNaN(Date.parse(r.anchorDate))).length>0)throw new Error("The query must not include Relative Date Filters with invalid anchor dates. Anchor dates must use the RFC 3339 standard. Example: 2025-03-14");{let e=t.reduce((r,o)=>{if(o.filterType!=="TOP")return r;let i=jn(o.fieldToMeasure);return i.isErr()&&r.push(i.error),r},[]);if(e.length>0)throw new Error(`The query must not include Top N filters with invalid fields. The following field errors occurred: ${e.join(", ")}`)}{let e=t.reduce((r,o)=>(o.filterType!=="MATCH"||!o.startsWith&&!o.endsWith&&!o.contains&&r.push(`The match filter for field "${o.field.fieldCaption}" must include at least one of the following properties: startsWith, endsWith, or contains`),r),[]);if(e.length>0)throw new Error(`The query must not include Match Filters with invalid fields. The following field errors occurred: ${e.join(", ")}.`)}}}function jn(t){if(ip(t))return new zo("The fieldCaption property must be a non-empty string.");if(qn(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new zo(`The field ${e} must not contain both a fieldCaption and a calculation.`.replace(" "," "))}if(Bo(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new zo(`The field ${e} must not contain both a function and a calculation.`.replace(" "," "))}return op.EMPTY}function ip(t){return"fieldCaption"in t&&!t.fieldCaption}function Bn({datasourceLuid:t,query:e}){kr({datasourceLuid:t});let{fields:r,filters:o}=e;if(Un(r),Vn(o),!Ht.safeParse(e).success)throw new Error("The query does not match the expected schema.")}var zn=`# Query Tableau Data Source Tool
|
|
322
326
|
|
|
323
327
|
Executes VizQL queries against Tableau data sources to answer business questions from published data. This tool allows you to retrieve aggregated and filtered data with proper sorting and grouping.
|
|
324
328
|
|
|
@@ -627,9 +631,7 @@ Filter relative date periods:
|
|
|
627
631
|
**Instead:**
|
|
628
632
|
- Use metadata tools to understand available fields
|
|
629
633
|
- Suggest alternative questions that can be answered with available data
|
|
630
|
-
- Recommend appropriate aggregation levels for the business question`;import
|
|
631
|
-
|
|
632
|
-
`);return new Vs({type:"filter-validation",message:f})}}let h=await c.vizqlDataServiceMethods.queryDatasource(m);return h.isErr()?new Vs(h.error instanceof Au?h.error:h.error==="feature-disabled"?{type:"feature-disabled"}:{type:"tableau-error",error:h.error}):h}})},getErrorText:s=>{switch(s.type){case"feature-disabled":return sr();case"filter-validation":return JSON.stringify({requestId:o,errorType:"validation",message:s.message});case"tableau-error":return JSON.stringify({requestId:o,...Ns(s.error)})}}})}});return e};import{Ok as Cu}from"ts-results-es";import{z as Ru}from"zod";var xu={viewId:Ru.string()},Ws=t=>{let e=new O({server:t,name:"get-view-data",description:"Retrieves data in comma separated value (CSV) format for the specified view in a Tableau workbook.",paramsSchema:xu,annotations:{title:"Get View Data",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r},{requestId:i})=>{let o=R();return await e.logAndExecute({requestId:i,args:{viewId:r},callback:async()=>new Cu(await P({config:o,requestId:i,server:t,jwtScopes:["tableau:views:download"],callback:async n=>await n.viewsMethods.queryViewData({viewId:r,siteId:n.siteId})}))})}});return e};import{Ok as vu}from"ts-results-es";import{z as ui}from"zod";function Hs(t){return{isError:!1,content:[{type:"image",data:Buffer.from(t).toString("base64"),mimeType:"image/png"}]}}var Lu={viewId:ui.string(),width:ui.number().gt(0).optional(),height:ui.number().gt(0).optional()},Gs=t=>{let e=new O({server:t,name:"get-view-image",description:"Retrieves an image of the specified view in a Tableau workbook. The width and height in pixels can be provided. The default width and height are both 800 pixels.",paramsSchema:Lu,annotations:{title:"Get View Image",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r,width:i,height:o},{requestId:n})=>{let s=R();return await e.logAndExecute({requestId:n,args:{viewId:r},callback:async()=>new vu(await P({config:s,requestId:n,server:t,jwtScopes:["tableau:views:download"],callback:async l=>await l.viewsMethods.queryViewImage({viewId:r,siteId:l.siteId,width:i,height:o,resolution:"high"})})),getSuccessResult:Hs})}});return e};import{Ok as Iu}from"ts-results-es";import{z as pi}from"zod";import{z as di}from"zod";var Qs=di.enum(["caption","contentUrl","createdAt","favoritesTotal","fields","hitsTotal","name","ownerDomain","ownerEmail","ownerName","projectName","sheetNumber","sheetType","tags","title","updatedAt","viewUrlname","workbookDescription","workbookName"]),Du={caption:["eq","in"],contentUrl:["eq","in"],createdAt:["eq","gt","gte","lt","lte"],favoritesTotal:["eq","gt","gte","lt","lte"],fields:["eq","in"],hitsTotal:["eq","gt","gte","lt","lte"],name:["eq","in"],ownerDomain:["eq","in"],ownerEmail:["eq","in"],ownerName:["eq","in"],projectName:["eq","in"],sheetNumber:["eq","gt","gte","lt","lte"],sheetType:["eq","in"],tags:["eq","in"],title:["eq","in"],updatedAt:["eq","gt","gte","lt","lte"],viewUrlname:["eq","in"],workbookDescription:["eq","in"],workbookName:["eq","in"]},Jw=di.object({field:Qs,operator:Pe,value:di.string()});function $s(t){return it({filterString:t,allowedOperatorsByField:Du,filterFieldSchema:Qs})}var Ou={filter:pi.string().optional(),pageSize:pi.number().gt(0).optional(),limit:pi.number().gt(0).optional()},Zs=t=>{let e=new O({server:t,name:"list-views",description:`
|
|
634
|
+
- Recommend appropriate aggregation levels for the business question`;import Kt from"fast-levenshtein";import{Err as Wo,Ok as Je}from"ts-results-es";async function Wn(t,e,r,o){if(!e.filters)return Je.EMPTY;let i=[],n=e.filters.filter(s=>(s.filterType==="SET"||s.filterType==="MATCH")&&"fieldCaption"in s.field&&s.field.fieldCaption);if(n.length===0)return Je.EMPTY;for(let s of n){let a=s.field.fieldCaption;try{if(s.filterType==="SET"){let c=await sp(s,r,o);c.isErr()&&i.push(c.error)}else if(s.filterType==="MATCH"){let c=await np(s,r,o);c.isErr()&&i.push(c.error)}}catch(c){ue.warning(t,`Filter value validation failed for field ${a}: ${c}`)}}return i.length>0?new Wo(i):Je.EMPTY}async function sp(t,e,r){let o=t.field.fieldCaption,i=t.values.map(p=>String(p)),s={datasource:r,query:{fields:[{fieldCaption:o,fieldAlias:"DistinctValues"}]},options:{returnFormat:"OBJECTS",debug:!0,disaggregate:!1}},a=await e.queryDatasource(s);if(a.isErr())return Je.EMPTY;let c=a.value.data||[],l=new Set(c.map(p=>String(p.DistinctValues||p[o]||""))),u=i.filter(p=>!l.has(p));if(u.length>0){let p=ap(u,Array.from(l),3,5),g=`Filter validation failed for field "${o}". The following values were not found: ${u.join(", ")}.`;return p.length>0&&(g+=` Did you mean: ${p.join(", ")}?`),g+=" Please evaluate whether you included the wrong filter value or if you are trying to filter on the wrong field entirely.",new Wo({field:o,invalidValues:u,sampleValues:p,message:g})}return Je.EMPTY}async function np(t,e,r){let o=t.field.fieldCaption,n={datasource:r,query:{fields:[{fieldCaption:o,fieldAlias:"SampleValues"}]},options:{returnFormat:"OBJECTS",debug:!0,disaggregate:!1}},s=await e.queryDatasource(n);if(s.isErr())return Je.EMPTY;let c=(s.value.data||[]).map(u=>String(u.SampleValues||u[o]||""));if(!c.some(u=>!(t.startsWith&&!u.startsWith(t.startsWith)||t.endsWith&&!u.endsWith(t.endsWith)||t.contains&&!u.includes(t.contains)))){let u=new Set;for(let f of c){if(u.size>=5)break;let y=f.toLowerCase(),w=t.startsWith?(()=>{let A=t.startsWith.toLowerCase(),x=A.length,R=Math.min(2,Math.floor(x/2)),j=y.slice(0,x);return Kt.get(A,j)<=R})():!0,v=t.endsWith?(()=>{let A=t.endsWith.toLowerCase(),x=A.length,R=Math.min(2,Math.floor(x/2)),j=y.slice(-x);return Kt.get(A,j)<=R})():!0,D=t.contains?(()=>{let A=t.contains.toLowerCase(),x=A.length,R=Math.min(2,Math.floor(x/2));return y.length>=x?Array.from({length:y.length-x+1},(j,F)=>Kt.get(A,y.slice(F,F+x))).some(j=>j<=R):Kt.get(A,y)<=R})():!0;w&&v&&D&&u.add(f)}let p=[];t.startsWith&&p.push(`starts with "${t.startsWith}"`),t.endsWith&&p.push(`ends with "${t.endsWith}"`),t.contains&&p.push(`contains "${t.contains}"`);let g=u.size>0?`Similar values in this field: ${Array.from(u).join(", ")}.`:"",b=`Filter validation failed for field "${o}". No values found that ${p.join(" and ")}. ${g} Please evaluate whether you included the wrong filter value or if you are trying to filter on the wrong field entirely.`;return new Wo({field:o,invalidValues:p,sampleValues:Array.from(u),message:b})}return Je.EMPTY}function ap(t,e,r=3,o=5){let i=[];for(let c of e){let l=t.map(u=>({value:u,distance:Kt.get(u.toLowerCase(),c.toLowerCase())})).filter(u=>u.distance<=r).sort((u,p)=>u.distance-p.distance);if(l.length>0){let u=l[0];i.push({invalidValue:u.value,suggestionForInvalidValue:c,distance:u.distance})}}i.sort((c,l)=>c.distance-l.distance);let n=[],s=Math.ceil(o/t.length),a=new Map;for(let c of t)a.set(c,0);for(let{invalidValue:c,suggestionForInvalidValue:l}of i){if(n.length===o)break;a.get(c)!==s&&(n.push(l),a.set(c,a.get(c)+1))}for(let{suggestionForInvalidValue:c}of i){if(n.length===o)break;if(n.includes(c))continue;n.push(c)}return n}var up={datasourceLuid:cp.string().nonempty(),query:Ht},Hn=t=>{let e=new O({server:t,name:"query-datasource",description:zn,paramsSchema:up,annotations:{title:"Query Datasource",readOnlyHint:!0,openWorldHint:!1},argsValidator:Bn,callback:async({datasourceLuid:r,query:o},{requestId:i,authInfo:n})=>{let s=E();return await e.logAndExecute({requestId:i,authInfo:n,args:{datasourceLuid:r,query:o},callback:async()=>{let a=await be.isDatasourceAllowed({datasourceLuid:r,restApiArgs:{config:s,requestId:i,server:t}});if(!a.allowed)return new Ho({type:"datasource-not-allowed",message:a.message});let c={datasourceLuid:r},l={returnFormat:"OBJECTS",debug:!0,disaggregate:!1},u=Nn(r);u&&(c.connections=u);let p={datasource:c,query:o,options:l};return await I({config:s,requestId:i,server:t,jwtScopes:["tableau:viz_data_service:read"],authInfo:N(n),callback:async g=>{if(!s.disableQueryDatasourceFilterValidation){let f=await Wn(t,o,g.vizqlDataServiceMethods,c);if(f.isErr()){let w=f.error.map(v=>v.message).join(", ");return new Ho({type:"filter-validation",message:w})}}let b=await g.vizqlDataServiceMethods.queryDatasource(p);return b.isErr()?new Ho(b.error instanceof lp?b.error:b.error==="feature-disabled"?{type:"feature-disabled"}:{type:"tableau-error",error:b.error}):b}})},constrainSuccessResult:a=>({type:"success",result:a}),getErrorText:a=>{switch(a.type){case"feature-disabled":return Ir();case"datasource-not-allowed":return a.message;case"filter-validation":return JSON.stringify({requestId:i,errorType:"validation",message:a.message});case"tableau-error":return JSON.stringify({requestId:i,...Fn(a.error)})}}})}});return e};import{Err as dp,Ok as pp}from"ts-results-es";import{z as mp}from"zod";var fp={viewId:mp.string()},Gn=t=>{let e=new O({server:t,name:"get-view-data",description:"Retrieves data in comma separated value (CSV) format for the specified view in a Tableau workbook.",paramsSchema:fp,annotations:{title:"Get View Data",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r},{requestId:o,authInfo:i})=>{let n=E();return await e.logAndExecute({requestId:o,authInfo:i,args:{viewId:r},callback:async()=>{let s=await be.isViewAllowed({viewId:r,restApiArgs:{config:n,requestId:o,server:t}});return s.allowed?new pp(await I({config:n,requestId:o,server:t,jwtScopes:["tableau:views:download"],authInfo:N(i),callback:async a=>await a.viewsMethods.queryViewData({viewId:r,siteId:a.siteId})})):new dp({type:"view-not-allowed",message:s.message})},constrainSuccessResult:s=>({type:"success",result:s}),getErrorText:s=>{switch(s.type){case"view-not-allowed":return s.message}}})}});return e};import{Err as hp,Ok as gp}from"ts-results-es";import{z as Go}from"zod";function $n(t){return{isError:!1,content:[{type:"image",data:Buffer.from(t).toString("base64"),mimeType:"image/png"}]}}var bp={viewId:Go.string(),width:Go.number().gt(0).optional(),height:Go.number().gt(0).optional()},Qn=t=>{let e=new O({server:t,name:"get-view-image",description:"Retrieves an image of the specified view in a Tableau workbook. The width and height in pixels can be provided. The default width and height are both 800 pixels.",paramsSchema:bp,annotations:{title:"Get View Image",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r,width:o,height:i},{requestId:n,authInfo:s})=>{let a=E();return await e.logAndExecute({requestId:n,authInfo:s,args:{viewId:r},callback:async()=>{let c=await be.isViewAllowed({viewId:r,restApiArgs:{config:a,requestId:n,server:t}});return c.allowed?new gp(await I({config:a,requestId:n,server:t,jwtScopes:["tableau:views:download"],authInfo:N(s),callback:async l=>await l.viewsMethods.queryViewImage({viewId:r,siteId:l.siteId,width:o,height:i,resolution:"high"})})):new hp({type:"view-not-allowed",message:c.message})},constrainSuccessResult:c=>({type:"success",result:c}),getSuccessResult:$n,getErrorText:c=>{switch(c.type){case"view-not-allowed":return c.message}}})}});return e};import{Ok as wp}from"ts-results-es";import{z as Qo}from"zod";import{z as $o}from"zod";var Kn=$o.enum(["caption","contentUrl","createdAt","favoritesTotal","fields","hitsTotal","name","ownerDomain","ownerEmail","ownerName","projectName","sheetNumber","sheetType","tags","title","updatedAt","viewUrlname","workbookDescription","workbookName"]),yp={caption:["eq","in"],contentUrl:["eq","in"],createdAt:["eq","gt","gte","lt","lte"],favoritesTotal:["eq","gt","gte","lt","lte"],fields:["eq","in"],hitsTotal:["eq","gt","gte","lt","lte"],name:["eq","in"],ownerDomain:["eq","in"],ownerEmail:["eq","in"],ownerName:["eq","in"],projectName:["eq","in"],sheetNumber:["eq","gt","gte","lt","lte"],sheetType:["eq","in"],tags:["eq","in"],title:["eq","in"],updatedAt:["eq","gt","gte","lt","lte"],viewUrlname:["eq","in"],workbookDescription:["eq","in"],workbookName:["eq","in"]},qS=$o.object({field:Kn,operator:Qe,value:$o.string()});function Jn(t){return Tt({filterString:t,allowedOperatorsByField:yp,filterFieldSchema:Kn})}var Tp={filter:Qo.string().optional(),pageSize:Qo.number().gt(0).optional(),limit:Qo.number().gt(0).optional()},Zn=t=>{let e=new O({server:t,name:"list-views",description:`
|
|
633
635
|
Retrieves a list of views on a Tableau site including their metadata such as name, owner, and the workbook they are found in. Supports optional filtering via field:operator:value expressions (e.g., name:eq:Overview) for precise and flexible view discovery. Use this tool when a user requests to list, search, or filter Tableau views on a site.
|
|
634
636
|
|
|
635
637
|
**Supported Filter Fields and Operators**
|
|
@@ -655,7 +657,7 @@ Filter relative date periods:
|
|
|
655
657
|
| workbookDescription | eq, in |
|
|
656
658
|
| workbookName | eq, in |
|
|
657
659
|
|
|
658
|
-
${
|
|
660
|
+
${wt}
|
|
659
661
|
|
|
660
662
|
**Example Usage:**
|
|
661
663
|
- List all views on a site
|
|
@@ -666,7 +668,7 @@ Filter relative date periods:
|
|
|
666
668
|
- List views created after January 1, 2023:
|
|
667
669
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
668
670
|
- List views with the name "Overview" in the "Finance" project and created after January 1, 2023:
|
|
669
|
-
filter: "name:eq:Overview,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:
|
|
671
|
+
filter: "name:eq:Overview,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:Tp,annotations:{title:"List Views",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=E(),c=r?Jn(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{},callback:async()=>new wp(await I({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:N(s),callback:async l=>await yt({pageConfig:{pageSize:o,limit:a.maxResultLimit?Math.min(a.maxResultLimit,i??Number.MAX_SAFE_INTEGER):i},getDataFn:async p=>{let{pagination:g,views:b}=await l.viewsMethods.queryViewsForSite({siteId:l.siteId,filter:c??"",includeUsageStatistics:!0,pageSize:p.pageSize,pageNumber:p.pageNumber});return{pagination:g,data:b}}})})),constrainSuccessResult:l=>Ap({views:l,boundedContext:a.boundedContext})})}});return e};function Ap({views:t,boundedContext:e}){if(t.length===0)return{type:"empty",message:"No views were found. Either none exist or you do not have permission to view them."};let{projectIds:r,workbookIds:o}=e;return r&&(t=t.filter(i=>i.project?.id?r.has(i.project.id):!1)),o&&(t=t.filter(i=>i.workbook?.id?o.has(i.workbook.id):!1)),t.length===0?{type:"empty",message:["The set of allowed views that can be queried is limited by the server configuration.","While views were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}import{Err as Ep,Ok as _p}from"ts-results-es";import{z as Sp}from"zod";var vp={workbookId:Sp.string()},Yn=t=>{let e=new O({server:t,name:"get-workbook",description:"Retrieves information about the specified workbook, including information about the views contained in the workbook.",paramsSchema:vp,annotations:{title:"Get Workbook",readOnlyHint:!0,openWorldHint:!1},callback:async({workbookId:r},{requestId:o,authInfo:i})=>{let n=E();return await e.logAndExecute({requestId:o,authInfo:i,args:{workbookId:r},callback:async()=>{let s=await be.isWorkbookAllowed({workbookId:r,restApiArgs:{config:n,requestId:o,server:t}});return s.allowed?new _p(await I({config:n,requestId:o,server:t,jwtScopes:["tableau:content:read"],authInfo:N(i),callback:async a=>{let c=s.content??await a.workbooksMethods.getWorkbook({workbookId:r,siteId:a.siteId});if(c.views){let l=await a.viewsMethods.queryViewsForWorkbook({workbookId:r,siteId:a.siteId,includeUsageStatistics:!0});c.views.view=l}return c}})):new Ep({type:"workbook-not-allowed",message:s.message})},constrainSuccessResult:s=>({type:"success",result:s}),getErrorText:s=>{switch(s.type){case"workbook-not-allowed":return s.message}}})}});return e};import{Ok as Rp}from"ts-results-es";import{z as Jo}from"zod";import{z as Ko}from"zod";var Xn=Ko.enum(["createdAt","contentUrl","displayTabs","favoritesTotal","hasAlerts","hasExtracts","name","ownerDomain","ownerEmail","ownerName","projectName","sheetCount","size","subscriptionTotal","tags","updatedAt"]),Cp={createdAt:["eq","gt","gte","lt","lte"],contentUrl:["eq","in"],displayTabs:["eq"],favoritesTotal:["eq","gt","gte","lt","lte"],hasAlerts:["eq"],hasExtracts:["eq"],name:["eq","in"],ownerDomain:["eq","in"],ownerEmail:["eq","in"],ownerName:["eq","in"],projectName:["eq","in"],sheetCount:["eq","gt","gte","lt","lte"],size:["eq","gt","gte","lt","lte"],subscriptionTotal:["eq","gt","gte","lt","lte"],tags:["eq","in"],updatedAt:["eq","gt","gte","lt","lte"]},uv=Ko.object({field:Xn,operator:Qe,value:Ko.string()});function ea(t){return Tt({filterString:t,allowedOperatorsByField:Cp,filterFieldSchema:Xn})}var xp={filter:Jo.string().optional(),pageSize:Jo.number().gt(0).optional(),limit:Jo.number().gt(0).optional()},ta=t=>{let e=new O({server:t,name:"list-workbooks",description:`
|
|
670
672
|
Retrieves a list of workbooks on a Tableau site including their metadata such as name, description, and information about the views contained in the workbook. Supports optional filtering via field:operator:value expressions (e.g., name:eq:Superstore) for precise and flexible workbook discovery. Use this tool when a user requests to list, search, or filter Tableau workbooks on a site.
|
|
671
673
|
|
|
672
674
|
**Supported Filter Fields and Operators**
|
|
@@ -689,7 +691,7 @@ Filter relative date periods:
|
|
|
689
691
|
| tags | eq, in |
|
|
690
692
|
| updatedAt | eq, gt, gte, lt, lte |
|
|
691
693
|
|
|
692
|
-
${
|
|
694
|
+
${wt}
|
|
693
695
|
|
|
694
696
|
**Example Usage:**
|
|
695
697
|
- List all workbooks on a site
|
|
@@ -700,10 +702,18 @@ Filter relative date periods:
|
|
|
700
702
|
- List workbooks created after January 1, 2023:
|
|
701
703
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
702
704
|
- List workbooks with the name "Superstore" in the "Finance" project and created after January 1, 2023:
|
|
703
|
-
filter: "name:eq:Superstore,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:
|
|
705
|
+
filter: "name:eq:Superstore,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:xp,annotations:{title:"List Workbooks",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=E(),c=r?ea(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{},callback:async()=>new Rp(await I({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:N(s),callback:async l=>await yt({pageConfig:{pageSize:o,limit:a.maxResultLimit?Math.min(a.maxResultLimit,i??Number.MAX_SAFE_INTEGER):i},getDataFn:async p=>{let{pagination:g,workbooks:b}=await l.workbooksMethods.queryWorkbooksForSite({siteId:l.siteId,filter:c??"",pageSize:p.pageSize,pageNumber:p.pageNumber});return{pagination:g,data:b}}})})),constrainSuccessResult:l=>Ip({workbooks:l,boundedContext:a.boundedContext})})}});return e};function Ip({workbooks:t,boundedContext:e}){if(t.length===0)return{type:"empty",message:"No workbooks were found. Either none exist or you do not have permission to view them."};let{projectIds:r,workbookIds:o}=e;return r&&(t=t.filter(i=>i.project?.id?r.has(i.project.id):!1)),o&&(t=t.filter(i=>o.has(i.id))),t.length===0?{type:"empty",message:["The set of allowed workbooks that can be queried is limited by the server configuration.","While workbooks were found, they were all filtered out by the server configuration."].join(" ")}:{type:"success",result:t}}var ra=[Tn,Sn,Hn,xn,In,kn,Dn,Ln,Rn,Yn,Gn,Qn,ta,Zn,gn];var Pe="tableau-mcp",Jt=mi.version,Cr=`${Pe}/${Jt}`,Ze=class extends kp{name;version;_clientInfo;get clientInfo(){return this._clientInfo??this.server.getClientVersion()}constructor({clientInfo:e}={}){super({name:Pe,version:Jt},{capabilities:{logging:{},tools:{}}}),this.name=Pe,this.version=Jt,this._clientInfo=e}registerTools=()=>{for(let{name:e,description:r,paramsSchema:o,annotations:i,callback:n}of this._getToolsToRegister())this.tool(e,r,o,i,n)};registerRequestHandlers=()=>{this.server.setRequestHandler(Pp,async e=>(Xe(this,e.params.level),{}))};_getToolsToRegister=()=>{let{includeTools:e,excludeTools:r}=E(),i=ra.map(n=>n(this)).filter(n=>e.length>0?e.includes(n.name):r.length>0?!r.includes(n.name):!0);if(i.length===0)throw new Error(`
|
|
704
706
|
No tools to register.
|
|
705
|
-
Tools available = [${
|
|
707
|
+
Tools available = [${jr.join(", ")}].
|
|
706
708
|
EXCLUDE_TOOLS = [${r.join(", ")}].
|
|
707
709
|
INCLUDE_TOOLS = [${e.join(", ")}]
|
|
708
|
-
`);return
|
|
710
|
+
`);return i}};import{StreamableHTTPServerTransport as om}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as im}from"@modelcontextprotocol/sdk/types.js";import sm from"cors";import ri from"express";import Ta,{existsSync as Aa}from"fs";import nm from"http";import am from"https";import{StreamableHTTPServerTransport as Dp}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as Lp}from"crypto";var Zo={},oa=({clientInfo:t})=>{let e=new Dp({sessionIdGenerator:()=>Lp(),onsessioninitialized:r=>{Zo[r]={transport:e,clientInfo:t}}});return e.onclose=()=>{e.sessionId&&Op(e.sessionId)},e},Yo=t=>Zo[t],Op=t=>{delete Zo[t]};function ia(t,e,r){let o=t.headers["mcp-protocol-version"];if(!o){r();return}let i=["2025-06-18","2025-03-26","2024-11-05"];if(!i.includes(o)){e.status(400).json({jsonrpc:"2.0",error:{code:-32600,message:"Unsupported protocol version",data:{supported:i,requested:o}},id:null});return}r()}import{createPrivateKey as em,createPublicKey as tm}from"crypto";import{readFileSync as rm}from"fs";function sa(t){t.get("/.well-known/oauth-authorization-server",(e,r)=>{let o=E().oauth.issuer;r.json({issuer:o,authorization_endpoint:`${o}/oauth/authorize`,token_endpoint:`${o}/oauth/token`,registration_endpoint:`${o}/oauth/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token","client_credentials"],code_challenge_methods_supported:["S256"],scopes_supported:[],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],subject_types_supported:["public"]})})}function na(t){t.get("/.well-known/oauth-protected-resource",(e,r)=>{let o=E().oauth.issuer;r.json({resource:`${o}/${Pe}`,authorization_servers:[o],bearer_methods_supported:["header"]})})}import{compactDecrypt as Mp}from"jose";import{Err as Zt,Ok as Np}from"ts-results-es";import{fromError as aa}from"zod-validation-error";function la(t){return async(e,r,o)=>{let i=e.headers.authorization;if(!i||!i.startsWith("Bearer ")){if(e.method==="GET"&&e.headers.accept?.includes("text/event-stream")){r.writeHead(401,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.write(`event: error
|
|
711
|
+
`),r.write(`data: {"error": "unauthorized", "error_description": "Authorization required"}
|
|
712
|
+
|
|
713
|
+
`),r.end();return}let a=`${e.protocol}://${e.get("host")}`;r.status(401).header("WWW-Authenticate",`Bearer realm="MCP", resource_metadata="${a}/.well-known/oauth-protected-resource"`).json({error:"unauthorized",error_description:"Authorization required. Use OAuth 2.1 flow."});return}let n=i.slice(7),s=await Fp(n,t);if(s.isErr()){if(e.method==="GET"&&e.headers.accept?.includes("text/event-stream")){r.writeHead(401,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.write(`event: error
|
|
714
|
+
`),r.write(`data: {"error": "invalid_token", "error_description": "${s.error}"}
|
|
715
|
+
|
|
716
|
+
`),r.end();return}r.status(401).json({error:"invalid_token",error_description:s.error});return}e.auth=s.value,o()}}async function Fp(t,e){let r=E();try{let{plaintext:o}=await Mp(t,e),i=JSON.parse(new TextDecoder().decode(o)),n=Fo.safeParse(i);if(!n.success)return Zt(`Invalid access token: ${aa(n.error).toString()}`);let{iss:s,aud:a,exp:c,clientId:l}=n.data;if(s!==r.oauth.issuer||a!==Yt||c<Math.floor(Date.now()/1e3))return new Zt("Invalid or expired access token");let u;if(r.auth==="oauth"){let p=cn.safeParse(i);if(!p.success)return Zt(`Invalid access token: ${aa(p.error).toString()}`);let{tableauAccessToken:g,tableauRefreshToken:b,tableauExpiresAt:f,tableauUserId:y,tableauServer:w,sub:v}=p.data;if(f<Math.floor(Date.now()/1e3))return new Zt("Invalid or expired access token");u={username:v,userId:y,server:w,accessToken:g,refreshToken:b}}else{let{tableauUserId:p,tableauServer:g,sub:b}=n.data;u={username:b,server:g,...p?{userId:p}:{}}}return Np({token:t,clientId:l,scopes:[],expiresAt:i.exp,extra:u})}catch{return new Zt("Invalid or expired access token")}}import{randomBytes as Xo,randomUUID as ca}from"crypto";import{fromError as qp}from"zod-validation-error";function Xt(t,e,...r){return e>2147483647?setTimeout(()=>{Xt(t,e-2147483647,...r)},2147483647):setTimeout(t,e,...r)}import{createHash as Up}from"crypto";function Mr(t){return Up("sha256").update(t).digest("base64url")}function Nr(t){if(typeof t!="string")return!1;try{let e=new URL(t);return e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1":!!e.protocol.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:$/)}catch{return!1}}function ua(t,e){let r=E();t.get("/oauth/authorize",(o,i)=>{let n=nn.safeParse(o.query);if(!n.success){i.status(400).json({error:"invalid_request",error_description:qp(n.error).toString()});return}let{clientId:s,redirectUri:a,responseType:c,codeChallenge:l,codeChallengeMethod:u,state:p}=n.data;if(c!=="code"){i.status(400).json({error:"unsupported_response_type",error_description:"Only authorization code flow is supported"});return}if(u!=="S256"){i.status(400).json({error:"invalid_request",error_description:"Only S256 code challenge method is supported"});return}if(!Nr(a)){i.status(400).json({error:"invalid_request",error_description:`Invalid redirect URI: ${a}`});return}let g=Xo(32).toString("hex"),b=Xo(32).toString("hex"),f=ca(),y=Math.floor(Math.random()*43)+22,w=Xo(y).toString("hex"),v=Mr(w);e.set(b,{clientId:s,redirectUri:a,codeChallenge:l,state:p??"",tableauState:g,tableauClientId:f,tableauCodeVerifier:w}),Xt(()=>e.delete(b),r.oauth.authzCodeTimeoutMs);let D=r.server||Fr,A=new URL(`${D}/oauth2/v1/auth`);A.searchParams.set("client_id",f),A.searchParams.set("code_challenge",v),A.searchParams.set("code_challenge_method","S256"),A.searchParams.set("response_type","code"),A.searchParams.set("redirect_uri",r.oauth.redirectUri),A.searchParams.set("state",`${b}:${g}`),A.searchParams.set("device_id",ca()),A.searchParams.set("target_site",r.siteName),A.searchParams.set("device_name",jp(a,p??"")),A.searchParams.set("client_type","tableau-mcp"),i.redirect(A.toString())})}function jp(t,e){let r="tableau-mcp (Unknown agent)";try{let o=new URL(t);return o.protocol==="https:"||o.protocol==="http:"?t==="https://vscode.dev/redirect"&&new URL(e).protocol==="vscode:"?"tableau-mcp (VS Code)":r:o.protocol==="cursor:"?"tableau-mcp (Cursor)":`tableau-mcp (${o.protocol.slice(0,-1)})`}catch{return r}}import{randomBytes as zp}from"crypto";import{Err as Wp,Ok as Hp}from"ts-results-es";import{fromError as Gp}from"zod-validation-error";import{Zodios as Bp}from"@zodios/core";import{makeApi as Vp}from"@zodios/core";import{z as ie}from"zod";var da=ie.discriminatedUnion("grant_type",[ie.object({grant_type:ie.literal("authorization_code"),code:ie.string(),code_verifier:ie.string(),redirect_uri:ie.string(),client_id:ie.string()}),ie.object({grant_type:ie.literal("refresh_token"),client_id:ie.string(),refresh_token:ie.string(),site_namespace:ie.string()})]),pa=ie.object({access_token:B("access_token"),expires_in:ie.number().int().nonnegative(),refresh_token:B("refresh_token"),origin_host:B("origin_host")}).transform(t=>({accessToken:t.access_token,expiresInSeconds:t.expires_in,refreshToken:t.refresh_token,originHost:t.origin_host}));var ma=Vp([{method:"post",path:"/oauth2/v1/token",alias:"token",response:pa,parameters:[{name:"body",type:"Body",schema:da}]}]);var fa=t=>new Bp(t,ma);async function Ur(t,e){return await fa(t).token(e,{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Cr}})}function ha(t,e,r){let o=E();t.get("/Callback",async(i,n)=>{let s=ln.safeParse(i.query);if(!s.success){n.status(400).json({error:"invalid_request",error_description:Gp(s.error).toString()});return}let{error:a,code:c,state:l}=s.data;if(a){n.status(400).json({error:"access_denied",error_description:"User denied authorization"});return}try{let[u,p]=l?.split(":")??[],g=e.get(u);if(!g||g.tableauState!==p){n.status(400).json({error:"invalid_request",error_description:"Invalid state parameter"});return}let b=await $p({server:o.server||Fr,code:c??"",redirectUri:o.oauth.redirectUri,clientId:g.tableauClientId,codeVerifier:g.tableauCodeVerifier});if(b.isErr()){n.status(400).json({error:"invalid_request",error_description:b.error});return}let{accessToken:f,refreshToken:y,expiresInSeconds:w,originHost:v}=b.value,D=new URL(`https://${v}`);if(o.server){let ae=new URL(o.server);if(D.hostname!==ae.hostname){n.status(400).json({error:"invalid_request",error_description:`Invalid origin host: ${v}. Expected: ${new URL(o.server).hostname}`});return}}let A=D.toString(),x=new bt(A);x.setCredentials(f,"unknown user id");let R=await x.serverMethods.getCurrentServerSession();if(R.isErr()){R.error.type==="unauthorized"?n.status(401).json({error:"unauthorized",error_description:`Unable to get the Tableau server session. Error: ${JSON.stringify(R.error)}`}):n.status(500).json({error:"server_error",error_description:"Internal server error during authorization. Unable to get the Tableau server session. Contact your administrator."});return}let j=zp(32).toString("hex");r.set(j,{clientId:g.clientId,redirectUri:g.redirectUri,codeChallenge:g.codeChallenge,user:R.value.user,server:A,tableauClientId:g.tableauClientId,tokens:{accessToken:f,refreshToken:y,expiresInSeconds:w},expiresAt:Math.floor((Date.now()+o.oauth.authzCodeTimeoutMs)/1e3)}),e.delete(u);let F=new URL(g.redirectUri);F.searchParams.set("code",j),F.searchParams.set("state",g.state),n.redirect(F.toString())}catch(u){console.error("OAuth callback error:",u),n.status(500).json({error:"server_error",error_description:"Internal server error during authorization. Contact your administrator."})}})}async function $p({server:t,code:e,redirectUri:r,clientId:o,codeVerifier:i}){try{let n=await Ur(t,{grant_type:"authorization_code",code:e,redirect_uri:r,client_id:o,code_verifier:i});return Hp(n)}catch{return Wp("Failed to exchange authorization code")}}import Qp from"express";function ga(t){t.post("/oauth/register",Qp.json(),(e,r)=>{let{redirect_uris:o}=e.body,i=[];if(o&&Array.isArray(o))for(let s of o){if(!Nr(s)){r.status(400).json({error:"invalid_redirect_uri",error_description:`Invalid redirect URI: ${s}`});return}i.push(s)}let{token_endpoint_auth_method:n}=e.body;(!n||typeof n!="string"||!["client_secret_basic","client_secret_post"].includes(n))&&(n="client_secret_basic"),r.json({client_id:"mcp-public-client",redirect_uris:i,grant_types:["authorization_code","client_credentials"],response_types:["code"],token_endpoint_auth_method:n,application_type:"native"})})}import{randomBytes as ba,timingSafeEqual as Kp}from"crypto";import{CompactEncrypt as ya}from"jose";import{Err as De,Ok as ti}from"ts-results-es";import{fromError as Jp}from"zod-validation-error";function wa(t,e,r,o){let i=E();t.post("/oauth/token",async(n,s)=>{let a=an.safeParse(n.body);if(!a.success){s.status(400).json({error:"invalid_request",error_description:Jp(a.error).toString()});return}let c=Xp({required:a.data.grantType==="client_credentials",clientId:a.data.clientId,clientSecret:a.data.clientSecret,clientIdSecretPairs:E().oauth.clientIdSecretPairs,authorizationHeader:n.headers.authorization});if(c.isErr()){s.status(401).json({error:"invalid_client",error_description:c.error});return}try{switch(a.data.grantType){case"authorization_code":{let{code:l,codeVerifier:u}=a.data,p=e.get(l);if(!p||p.expiresAt<Math.floor(Date.now()/1e3)){e.delete(l),s.status(400).json({error:"invalid_grant",error_description:"Invalid or expired authorization code"});return}if(Mr(u)!==p.codeChallenge){s.status(400).json({error:"invalid_grant",error_description:"Invalid code verifier"});return}let b=ba(32).toString("hex"),f=await ei(p,o);r.set(b,{user:p.user,server:p.server,clientId:p.clientId,tokens:p.tokens,expiresAt:Math.floor((Date.now()+i.oauth.refreshTokenTimeoutMs)/1e3),tableauClientId:p.tableauClientId}),Xt(()=>r.delete(b),i.oauth.refreshTokenTimeoutMs),e.delete(l),s.json({access_token:f,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3,refresh_token:b});return}case"client_credentials":{let l=await Zp({clientId:c.value.clientId,server:i.server},o);s.json({access_token:l,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3});return}case"refresh_token":{let{refreshToken:l}=a.data,u=r.get(l);if(!u||u.expiresAt<Math.floor(Date.now()/1e3)){r.delete(l),s.status(400).json({error:"invalid_grant",error_description:"Invalid or expired refresh token"});return}let p,{refreshToken:g}=u.tokens,b=await Yp(u.server,g,u.tableauClientId);if(b.isErr())p=await ei({user:u.user,clientId:u.clientId,server:u.server,tokens:u.tokens},o);else{let{accessToken:y,refreshToken:w,expiresInSeconds:v}=b.value;p=await ei({user:u.user,clientId:u.clientId,server:u.server,tokens:{accessToken:y,refreshToken:w,expiresInSeconds:v}},o)}r.delete(l);let f=ba(32).toString("hex");r.set(f,{user:u.user,server:u.server,clientId:u.clientId,tokens:u.tokens,expiresAt:Math.floor((Date.now()+i.oauth.refreshTokenTimeoutMs)/1e3),tableauClientId:u.tableauClientId}),s.json({access_token:p,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3,refresh_token:f});return}}}catch(l){console.error("Token endpoint error:",l),s.status(500).json({error:"server_error",error_description:"Internal server error"});return}})}async function ei(t,e){let r=E(),o=JSON.stringify({sub:t.user.name,clientId:t.clientId,tableauServer:t.server,tableauUserId:t.user.id,iat:Math.floor(Date.now()/1e3),exp:Math.floor((Date.now()+r.oauth.accessTokenTimeoutMs)/1e3),aud:Yt,iss:r.oauth.issuer,...r.auth==="oauth"?{tableauAccessToken:t.tokens.accessToken,tableauRefreshToken:t.tokens.refreshToken,tableauExpiresAt:Math.floor(Date.now()/1e3)+t.tokens.expiresInSeconds,tableauUserId:t.user.id}:{}});return await new ya(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function Zp(t,e){let r=E(),o=JSON.stringify({sub:t.clientId,clientId:t.clientId,tableauServer:t.server,iat:Math.floor(Date.now()/1e3),exp:Math.floor((Date.now()+r.oauth.accessTokenTimeoutMs)/1e3),aud:Yt,iss:r.oauth.issuer});return await new ya(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function Yp(t,e,r){try{let o=await Ur(t,{grant_type:"refresh_token",refresh_token:e,client_id:r,site_namespace:""});return ti(o)}catch{return De("Failed to exchange refresh token")}}function Xp({required:t,clientId:e,clientSecret:r,clientIdSecretPairs:o,authorizationHeader:i}){if(!e&&!r&&t){if(!i)return De("Authorization header is required");let[l,u]=i.split(" ");if(l!=="Basic")return De("Invalid authorization type");if([e,r]=Buffer.from(u,"base64").toString().split(":"),!e||!r)return De("Invalid client credentials")}if(!t)return ti({clientId:""});if(!e)return De("Client ID is required");if(!r)return De("Client secret is required");let n=o?.[e];if(!n||r.length!==n.length)return De("Invalid client credentials");let s=new TextEncoder,a=s.encode(r),c=s.encode(n);return a.byteLength!==c.byteLength||!Kp(a,c)?De("Invalid client credentials"):ti({clientId:e})}var Fr="https://online.tableau.com",Yt="tableau-mcp-server",qr=class{config=E();pendingAuthorizations=new Map;authorizationCodes=new Map;refreshTokens=new Map;privateKey;publicKey;constructor(){this.privateKey=this.getPrivateKey(),this.publicKey=tm(this.privateKey)}get authMiddleware(){return la(this.privateKey)}setupRoutes(e){sa(e),na(e),ga(e),ua(e,this.pendingAuthorizations),ha(e,this.pendingAuthorizations,this.authorizationCodes),wa(e,this.authorizationCodes,this.refreshTokens,this.publicKey)}getPrivateKey(){let e=this.config.oauth.jwePrivateKey.replace(/\\n/g,`
|
|
717
|
+
`);if(!e)try{e=rm(this.config.oauth.jwePrivateKeyPath,"utf8")}catch{throw new Error("Failed to read private key file")}try{return em({key:e,format:"pem",passphrase:this.config.oauth.jwePrivateKeyPassphrase})}catch{throw new Error("Failed to create private key")}}};var oi="mcp-session-id";async function va({basePath:t,config:e,logLevel:r}){let o=ri();o.use(ri.json()),o.use(ri.urlencoded()),o.use(sm({origin:e.corsOriginConfig,credentials:!0,allowedHeaders:["Content-Type","Authorization","Cache-Control","Accept","MCP-Protocol-Version"],exposedHeaders:[oi,"x-session-id"]})),e.trustProxyConfig!==null&&o.set("trust proxy",e.trustProxyConfig);let i=[];if(e.oauth.enabled){let l=new qr;l.setupRoutes(o),i.push(l.authMiddleware),i.push(ia)}let n=`/${t}`;if(o.post(n,...i,c),o.get(n,...i,e.disableSessionManagement?_a:Sa),o.delete(n,...i,e.disableSessionManagement?_a:Sa),!!!(e.sslKey&&e.sslCert))return new Promise(l=>{let u=nm.createServer(o).listen(e.httpPort,()=>l({url:`http://localhost:${e.httpPort}/${t}`,app:o,server:u}))});if(!Aa(e.sslKey))throw new Error("SSL key file does not exist");if(!Aa(e.sslCert))throw new Error("SSL cert file does not exist");let a={key:Ta.readFileSync(e.sslKey),cert:Ta.readFileSync(e.sslCert)};return new Promise(l=>{let u=am.createServer(a,o).listen(e.httpPort,()=>l({url:`https://localhost:${e.httpPort}/${t}`,app:o,server:u}))});async function c(l,u){try{let p;if(e.disableSessionManagement){let g=new Ze;p=new om({sessionIdGenerator:void 0}),u.on("close",()=>{p.close(),g.close()}),await Ea(g,p,r)}else{let g=l.headers[oi],b;if(g&&(b=Yo(g)))p=b.transport;else if(!g&&im(l.body)){let f=l.body.params.clientInfo;p=oa({clientInfo:f});let y=new Ze({clientInfo:f});await Ea(y,p,r)}else{u.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});return}}await p.handleRequest(l,u,l.body)}catch(p){console.error("Error handling MCP request:",p),u.headersSent||u.status(500).json({jsonrpc:"2.0",error:{code:-32603,message:"Internal server error"},id:null})}}}async function Ea(t,e,r){t.registerTools(),t.registerRequestHandlers(),await t.connect(e),Xe(t,r)}async function _a(t,e){e.writeHead(405).end(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}))}async function Sa(t,e){let r=t.headers[oi],o;if(!r||!(o=Yo(r))){e.status(400).send("Invalid or missing session ID");return}await o.transport.handleRequest(t,e)}async function um(){cm.config();let t=E(),e=ui(t.defaultLogLevel)?t.defaultLogLevel:"debug";switch(t.enableServerLogging&&di(new tr({logDirectory:t.serverLogDirectory})),t.transport){case"stdio":{let r=new Ze;r.registerTools(),r.registerRequestHandlers();let o=new lm;await r.connect(o),Xe(r,e),ue.info(r,`${r.name} v${r.version} running on stdio`);break}case"http":{let{url:r}=await va({basePath:Pe,config:t,logLevel:e});t.oauth.enabled||console.warn('\u26A0\uFE0F TRANSPORT is "http" but OAuth is disabled! Your MCP server may not be protected from unauthorized access! By having explicitly disabled OAuth by setting the DANGEROUSLY_DISABLE_OAUTH environment variable to "true", you accept any and all risks associated with this decision.'),console.log(`${Pe} v${Jt} ${t.disableSessionManagement?"stateless ":""}streamable HTTP server available at ${r}`);break}}t.disableLogMasking&&Me("\u26A0\uFE0F Log masking is disabled!")}try{await um()}catch(t){Me(`Fatal error when starting the server: ${W(t)}`),process.exit(1)}
|
|
718
|
+
/* v8 ignore file -- @preserve */
|
|
709
719
|
//# sourceMappingURL=index.js.map
|