@tableau/mcp-server 1.12.0 → 1.13.1
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/build/index.js +560 -35
- package/build/index.js.map +4 -4
- package/package.json +6 -2
package/build/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var Ka=Object.defineProperty;var Ja=(t,e)=>{for(var r in e)Ka(t,r,{get:e[r],enumerable:!0})};import{StdioServerTransport as Zm}from"@modelcontextprotocol/sdk/server/stdio.js";import Xm from"dotenv";import{existsSync as Xa}from"fs";import{join as el}from"path";import{fileURLToPath as tl}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"],Ya=["datasource","workbook","view","pulse","content-exploration"],Yr={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 Zr(t){return!!Jr.find(e=>e===t)}function Xr(t){return!!Ya.find(e=>e===t)}var Za=["stdio","http"];function wi(t){return!!Za.find(e=>e===t)}function ce(t,e){if(!t)throw new Error(e||"Invariant Violation")}var rl=tl(new URL(".",import.meta.url)),ro=10*60*1e3,Ai=60*60*1e3,Ei=24*60*60*1e3,Si=30*24*60*60*1e3,ol=365.25*24*60*60*1e3,il=["pat","direct-trust","oauth"];function sl(t){return!!il.find(e=>e===t)}var to=class{auth;server;transport;sslKey;sslCert;httpPort;corsOriginConfig;trustProxyConfig;siteName;patName;patValue;jwtSubClaim;connectedAppClientId;connectedAppSecretId;connectedAppSecretValue;jwtAdditionalPayload;datasourceCredentials;defaultLogLevel;disableLogMasking;includeTools;excludeTools;maxResultLimit;disableQueryDatasourceValidationRequests;disableMetadataApiRequests;disableSessionManagement;enableServerLogging;serverLogDirectory;boundedContext;tableauServerVersionCheckIntervalInHours;oauth;constructor(){let e=cl(process.env),{AUTH:r,SERVER:o,SITE_NAME:i,TRANSPORT:n,SSL_KEY:s,SSL_CERT:a,HTTP_PORT_ENV_VAR_NAME:l,CORS_ORIGIN_CONFIG:c,TRUST_PROXY_CONFIG:u,PAT_NAME:p,PAT_VALUE:g,JWT_SUB_CLAIM:b,CONNECTED_APP_CLIENT_ID:m,CONNECTED_APP_SECRET_ID:y,CONNECTED_APP_SECRET_VALUE:T,JWT_ADDITIONAL_PAYLOAD:v,DATASOURCE_CREDENTIALS:P,DEFAULT_LOG_LEVEL:S,DISABLE_LOG_MASKING:C,INCLUDE_TOOLS:x,EXCLUDE_TOOLS:q,MAX_RESULT_LIMIT:F,DISABLE_QUERY_DATASOURCE_VALIDATION_REQUESTS:te,DISABLE_METADATA_API_REQUESTS:pe,DISABLE_SESSION_MANAGEMENT:Se,ENABLE_SERVER_LOGGING:ve,SERVER_LOG_DIRECTORY:ne,INCLUDE_PROJECT_IDS:le,INCLUDE_DATASOURCE_IDS:G,INCLUDE_WORKBOOK_IDS:J,TABLEAU_SERVER_VERSION_CHECK_INTERVAL_IN_HOURS:Ce,DANGEROUSLY_DISABLE_OAUTH:_,OAUTH_ISSUER:E,OAUTH_JWE_PRIVATE_KEY:W,OAUTH_JWE_PRIVATE_KEY_PATH:K,OAUTH_JWE_PRIVATE_KEY_PASSPHRASE:j,OAUTH_REDIRECT_URI:re,OAUTH_CLIENT_ID_SECRET_PAIRS:me,OAUTH_CIMD_DNS_SERVERS:Z,OAUTH_AUTHORIZATION_CODE_TIMEOUT_MS:oe,OAUTH_ACCESS_TOKEN_TIMEOUT_MS:tr,OAUTH_REFRESH_TOKEN_TIMEOUT_MS:St}=e;if(this.siteName=i??"",this.sslKey=s?.trim()??"",this.sslCert=a?.trim()??"",this.httpPort=Et(e[l?.trim()||"PORT"],{defaultValue:3927,minValue:1,maxValue:65535}),this.corsOriginConfig=al(c?.trim()??""),this.trustProxyConfig=ll(u?.trim()??""),this.datasourceCredentials=P??"",this.defaultLogLevel=S??"debug",this.disableLogMasking=C==="true",this.disableQueryDatasourceValidationRequests=te==="true",this.disableMetadataApiRequests=pe==="true",this.disableSessionManagement=Se==="true",this.enableServerLogging=ve==="true",this.serverLogDirectory=ne||el(rl,"logs"),this.boundedContext={projectIds:eo(le),datasourceIds:eo(G),workbookIds:eo(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=Et(Ce,{defaultValue:1,minValue:1,maxValue:24*7});let Q=_==="true";if(this.oauth={enabled:Q?!1:!!E,issuer:E??"",redirectUri:re||(E?`${E}/Callback`:""),jwePrivateKey:W??"",jwePrivateKeyPath:K??"",jwePrivateKeyPassphrase:j||void 0,dnsServers:Z?Z.split(",").map(Re=>Re.trim()):["1.1.1.1","1.0.0.1"],authzCodeTimeoutMs:Et(oe,{defaultValue:ro,minValue:0,maxValue:Ai}),accessTokenTimeoutMs:Et(tr,{defaultValue:Ai,minValue:0,maxValue:Si}),refreshTokenTimeoutMs:Et(St,{defaultValue:Si,minValue:0,maxValue:ol}),clientIdSecretPairs:me?me.split(",").reduce((Re,fe)=>{let[bi,Ti]=fe.split(":");return bi&&Ti&&(Re[bi]=Ti),Re},{}):null},this.auth=sl(r)?r:this.oauth.enabled?"oauth":"pat",this.transport=wi(n)?n:this.oauth.enabled?"http":"stdio",this.transport==="http"&&!Q&&!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(Q)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"),nl(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"&&!Xa(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 Kr=F?parseInt(F):NaN;if(this.maxResultLimit=isNaN(Kr)||Kr<=0?null:Kr,this.includeTools=x?x.split(",").flatMap(Re=>{let fe=Re.trim();return Zr(fe)?fe:Xr(fe)?Yr[fe]:[]}):[],this.excludeTools=q?q.split(",").flatMap(Re=>{let fe=Re.trim();return Zr(fe)?fe:Xr(fe)?Yr[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(m,"The environment variable CONNECTED_APP_CLIENT_ID is not set"),ce(y,"The environment variable CONNECTED_APP_SECRET_ID is not set"),ce(T,"The environment variable CONNECTED_APP_SECRET_VALUE is not set")),this.server=o??"",this.patName=p??"",this.patValue=g??"",this.jwtSubClaim=b??"",this.connectedAppClientId=m??"",this.connectedAppSecretId=y??"",this.connectedAppSecretValue=T??"",this.jwtAdditionalPayload=v||"{}"}};function nl(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 al(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 ll(t){return t?t.match(/^true|false$/i)?t.toLowerCase()==="true":t.match(/^\d+$/)?parseInt(t,10):t:null}function eo(t){return t===void 0?null:new Set(t.trim().split(",").map(e=>e.trim()).filter(Boolean))}function cl(t){return Object.entries(t).reduce((e,[r,o])=>(o?.startsWith("${user_config.")?e[r]="":e[r]=o,e),{})}function Et(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 A=()=>new to;var oo=["debug","info","notice","warning","error","critical","alert","emergency"],_t="debug",_i;function vi(t){return!!oo.find(e=>e===t)}var et=(t,e,{silent:r=!1}={})=>{_t!==e&&(_t=e,r||ue.notice(t,`Logging level set to: ${e}`))},Ci=t=>{_i=t},ue={debug:xe("debug"),info:xe("info"),notice:xe("notice"),warning:xe("warning"),error:xe("error"),critical:xe("critical"),alert:xe("alert"),emergency:xe("emergency")},Ue=(t=_t)=>oo.indexOf(t)>=oo.indexOf(_t),Fe=t=>{process.env.TABLEAU_MCP_TEST!=="true"&&(t=t.endsWith(`
|
|
3
3
|
`)?t:`${t}
|
|
4
|
-
`,process.stderr.write(t))},
|
|
5
|
-
`)}catch(d){Le(`Failed to write to log file ${i}: ${W(d)}`)}});this._fileMutexes.set(n,a),a.finally(()=>{this._fileMutexes.get(n)===a&&this._fileMutexes.delete(n)}),await a}};import{McpServer as dp}from"@modelcontextprotocol/sdk/server/mcp.js";import{SetLevelRequestSchema as pp}from"@modelcontextprotocol/sdk/types.js";var ii={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.0",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","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 pd}from"ts-results-es";import{z as on}from"zod";import{Err as si,Ok as Pa}from"ts-results-es";var ni=t=>{let e=li(t);if(e.isErr())return t;let r=e.value;return Pe("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},ai=t=>{let e=li(t);if(e.isErr())return t;let r=e.value;return Pe("debug")?r.data?.credentials&&(r.data.credentials="<redacted>"):(delete r.data,delete r.headers),r};function li(t){try{return Pa(structuredClone(t))}catch(e){if(e instanceof Error)return si(e);let r=W(e);return Le(`Could not clone object, notification may not be sanitized! Error: ${r}`),si(new Error(r))}}function Jt(t){return{method:t.method??"UNKNOWN METHOD",url:t.url??"UNKNOWN URL",headers:t.headers,data:t.data,params:t.params}}function Zt(t){return{url:t.config.url??"UNKNOWN URL",status:t.status,headers:t.headers,data:t.data}}import{Zodios as pi}from"@zodios/core";import{randomUUID as La}from"node:crypto";import{SignJWT as Oa}from"jose";async function ci({username:t,connectedApp:e,scopes:r,additionalPayload:o}){let i={alg:"HS256",typ:"JWT",kid:e.secretId},n={jti:La(),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 Oa(n).setProtectedHeader(i).sign(new TextEncoder().encode(e.secretValue))}import{makeApi as Ma,makeEndpoint as di}from"@zodios/core";import{z as ye}from"zod";import{z as Oe}from"zod";var ui=Oe.object({credentials:Oe.object({site:Oe.object({id:Oe.string()}),user:Oe.object({id:Oe.string()}),token:Oe.string()})});var Na=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()})))}),Fa=di({method:"post",path:"/auth/signin",alias:"signIn",description:"Signs in with Tableau credentials.",response:ui,parameters:[{name:"credentials",type:"Body",schema:Na}]}),Ua=di({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()}),qa=Ma([Fa,Ua]),Vr=[...qa];var Me=class{_apiClient;constructor(e){this._apiClient=e}get interceptors(){return this._apiClient.axios.interceptors}};var H=class extends Me{_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 yt=class extends Me{constructor(e){super(new pi(e,Vr))}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 ci({username:e.username,connectedApp:{clientId:e.clientId,secretId:e.secretId,secretValue:e.secretValue},scopes:e.scopes,additionalPayload:e.additionalPayload})}}})()}})).credentials},Yt=class extends H{constructor(e,r){super(new pi(e,Vr),r)}signOut=async()=>{await this._apiClient.signOut(void 0,{...this.authHeader})}};import{Zodios as Ga}from"@zodios/core";import{makeApi as Ba,makeEndpoint as za}from"@zodios/core";import{z as Je}from"zod";import{z as k}from"zod";var ja=k.enum(["hitsTotal","hitsSmallSpanTotal","hitsMediumSpanTotal","hitsLargeSpanTotal","downstreamWorkbookCount"]),mi=k.array(k.object({method:ja,sortDirection:k.enum(["asc","desc"]).default("asc").optional()})).nonempty(),fi=k.enum(["lens","datasource","virtualconnection","collection","project","flow","datarole","table","database","view","workbook"]),hi=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()]),Br=k.object({contentTypes:k.array(fi).nonempty(),ownerIds:k.array(k.number().int()).nonempty(),modifiedTime:hi}).partial(),gi=k.union([Br.extend({contentTypes:k.array(fi).nonempty()}).strict(),Br.extend({ownerIds:k.array(k.number().int()).nonempty()}).strict(),Br.extend({modifiedTime:hi}).strict()]),Va=k.object({uri:k.string(),content:k.record(k.string(),k.unknown())}),bi=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(Va)}).partial();var Wa=za({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:Je.string().optional()},{name:"page",type:"Query",schema:Je.number().int().optional()},{name:"limit",type:"Query",schema:Je.number().int().optional()},{name:"order_by",type:"Query",schema:Je.string().optional()},{name:"filter",type:"Query",schema:Je.string().optional()}],response:Je.object({hits:bi})}),Ha=Ba([Wa]),yi=[...Ha];var wt=class extends H{constructor(e,r){super(new Ga(e,yi),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 Za}from"@zodios/core";import{makeApi as $a,makeEndpoint as Ti}from"@zodios/core";import{z as Ne}from"zod";import{z as er}from"zod";import{z as zr}from"zod";var Xt=zr.object({name:zr.string(),id:zr.string()});var Wr=er.object({id:er.string(),name:er.string(),description:er.string().optional(),project:Xt});import{z as tr}from"zod";var Ze=tr.object({pageNumber:tr.coerce.number(),pageSize:tr.coerce.number(),totalAvailable:tr.coerce.number()});import{z as wi}from"zod";var Ye=[{name:"pageSize",type:"Query",schema:wi.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:wi.number().optional(),description:"The offset for paging. The default is 1."}];var Qa=Ti({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:[...Ye,{name:"siteId",type:"Path",schema:Ne.string()},{name:"filter",type:"Query",schema:Ne.string().optional(),description:"Filter string in the format field:operator:value (e.g., name:eq:Project Views)"}],response:Ne.object({pagination:Ze,datasources:Ne.object({datasource:Ne.optional(Ne.array(Wr))})})}),Ka=Ti({method:"get",path:"/sites/:siteId/datasources/:datasourceId",alias:"queryDatasource",description:"Returns information about the specified data source.",response:Ne.object({datasource:Wr})}),Ja=$a([Qa,Ka]),Ai=[...Ja];var Tt=class extends H{constructor(e,r){super(new Za(e,Ai),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 ol}from"@zodios/core";import{makeApi as Ya,makeEndpoint as Xa}from"@zodios/core";import{z as D}from"zod";var el=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()}))}))})}),tl=Xa({method:"post",path:"/graphql",alias:"graphql",response:el,parameters:[{name:"query",type:"Body",schema:D.object({query:D.string()})}]}),rl=Ya([tl]),Ei=[...rl];var At=class extends H{constructor(e,r){super(new ol(e,Ei),r)}graphql=async e=>await this._apiClient.graphql({query:e},{...this.authHeader})};import{Zodios as cu}from"@zodios/core";import{Err as ks,Ok as uu}from"ts-results-es";function Et(t,e){return function(){return t.apply(e,arguments)}}var{toString:il}=Object.prototype,{getPrototypeOf:Gr}=Object,{iterator:or,toStringTag:Si}=Symbol,ir=(t=>e=>{let r=il.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),fe=t=>(t=t.toLowerCase(),e=>ir(e)===t),sr=t=>e=>typeof e===t,{isArray:et}=Array,Xe=sr("undefined");function _t(t){return t!==null&&!Xe(t)&&t.constructor!==null&&!Xe(t.constructor)&&ie(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var Ci=fe("ArrayBuffer");function sl(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Ci(t.buffer),e}var nl=sr("string"),ie=sr("function"),vi=sr("number"),St=t=>t!==null&&typeof t=="object",al=t=>t===!0||t===!1,rr=t=>{if(ir(t)!=="object")return!1;let e=Gr(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Si in t)&&!(or in t)},ll=t=>{if(!St(t)||_t(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},cl=fe("Date"),ul=fe("File"),dl=fe("Blob"),pl=fe("FileList"),ml=t=>St(t)&&ie(t.pipe),fl=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ie(t.append)&&((e=ir(t))==="formdata"||e==="object"&&ie(t.toString)&&t.toString()==="[object FormData]"))},hl=fe("URLSearchParams"),[gl,bl,yl,wl]=["ReadableStream","Request","Response","Headers"].map(fe),Tl=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ct(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let o,i;if(typeof t!="object"&&(t=[t]),et(t))for(o=0,i=t.length;o<i;o++)e.call(null,t[o],o,t);else{if(_t(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 Ri(t,e){if(_t(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 Fe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,xi=t=>!Xe(t)&&t!==Fe;function Hr(){let{caseless:t,skipUndefined:e}=xi(this)&&this||{},r={},o=(i,n)=>{let s=t&&Ri(r,n)||n;rr(r[s])&&rr(i)?r[s]=Hr(r[s],i):rr(i)?r[s]=Hr({},i):et(i)?r[s]=i.slice():(!e||!Xe(i))&&(r[s]=i)};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&Ct(arguments[i],o);return r}var Al=(t,e,r,{allOwnKeys:o}={})=>(Ct(e,(i,n)=>{r&&ie(i)?t[n]=Et(i,r):t[n]=i},{allOwnKeys:o}),t),El=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),_l=(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)},Sl=(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&&Gr(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},Cl=(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(et(t))return t;let e=t.length;if(!vi(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},Rl=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&Gr(Uint8Array)),xl=(t,e)=>{let o=(t&&t[or]).call(t),i;for(;(i=o.next())&&!i.done;){let n=i.value;e.call(t,n[0],n[1])}},Il=(t,e)=>{let r,o=[];for(;(r=t.exec(e))!==null;)o.push(r);return o},kl=fe("HTMLFormElement"),Dl=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,o,i){return o.toUpperCase()+i}),_i=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),Pl=fe("RegExp"),Ii=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),o={};Ct(r,(i,n)=>{let s;(s=e(i,n,t))!==!1&&(o[n]=s||i)}),Object.defineProperties(t,o)},Ll=t=>{Ii(t,(e,r)=>{if(ie(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let o=t[r];if(ie(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+"'")})}})},Ol=(t,e)=>{let r={},o=i=>{i.forEach(n=>{r[n]=!0})};return et(t)?o(t):o(String(t).split(e)),r},Ml=()=>{},Nl=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function Fl(t){return!!(t&&ie(t.append)&&t[Si]==="FormData"&&t[or])}var Ul=t=>{let e=new Array(10),r=(o,i)=>{if(St(o)){if(e.indexOf(o)>=0)return;if(_t(o))return o;if(!("toJSON"in o)){e[i]=o;let n=et(o)?[]:{};return Ct(o,(s,a)=>{let d=r(s,i+1);!Xe(d)&&(n[a]=d)}),e[i]=void 0,n}}return o};return r(t,0)},ql=fe("AsyncFunction"),jl=t=>t&&(St(t)||ie(t))&&ie(t.then)&&ie(t.catch),ki=((t,e)=>t?setImmediate:e?((r,o)=>(Fe.addEventListener("message",({source:i,data:n})=>{i===Fe&&n===r&&o.length&&o.shift()()},!1),i=>{o.push(i),Fe.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ie(Fe.postMessage)),Vl=typeof queueMicrotask<"u"?queueMicrotask.bind(Fe):typeof process<"u"&&process.nextTick||ki,Bl=t=>t!=null&&ie(t[or]),u={isArray:et,isArrayBuffer:Ci,isBuffer:_t,isFormData:fl,isArrayBufferView:sl,isString:nl,isNumber:vi,isBoolean:al,isObject:St,isPlainObject:rr,isEmptyObject:ll,isReadableStream:gl,isRequest:bl,isResponse:yl,isHeaders:wl,isUndefined:Xe,isDate:cl,isFile:ul,isBlob:dl,isRegExp:Pl,isFunction:ie,isStream:ml,isURLSearchParams:hl,isTypedArray:Rl,isFileList:pl,forEach:Ct,merge:Hr,extend:Al,trim:Tl,stripBOM:El,inherits:_l,toFlatObject:Sl,kindOf:ir,kindOfTest:fe,endsWith:Cl,toArray:vl,forEachEntry:xl,matchAll:Il,isHTMLForm:kl,hasOwnProperty:_i,hasOwnProp:_i,reduceDescriptors:Ii,freezeMethods:Ll,toObjectSet:Ol,toCamelCase:Dl,noop:Ml,toFiniteNumber:Nl,findKey:Ri,global:Fe,isContextDefined:xi,isSpecCompliantForm:Fl,toJSONObject:Ul,isAsyncFn:ql,isThenable:jl,setImmediate:ki,asap:Vl,isIterable:Bl};function tt(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)}u.inherits(tt,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:u.toJSONObject(this.config),code:this.code,status:this.status}}});var Di=tt.prototype,Pi={};["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=>{Pi[t]={value:t}});Object.defineProperties(tt,Pi);Object.defineProperty(Di,"isAxiosError",{value:!0});tt.from=(t,e,r,o,i,n)=>{let s=Object.create(Di);u.toFlatObject(t,s,function(c){return c!==Error.prototype},l=>l!=="isAxiosError");let a=t&&t.message?t.message:"Error",d=e==null&&t?t.code:e;return tt.call(s,a,d,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=tt;import zl from"form-data";var nr=zl;function $r(t){return u.isPlainObject(t)||u.isArray(t)}function Oi(t){return u.endsWith(t,"[]")?t.slice(0,-2):t}function Li(t,e,r){return t?t.concat(e).map(function(i,n){return i=Oi(i),!r&&n?"["+i+"]":i}).join(r?".":""):e}function Wl(t){return u.isArray(t)&&!t.some($r)}var Hl=u.toFlatObject(u,{},null,function(e){return/^is[A-Z]/.test(e)});function Gl(t,e,r){if(!u.isObject(t))throw new TypeError("target must be an object");e=e||new(nr||FormData),r=u.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(b,y){return!u.isUndefined(y[b])});let o=r.metaTokens,i=r.visitor||c,n=r.dots,s=r.indexes,d=(r.Blob||typeof Blob<"u"&&Blob)&&u.isSpecCompliantForm(e);if(!u.isFunction(i))throw new TypeError("visitor must be a function");function l(f){if(f===null)return"";if(u.isDate(f))return f.toISOString();if(u.isBoolean(f))return f.toString();if(!d&&u.isBlob(f))throw new T("Blob is not supported. Use a Buffer instead.");return u.isArrayBuffer(f)||u.isTypedArray(f)?d&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function c(f,b,y){let S=f;if(f&&!y&&typeof f=="object"){if(u.endsWith(b,"{}"))b=o?b:b.slice(0,-2),f=JSON.stringify(f);else if(u.isArray(f)&&Wl(f)||(u.isFileList(f)||u.endsWith(b,"[]"))&&(S=u.toArray(f)))return b=Oi(b),S.forEach(function(A,R){!(u.isUndefined(A)||A===null)&&e.append(s===!0?Li([b],R,n):s===null?b:b+"[]",l(A))}),!1}return $r(f)?!0:(e.append(Li(y,b,n),l(f)),!1)}let m=[],g=Object.assign(Hl,{defaultVisitor:c,convertValue:l,isVisitable:$r});function w(f,b){if(!u.isUndefined(f)){if(m.indexOf(f)!==-1)throw Error("Circular reference detected in "+b.join("."));m.push(f),u.forEach(f,function(S,P){(!(u.isUndefined(S)||S===null)&&i.call(e,S,u.isString(P)?P.trim():P,b,g))===!0&&w(S,b?b.concat(P):[P])}),m.pop()}}if(!u.isObject(t))throw new TypeError("data must be an object");return w(t),e}var Re=Gl;function Mi(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(o){return e[o]})}function Ni(t,e){this._pairs=[],t&&Re(t,this,e)}var Fi=Ni.prototype;Fi.append=function(e,r){this._pairs.push([e,r])};Fi.toString=function(e){let r=e?function(o){return e.call(this,o,Mi)}:Mi;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var Ui=Ni;function $l(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ue(t,e,r){if(!e)return t;let o=r&&r.encode||$l;u.isFunction(r)&&(r={serialize:r});let i=r&&r.serialize,n;if(i?n=i(e,r):n=u.isURLSearchParams(e)?e.toString():new Ui(e,r).toString(o),n){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t}var Qr=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){u.forEach(this.handlers,function(o){o!==null&&e(o)})}},Kr=Qr;var rt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};import Kl from"crypto";import Ql from"url";var qi=Ql.URLSearchParams;var Jr="abcdefghijklmnopqrstuvwxyz",ji="0123456789",Vi={DIGIT:ji,ALPHA:Jr,ALPHA_DIGIT:Jr+Jr.toUpperCase()+ji},Jl=(t=16,e=Vi.ALPHA_DIGIT)=>{let r="",{length:o}=e,i=new Uint32Array(t);Kl.randomFillSync(i);for(let n=0;n<t;n++)r+=e[i[n]%o];return r},Bi={isNode:!0,classes:{URLSearchParams:qi,FormData:nr,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:Vi,generateString:Jl,protocols:["http","https","file","data"]};var Xr={};ma(Xr,{hasBrowserEnv:()=>Yr,hasStandardBrowserEnv:()=>Zl,hasStandardBrowserWebWorkerEnv:()=>Yl,navigator:()=>Zr,origin:()=>Xl});var Yr=typeof window<"u"&&typeof document<"u",Zr=typeof navigator=="object"&&navigator||void 0,Zl=Yr&&(!Zr||["ReactNative","NativeScript","NS"].indexOf(Zr.product)<0),Yl=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Xl=Yr&&window.location.href||"http://localhost";var L={...Xr,...Bi};function eo(t,e){return Re(t,new L.classes.URLSearchParams,{visitor:function(r,o,i,n){return L.isNode&&u.isBuffer(r)?(this.append(o,r.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...e})}function ec(t){return u.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function tc(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 rc(t){function e(r,o,i,n){let s=r[n++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),d=n>=r.length;return s=!s&&u.isArray(i)?i.length:s,d?(u.hasOwnProp(i,s)?i[s]=[i[s],o]:i[s]=o,!a):((!i[s]||!u.isObject(i[s]))&&(i[s]=[]),e(r,o,i[s],n)&&u.isArray(i[s])&&(i[s]=tc(i[s])),!a)}if(u.isFormData(t)&&u.isFunction(t.entries)){let r={};return u.forEachEntry(t,(o,i)=>{e(ec(o),i,r,0)}),r}return null}var ar=rc;function oc(t,e,r){if(u.isString(t))try{return(e||JSON.parse)(t),u.trim(t)}catch(o){if(o.name!=="SyntaxError")throw o}return(r||JSON.stringify)(t)}var to={transitional:rt,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){let o=r.getContentType()||"",i=o.indexOf("application/json")>-1,n=u.isObject(e);if(n&&u.isHTMLForm(e)&&(e=new FormData(e)),u.isFormData(e))return i?JSON.stringify(ar(e)):e;if(u.isArrayBuffer(e)||u.isBuffer(e)||u.isStream(e)||u.isFile(e)||u.isBlob(e)||u.isReadableStream(e))return e;if(u.isArrayBufferView(e))return e.buffer;if(u.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 eo(e,this.formSerializer).toString();if((a=u.isFileList(e))||o.indexOf("multipart/form-data")>-1){let d=this.env&&this.env.FormData;return Re(a?{"files[]":e}:e,d&&new d,this.formSerializer)}}return n||i?(r.setContentType("application/json",!1),oc(e)):e}],transformResponse:[function(e){let r=this.transitional||to.transitional,o=r&&r.forcedJSONParsing,i=this.responseType==="json";if(u.isResponse(e)||u.isReadableStream(e))return e;if(e&&u.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}}};u.forEach(["delete","get","head","post","put","patch"],t=>{to.headers[t]={}});var ot=to;var ic=u.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"]),zi=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]&&
|
|
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[
|
|
8
|
-
`,hc=kt.encode(Ve),gc=2,co=class{constructor(e,r){let{escapeName:o}=this.constructor,i=u.isString(r),n=`Content-Disposition: form-data; name="${o(e)}"${!i&&r.name?`; filename="${o(r.name)}"`:""}${Ve}`;i?r=kt.encode(String(r).replace(/\r?\n|\r\n?/g,Ve)):n+=`Content-Type: ${r.type||"application/octet-stream"}${Ve}`,this.headers=kt.encode(n+Ve),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+gc,this.name=e,this.value=r}async*encode(){yield this.headers;let{value:e}=this;u.isTypedArray(e)?yield e:yield*cr(e),yield hc}static escapeName(e){return String(e).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},bc=(t,e,r)=>{let{tag:o="form-data-boundary",size:i=25,boundary:n=o+"-"+L.generateString(i,fc)}=r||{};if(!u.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=kt.encode("--"+n+Ve),a=kt.encode("--"+n+"--"+Ve),d=a.byteLength,l=Array.from(t.entries()).map(([m,g])=>{let w=new co(m,g);return d+=w.size,w});d+=s.byteLength*l.length,d=u.toFiniteNumber(d);let c={"Content-Type":`multipart/form-data; boundary=${n}`};return Number.isFinite(d)&&(c["Content-Length"]=d),e&&e(c),mc.from(async function*(){for(let m of l)yield s,yield*m.encode();yield a}())},$i=bc;import yc from"stream";var uo=class extends yc.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)}},Qi=uo;var wc=(t,e)=>u.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,Ki=wc;function Tc(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(d){let l=Date.now(),c=o[n];s||(s=l),r[i]=d,o[i]=l;let m=n,g=0;for(;m!==i;)g+=r[m++],m=m%t;if(i=(i+1)%t,i===n&&(n=(n+1)%t),l-s<e)return;let w=c&&l-c;return w?Math.round(g*1e3/w):void 0}}var Ji=Tc;function Ac(t,e){let r=0,o=1e3/e,i,n,s=(l,c=Date.now())=>{r=c,i=null,n&&(clearTimeout(n),n=null),t(...l)};return[(...l)=>{let c=Date.now(),m=c-r;m>=o?s(l,c):(i=l,n||(n=setTimeout(()=>{n=null,s(i)},o-m)))},()=>i&&s(i)]}var Zi=Ac;var _e=(t,e,r=3)=>{let o=0,i=Ji(50,250);return Zi(n=>{let s=n.loaded,a=n.lengthComputable?n.total:void 0,d=s-o,l=i(d),c=s<=a;o=s;let m={loaded:s,total:a,progress:a?s/a:void 0,bytes:d,rate:l||void 0,estimated:l&&a&&c?(a-s)/l:void 0,event:n,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(m)},r)},st=(t,e)=>{let r=t!=null;return[o=>e[0]({lengthComputable:r,total:t,loaded:o}),e[1]]},nt=t=>(...e)=>u.asap(()=>t(...e));function po(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 w=o.charCodeAt(g+1),f=o.charCodeAt(g+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,g+=2)}let a=0,d=s-1,l=g=>g>=2&&o.charCodeAt(g-2)===37&&o.charCodeAt(g-1)===51&&(o.charCodeAt(g)===68||o.charCodeAt(g)===100);d>=0&&(o.charCodeAt(d)===61?(a++,d--):l(d)&&(a++,d-=3)),a===1&&d>=0&&(o.charCodeAt(d)===61||l(d))&&a++;let m=Math.floor(n/4)*3-(a||0);return m>0?m:0}return Buffer.byteLength(o,"utf8")}var Yi={flush:xe.constants.Z_SYNC_FLUSH,finishFlush:xe.constants.Z_SYNC_FLUSH},xc={flush:xe.constants.BROTLI_OPERATION_FLUSH,finishFlush:xe.constants.BROTLI_OPERATION_FLUSH},Xi=u.isFunction(xe.createBrotliDecompress),{http:Ic,https:kc}=vc,Dc=/https:?/,es=L.protocols.map(t=>t+":"),ts=(t,[e,r])=>(t.on("end",r).on("error",r),e);function Pc(t,e){t.beforeRedirects.proxy&&t.beforeRedirects.proxy(t),t.beforeRedirects.config&&t.beforeRedirects.config(t,e)}function os(t,e,r){let o=e;if(!o&&o!==!1){let i=Ec.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){os(n,e,n.href)}}var Lc=typeof process<"u"&&u.kindOf(process)==="process",Oc=t=>new Promise((e,r)=>{let o,i,n=(d,l)=>{i||(i=!0,o&&o(d,l))},s=d=>{n(d),e(d)},a=d=>{n(d,!0),r(d)};t(s,a,d=>o=d).catch(a)}),Mc=({address:t,family:e})=>{if(!u.isString(t))throw TypeError("address must be a string");return{address:t,family:e||(t.indexOf(".")<0?6:4)}},rs=(t,e)=>Mc(u.isObject(t)?t:{address:t,family:e}),is=Lc&&function(e){return Oc(async function(o,i,n){let{data:s,lookup:a,family:d}=e,{responseType:l,responseEncoding:c}=e,m=e.method.toUpperCase(),g,w=!1,f;if(a){let _=Ki(a,C=>u.isArray(C)?C:[C]);a=(C,z,K)=>{_(C,z,(N,oe,be)=>{if(N)return K(N);let Z=u.isArray(oe)?oe.map(X=>rs(X)):[rs(oe,be)];z.all?K(N,Z):K(N,Z[0].address,Z[0].family)})}}let b=new Rc,y=()=>{e.cancelToken&&e.cancelToken.unsubscribe(S),e.signal&&e.signal.removeEventListener("abort",S),b.removeAllListeners()};n((_,C)=>{g=!0,C&&(w=!0,y())});function S(_){b.emit("abort",!_||_.type?new ae(null,e,f):_)}b.once("abort",i),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(S),e.signal&&(e.signal.aborted?S():e.signal.addEventListener("abort",S)));let P=qe(e.baseURL,e.url,e.allowAbsoluteUrls),A=new URL(P,L.hasBrowserEnv?L.origin:void 0),R=A.protocol||es[0];if(R==="data:"){if(e.maxContentLength>-1){let C=String(e.url||P||"");if(po(C)>e.maxContentLength)return i(new T("maxContentLength size of "+e.maxContentLength+" exceeded",T.ERR_BAD_RESPONSE,e))}let _;if(m!=="GET")return we(o,i,{status:405,statusText:"method not allowed",headers:{},config:e});try{_=so(e.url,l==="blob",{Blob:e.env&&e.env.Blob})}catch(C){throw T.from(C,T.ERR_BAD_REQUEST,e)}return l==="text"?(_=_.toString(c),(!c||c==="utf8")&&(_=u.stripBOM(_))):l==="stream"&&(_=at.Readable.from(_)),we(o,i,{data:_,status:200,statusText:"OK",headers:new V,config:e})}if(es.indexOf(R)===-1)return i(new T("Unsupported protocol "+R,T.ERR_BAD_REQUEST,e));let x=V.from(e.headers).normalize();x.set("User-Agent","axios/"+je,!1);let{onUploadProgress:q,onDownloadProgress:U}=e,le=e.maxRate,me,Ae;if(u.isSpecCompliantForm(s)){let _=x.getContentType(/boundary=([-_\w\d]{10,70})/i);s=$i(s,C=>{x.set(C)},{tag:`axios-${je}-boundary`,boundary:_&&_[1]||void 0})}else if(u.isFormData(s)&&u.isFunction(s.getHeaders)){if(x.set(s.getHeaders()),!x.hasContentLength())try{let _=await Cc.promisify(s.getLength).call(s);Number.isFinite(_)&&_>=0&&x.setContentLength(_)}catch{}}else if(u.isBlob(s)||u.isFile(s))s.size&&x.setContentType(s.type||"application/octet-stream"),x.setContentLength(s.size||0),s=at.Readable.from(cr(s));else if(s&&!u.isStream(s)){if(!Buffer.isBuffer(s))if(u.isArrayBuffer(s))s=Buffer.from(new Uint8Array(s));else if(u.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(x.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 Se=u.toFiniteNumber(x.getContentLength());u.isArray(le)?(me=le[0],Ae=le[1]):me=Ae=le,s&&(q||me)&&(u.isStream(s)||(s=at.Readable.from(s,{objectMode:!1})),s=at.pipeline([s,new lo({maxRate:u.toFiniteNumber(me)})],u.noop),q&&s.on("progress",ts(s,st(Se,_e(nt(q),!1,3)))));let ne;if(e.auth){let _=e.auth.username||"",C=e.auth.password||"";ne=_+":"+C}if(!ne&&A.username){let _=A.username,C=A.password;ne=_+":"+C}ne&&x.delete("authorization");let ce;try{ce=Ue(A.pathname+A.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(_){let C=new Error(_.message);return C.config=e,C.url=e.url,C.exists=!0,i(C)}x.set("Accept-Encoding","gzip, compress, deflate"+(Xi?", br":""),!1);let Q={path:ce,method:m,headers:x.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:ne,protocol:R,family:d,beforeRedirect:Pc,beforeRedirects:{}};!u.isUndefined(a)&&(Q.lookup=a),e.socketPath?Q.socketPath=e.socketPath:(Q.hostname=A.hostname.startsWith("[")?A.hostname.slice(1,-1):A.hostname,Q.port=A.port,os(Q,e.proxy,R+"//"+A.hostname+(A.port?":"+A.port:"")+Q.path));let G,Ce=Dc.test(Q.protocol);if(Q.agent=Ce?e.httpsAgent:e.httpAgent,e.transport?G=e.transport:e.maxRedirects===0?G=Ce?Sc:_c:(e.maxRedirects&&(Q.maxRedirects=e.maxRedirects),e.beforeRedirect&&(Q.beforeRedirects.config=e.beforeRedirect),G=Ce?kc:Ic),e.maxBodyLength>-1?Q.maxBodyLength=e.maxBodyLength:Q.maxBodyLength=1/0,e.insecureHTTPParser&&(Q.insecureHTTPParser=e.insecureHTTPParser),f=G.request(Q,function(C){if(f.destroyed)return;let z=[C],K=+C.headers["content-length"];if(U||Ae){let X=new lo({maxRate:u.toFiniteNumber(Ae)});U&&X.on("progress",ts(X,st(K,_e(nt(U),!0,3)))),z.push(X)}let N=C,oe=C.req||f;if(e.decompress!==!1&&C.headers["content-encoding"])switch((m==="HEAD"||C.statusCode===204)&&delete C.headers["content-encoding"],(C.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":z.push(xe.createUnzip(Yi)),delete C.headers["content-encoding"];break;case"deflate":z.push(new Qi),z.push(xe.createUnzip(Yi)),delete C.headers["content-encoding"];break;case"br":Xi&&(z.push(xe.createBrotliDecompress(xc)),delete C.headers["content-encoding"])}N=z.length>1?at.pipeline(z,u.noop):z[0];let be=at.finished(N,()=>{be(),y()}),Z={status:C.statusCode,statusText:C.statusMessage,headers:new V(C.headers),config:e,request:oe};if(l==="stream")Z.data=N,we(o,i,Z);else{let X=[],Ee=0;N.on("data",function(J){X.push(J),Ee+=J.length,e.maxContentLength>-1&&Ee>e.maxContentLength&&(w=!0,N.destroy(),i(new T("maxContentLength size of "+e.maxContentLength+" exceeded",T.ERR_BAD_RESPONSE,e,oe)))}),N.on("aborted",function(){if(w)return;let J=new T("stream has been aborted",T.ERR_BAD_RESPONSE,e,oe);N.destroy(J),i(J)}),N.on("error",function(J){f.destroyed||i(T.from(J,null,e,oe))}),N.on("end",function(){try{let J=X.length===1?X[0]:Buffer.concat(X);l!=="arraybuffer"&&(J=J.toString(c),(!c||c==="utf8")&&(J=u.stripBOM(J))),Z.data=J}catch(J){return i(T.from(J,null,e,Z.request,Z))}we(o,i,Z)})}b.once("abort",X=>{N.destroyed||(N.emit("error",X),N.destroy())})}),b.once("abort",_=>{i(_),f.destroy(_)}),f.on("error",function(C){i(T.from(C,null,e,f))}),f.on("socket",function(C){C.setKeepAlive(!0,1e3*60)}),e.timeout){let _=parseInt(e.timeout,10);if(Number.isNaN(_)){i(new T("error trying to parse `config.timeout` to int",T.ERR_BAD_OPTION_VALUE,e,f));return}f.setTimeout(_,function(){if(g)return;let z=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",K=e.transitional||rt;e.timeoutErrorMessage&&(z=e.timeoutErrorMessage),i(new T(z,K.clarifyTimeoutError?T.ETIMEDOUT:T.ECONNABORTED,e,f)),S()})}if(u.isStream(s)){let _=!1,C=!1;s.on("end",()=>{_=!0}),s.once("error",z=>{C=!0,f.destroy(z)}),s.on("close",()=>{!_&&!C&&S(new ae("Request stream has been aborted",e,f))}),s.pipe(f)}else f.end(s)})};var ss=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 ns=L.hasStandardBrowserEnv?{write(t,e,r,o,i,n){let s=[t+"="+encodeURIComponent(e)];u.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),u.isString(o)&&s.push("path="+o),u.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 as=t=>t instanceof V?{...t}:t;function he(t,e){e=e||{};let r={};function o(l,c,m,g){return u.isPlainObject(l)&&u.isPlainObject(c)?u.merge.call({caseless:g},l,c):u.isPlainObject(c)?u.merge({},c):u.isArray(c)?c.slice():c}function i(l,c,m,g){if(u.isUndefined(c)){if(!u.isUndefined(l))return o(void 0,l,m,g)}else return o(l,c,m,g)}function n(l,c){if(!u.isUndefined(c))return o(void 0,c)}function s(l,c){if(u.isUndefined(c)){if(!u.isUndefined(l))return o(void 0,l)}else return o(void 0,c)}function a(l,c,m){if(m in e)return o(l,c);if(m in t)return o(void 0,l)}let d={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,c,m)=>i(as(l),as(c),m,!0)};return u.forEach(Object.keys({...t,...e}),function(c){let m=d[c]||i,g=m(t[c],e[c],c);u.isUndefined(g)&&m!==a||(r[c]=g)}),r}var ur=t=>{let e=he({},t),{data:r,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:n,headers:s,auth:a}=e;if(e.headers=s=V.from(s),e.url=Ue(qe(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&s.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),u.isFormData(r)){if(L.hasStandardBrowserEnv||L.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(u.isFunction(r.getHeaders)){let d=r.getHeaders(),l=["content-type","content-length"];Object.entries(d).forEach(([c,m])=>{l.includes(c.toLowerCase())&&s.set(c,m)})}}if(L.hasStandardBrowserEnv&&(o&&u.isFunction(o)&&(o=o(e)),o||o!==!1&&ss(e.url))){let d=i&&n&&ns.read(n);d&&s.set(i,d)}return e};var Nc=typeof XMLHttpRequest<"u",ls=Nc&&function(t){return new Promise(function(r,o){let i=ur(t),n=i.data,s=V.from(i.headers).normalize(),{responseType:a,onUploadProgress:d,onDownloadProgress:l}=i,c,m,g,w,f;function b(){w&&w(),f&&f(),i.cancelToken&&i.cancelToken.unsubscribe(c),i.signal&&i.signal.removeEventListener("abort",c)}let y=new XMLHttpRequest;y.open(i.method.toUpperCase(),i.url,!0),y.timeout=i.timeout;function S(){if(!y)return;let A=V.from("getAllResponseHeaders"in y&&y.getAllResponseHeaders()),x={data:!a||a==="text"||a==="json"?y.responseText:y.response,status:y.status,statusText:y.statusText,headers:A,config:t,request:y};we(function(U){r(U),b()},function(U){o(U),b()},x),y=null}"onloadend"in y?y.onloadend=S:y.onreadystatechange=function(){!y||y.readyState!==4||y.status===0&&!(y.responseURL&&y.responseURL.indexOf("file:")===0)||setTimeout(S)},y.onabort=function(){y&&(o(new T("Request aborted",T.ECONNABORTED,t,y)),y=null)},y.onerror=function(R){let x=R&&R.message?R.message:"Network Error",q=new T(x,T.ERR_NETWORK,t,y);q.event=R||null,o(q),y=null},y.ontimeout=function(){let R=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",x=i.transitional||rt;i.timeoutErrorMessage&&(R=i.timeoutErrorMessage),o(new T(R,x.clarifyTimeoutError?T.ETIMEDOUT:T.ECONNABORTED,t,y)),y=null},n===void 0&&s.setContentType(null),"setRequestHeader"in y&&u.forEach(s.toJSON(),function(R,x){y.setRequestHeader(x,R)}),u.isUndefined(i.withCredentials)||(y.withCredentials=!!i.withCredentials),a&&a!=="json"&&(y.responseType=i.responseType),l&&([g,f]=_e(l,!0),y.addEventListener("progress",g)),d&&y.upload&&([m,w]=_e(d),y.upload.addEventListener("progress",m),y.upload.addEventListener("loadend",w)),(i.cancelToken||i.signal)&&(c=A=>{y&&(o(!A||A.type?new ae(null,t,y):A),y.abort(),y=null)},i.cancelToken&&i.cancelToken.subscribe(c),i.signal&&(i.signal.aborted?c():i.signal.addEventListener("abort",c)));let P=It(i.url);if(P&&L.protocols.indexOf(P)===-1){o(new T("Unsupported protocol "+P+":",T.ERR_BAD_REQUEST,t));return}y.send(n||null)})};var Fc=(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 c=l instanceof Error?l:this.reason;o.abort(c instanceof T?c:new ae(c instanceof Error?c.message:c))}},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:d}=o;return d.unsubscribe=()=>u.asap(a),d}},cs=Fc;var Uc=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},qc=async function*(t,e){for await(let r of jc(t))yield*Uc(r,e)},jc=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()}},mo=(t,e,r,o)=>{let i=qc(t,e),n=0,s,a=d=>{s||(s=!0,o&&o(d))};return new ReadableStream({async pull(d){try{let{done:l,value:c}=await i.next();if(l){a(),d.close();return}let m=c.byteLength;if(r){let g=n+=m;r(g)}d.enqueue(new Uint8Array(c))}catch(l){throw a(l),l}},cancel(d){return a(d),i.return()}},{highWaterMark:2})};var us=64*1024,{isFunction:dr}=u,fs=(({fetch:t,Request:e,Response:r})=>({fetch:t,Request:e,Response:r}))(u.global),{ReadableStream:ds,TextEncoder:ps}=u.global,ms=(t,...e)=>{try{return!!t(...e)}catch{return!1}},Vc=t=>{let{fetch:e,Request:r,Response:o}=Object.assign({},fs,t),i=dr(e),n=dr(r),s=dr(o);if(!i)return!1;let a=i&&dr(ds),d=i&&(typeof ps=="function"?(f=>b=>f.encode(b))(new ps):async f=>new Uint8Array(await new r(f).arrayBuffer())),l=n&&a&&ms(()=>{let f=!1,b=new r(L.origin,{body:new ds,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!b}),c=s&&a&&ms(()=>u.isReadableStream(new o("").body)),m={stream:c&&(f=>f.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!m[f]&&(m[f]=(b,y)=>{let S=b&&b[f];if(S)return S.call(b);throw new T(`Response type '${f}' is not supported`,T.ERR_NOT_SUPPORT,y)})});let g=async f=>{if(f==null)return 0;if(u.isBlob(f))return f.size;if(u.isSpecCompliantForm(f))return(await new r(L.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(u.isArrayBufferView(f)||u.isArrayBuffer(f))return f.byteLength;if(u.isURLSearchParams(f)&&(f=f+""),u.isString(f))return(await d(f)).byteLength},w=async(f,b)=>{let y=u.toFiniteNumber(f.getContentLength());return y??g(b)};return async f=>{let{url:b,method:y,data:S,signal:P,cancelToken:A,timeout:R,onDownloadProgress:x,onUploadProgress:q,responseType:U,headers:le,withCredentials:me="same-origin",fetchOptions:Ae}=ur(f);U=U?(U+"").toLowerCase():"text";let Se=cs([P,A&&A.toAbortSignal()],R),ne=null,ce=Se&&Se.unsubscribe&&(()=>{Se.unsubscribe()}),Q;try{if(q&&l&&y!=="get"&&y!=="head"&&(Q=await w(le,S))!==0){let K=new r(b,{method:"POST",body:S,duplex:"half"}),N;if(u.isFormData(S)&&(N=K.headers.get("content-type"))&&le.setContentType(N),K.body){let[oe,be]=st(Q,_e(nt(q)));S=mo(K.body,us,oe,be)}}u.isString(me)||(me=me?"include":"omit");let G=n&&"credentials"in r.prototype,Ce={...Ae,signal:Se,method:y.toUpperCase(),headers:le.normalize().toJSON(),body:S,duplex:"half",credentials:G?me:void 0};ne=n&&new r(b,Ce);let _=await(n?e(ne,Ae):e(b,Ce)),C=c&&(U==="stream"||U==="response");if(c&&(x||C&&ce)){let K={};["status","statusText","headers"].forEach(Z=>{K[Z]=_[Z]});let N=u.toFiniteNumber(_.headers.get("content-length")),[oe,be]=x&&st(N,_e(nt(x),!0))||[];_=new o(mo(_.body,us,oe,()=>{be&&be(),ce&&ce()}),K)}U=U||"text";let z=await m[u.findKey(m,U)||"text"](_,f);return!C&&ce&&ce(),await new Promise((K,N)=>{we(K,N,{data:z,headers:V.from(_.headers),status:_.status,statusText:_.statusText,config:f,request:ne})})}catch(G){throw ce&&ce(),G&&G.name==="TypeError"&&/Load failed|fetch/i.test(G.message)?Object.assign(new T("Network Error",T.ERR_NETWORK,f,ne),{cause:G.cause||G}):T.from(G,G&&G.code,f,ne)}}},Bc=new Map,fo=t=>{let e=u.merge.call({skipUndefined:!0},fs,t?t.env:null),{fetch:r,Request:o,Response:i}=e,n=[o,i,r],s=n.length,a=s,d,l,c=Bc;for(;a--;)d=n[a],l=c.get(d),l===void 0&&c.set(d,l=a?new Map:Vc(e)),c=l;return l},wb=fo();var ho={http:is,xhr:ls,fetch:{get:fo}};u.forEach(ho,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var hs=t=>`- ${t}`,Wc=t=>u.isFunction(t)||t===null||t===!1,pr={getAdapter:(t,e)=>{t=u.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,!Wc(o)&&(i=ho[(a=String(o)).toLowerCase()],i===void 0))throw new T(`Unknown adapter '${a}'`);if(i&&(u.isFunction(i)||(i=i.get(e))))break;n[a||"#"+s]=i}if(!i){let s=Object.entries(n).map(([d,l])=>`adapter ${d} `+(l===!1?"is not supported by the environment":"is not available in the build")),a=r?s.length>1?`since :
|
|
9
|
-
`+s.map(
|
|
10
|
-
`):" "+
|
|
11
|
-
`+n):o.stack=n}catch{}}throw o}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=he(this.defaults,r);let{transitional:o,paramsSerializer:i,headers:n}=r;o!==void 0&&Dt.assertOptions(o,{silentJSONParsing:Te.transitional(Te.boolean),forcedJSONParsing:Te.transitional(Te.boolean),clarifyTimeoutError:Te.transitional(Te.boolean)},!1),i!=null&&(u.isFunction(i)?r.paramsSerializer={serialize:i}:Dt.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),Dt.assertOptions(r,{baseUrl:Te.spelling("baseURL"),withXsrfToken:Te.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let s=n&&u.merge(n.common,n[r.method]);n&&u.forEach(["delete","get","head","post","put","patch","common"],f=>{delete n[f]}),r.headers=V.concat(s,n);let a=[],d=!0;this.interceptors.request.forEach(function(b){typeof b.runWhen=="function"&&b.runWhen(r)===!1||(d=d&&b.synchronous,a.unshift(b.fulfilled,b.rejected))});let l=[];this.interceptors.response.forEach(function(b){l.push(b.fulfilled,b.rejected)});let c,m=0,g;if(!d){let f=[mr.bind(this),void 0];for(f.unshift(...a),f.push(...l),g=f.length,c=Promise.resolve(r);m<g;)c=c.then(f[m++],f[m++]);return c}g=a.length;let w=r;for(m=0;m<g;){let f=a[m++],b=a[m++];try{w=f(w)}catch(y){b.call(this,y);break}}try{c=mr.call(this,w)}catch(f){return Promise.reject(f)}for(m=0,g=l.length;m<g;)c=c.then(l[m++],l[m++]);return c}getUri(e){e=he(this.defaults,e);let r=qe(e.baseURL,e.url,e.allowAbsoluteUrls);return Ue(r,e.params,e.paramsSerializer)}};u.forEach(["delete","get","head","options"],function(e){lt.prototype[e]=function(r,o){return this.request(he(o||{},{method:e,url:r,data:(o||{}).data}))}});u.forEach(["post","put","patch"],function(e){function r(o){return function(n,s,a){return this.request(he(a||{},{method:e,headers:o?{"Content-Type":"multipart/form-data"}:{},url:n,data:s}))}}lt.prototype[e]=r(),lt.prototype[e+"Form"]=r(!0)});var Pt=lt;var bo=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 ae(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}}},bs=bo;function yo(t){return function(r){return t.apply(null,r)}}function wo(t){return u.isObject(t)&&t.isAxiosError===!0}var To={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(To).forEach(([t,e])=>{To[e]=t});var ys=To;function ws(t){let e=new Pt(t),r=Et(Pt.prototype.request,e);return u.extend(r,Pt.prototype,e,{allOwnKeys:!0}),u.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return ws(he(t,i))},r}var $=ws(ot);$.Axios=Pt;$.CanceledError=ae;$.CancelToken=bs;$.isCancel=xt;$.VERSION=je;$.toFormData=Re;$.AxiosError=T;$.Cancel=$.CanceledError;$.all=function(e){return Promise.all(e)};$.spread=yo;$.isAxiosError=wo;$.mergeConfig=he;$.AxiosHeaders=V;$.formToJSON=t=>ar(u.isHTMLForm(t)?new FormData(t):t);$.getAdapter=pr.getAdapter;$.HttpStatusCode=ys;$.default=$;var Ts=$;var{Axios:hy,AxiosError:gy,CanceledError:by,isCancel:yy,CancelToken:wy,VERSION:Ty,all:Ay,Cancel:Ey,isAxiosError:Ie,spread:_y,toFormData:Sy,AxiosHeaders:Cy,HttpStatusCode:vy,formToJSON:Ry,getAdapter:xy,mergeConfig:Iy}=Ts;import{makeApi as tu,makeEndpoint as ct}from"@zodios/core";import{z as j}from"zod";import{z as h}from"zod";var Gc=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()}),$c=h.object({id:h.string()}),As=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()}))}),Ao=h.object({measure:h.object({field:h.string(),aggregation:h.string()}),time_dimension:h.object({field:h.string()}),filters:h.array(As)}),Qc=h.object({datasource:$c,basic_specification:Ao,viz_state_specification:h.object({viz_state_string:h.string()}).optional(),is_running_total:h.boolean()}),Es=h.object({allowed_dimensions:h.array(h.string()),allowed_granularities:h.array(h.string()),offset_from_today:h.number()}),_s=h.object({filters:h.array(As),measurement_period:h.object({granularity:h.string(),range:h.string()}),comparison:h.object({comparison:h.string()})}),Ss=h.object({target:h.object({value:h.number()}).optional()}),hr=h.object({id:h.string(),specification:_s,definition_id:h.string(),is_default:h.boolean(),schema_version:h.string(),metric_version:h.coerce.number(),goals:Ss.optional(),is_followed:h.boolean(),datasource_luid:h.string()}),Cs=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()}),vs=h.object({settings:h.array(h.object({type:h.string(),disabled:h.boolean()}))}),Kc=h.object({comparisons:h.array(h.object({compare_config:h.object({comparison:h.string()}),index:h.coerce.number()}))}),Jc=h.array(h.object({basic_specification:Ao,viz_state_specification:h.object({viz_state_string:h.string()}).optional(),minimum_granularity:h.string()})),Eo=h.object({metadata:Gc,specification:Qc,extension_options:Es,metrics:h.array(hr),total_metrics:h.coerce.number(),representation_options:Cs,insights_options:vs,comparisons:Kc,datasource_goals:Jc}),Rs=h.object({id:h.string(),metric_id:h.string()}),Zc=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"]),Yc=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"]),Xc=h.enum(["OUTPUT_FORMAT_UNSPECIFIED","OUTPUT_FORMAT_HTML","OUTPUT_FORMAT_TEXT"]),gr=h.object({bundle_request:h.object({version:h.number(),options:h.object({output_format:Xc,time_zone:h.string(),language:Zc,locale:Yc}),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:Ao,is_running_total:h.boolean()}),metric_specification:_s,extension_options:Es,representation_options:Cs,insights_options:vs,goals:Ss.optional()})})})}),eu=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()})}))}),xs=h.object({bundle_response:h.object({result:h.object({insight_groups:h.array(eu),has_errors:h.boolean(),characterization:h.string()})})}),br=["ban","springboard","basic","detail"],Be=["DEFINITION_VIEW_BASIC","DEFINITION_VIEW_FULL","DEFINITION_VIEW_DEFAULT"];var ru=ct({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:j.optional(j.enum(Be)),description:`The range of metrics to return for a definition. The default is 'DEFINITION_VIEW_BASIC' if not specified.
|
|
4
|
+
`,process.stderr.write(t))},Ri=({requestId:t,toolName:e,args:r,username:o})=>({type:"tool",requestId:t,...o?{username:o}:{},tool:{name:e,...r!==void 0?{args:r}:{}}});function xe(t){return async(e,r,{logger:o,requestId:i}={logger:e.name})=>{if(_i?.log({message:r,level:t,logger:o}),!!Ue(t))return e.server.notification({method:"notifications/message",params:{level:t,logger:o,data:JSON.stringify({timestamp:new Date().toISOString(),currentLogLevel:_t,message:r},null,2)}},{relatedRequestId:i})}}import{appendFile as ul}from"node:fs/promises";import{existsSync as dl,mkdirSync as pl}from"fs";import{join as ml}from"path";function V(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)??"undefined"}catch{return`${t}`}}var rr=class{_logDirectory;_fileMutexes=new Map;constructor({logDirectory:e}){this._logDirectory=e,dl(this._logDirectory)||pl(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=ml(this._logDirectory,o),n=i,a=(this._fileMutexes.get(n)??Promise.resolve()).then(async()=>{try{await ul(i,JSON.stringify({timestamp:r,...e})+`
|
|
5
|
+
`)}catch(l){Fe(`Failed to write to log file ${i}: ${V(l)}`)}});this._fileMutexes.set(n,a),a.finally(()=>{this._fileMutexes.get(n)===a&&this._fileMutexes.delete(n)}),await a}};import{McpServer as ym}from"@modelcontextprotocol/sdk/server/mcp.js";import{SetLevelRequestSchema as bm}from"@modelcontextprotocol/sdk/types.js";var xi={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.13.1",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","axios-retry":"^4.5.0",cors:"^2.8.5",dotenv:"^16.5.0",express:"^5.1.0","fast-levenshtein":"^3.0.0",jose:"^6.0.12",ssrfcheck:"^1.2.0","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 ap}from"ts-results-es";import{z as In}from"zod";import{Err as Ii,Ok as hl}from"ts-results-es";var Pi=t=>{let e=ki(t);if(e.isErr())return t;let r=e.value;return Ue("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},Di=t=>{let e=ki(t);if(e.isErr())return t;let r=e.value;return Ue("debug")?r.data?.credentials&&(r.data.credentials="<redacted>"):(delete r.data,delete r.headers),r};function ki(t){try{return hl(structuredClone(t))}catch(e){if(e instanceof Error)return Ii(e);let r=V(e);return Fe(`Could not clone object, notification may not be sanitized! Error: ${r}`),Ii(new Error(r))}}function or(t){return{method:t.method??"UNKNOWN METHOD",url:t.url??"UNKNOWN URL",headers:t.headers,data:t.data,params:t.params}}function ir(t){return{url:t.config.url??"UNKNOWN URL",status:t.status,headers:t.headers,data:t.data}}import{Zodios as Ni}from"@zodios/core";import{randomUUID as gl}from"node:crypto";import{SignJWT as yl}from"jose";async function Li({username:t,connectedApp:e,scopes:r,additionalPayload:o}){let i={alg:"HS256",typ:"JWT",kid:e.secretId},n={jti:gl(),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 yl(n).setProtectedHeader(i).sign(new TextEncoder().encode(e.secretValue))}import{makeApi as bl,makeEndpoint as Oi}from"@zodios/core";import{z as Te}from"zod";import{z as qe}from"zod";var Mi=qe.object({credentials:qe.object({site:qe.object({id:qe.string()}),user:qe.object({id:qe.string()}),token:qe.string()})});var Tl=Te.object({credentials:Te.object({site:Te.object({contentUrl:Te.string()})}).and(Te.object({personalAccessTokenName:Te.string(),personalAccessTokenSecret:Te.string()}).or(Te.object({jwt:Te.string()})))}),wl=Oi({method:"post",path:"/auth/signin",alias:"signIn",description:"Signs in with Tableau credentials.",response:Mi,parameters:[{name:"credentials",type:"Body",schema:Tl}]}),Al=Oi({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:Te.void()}),Sl=bl([wl,Al]),io=[...Sl];var Ee=class{_apiClient;constructor(e){this._apiClient=e}get interceptors(){return this._apiClient.axios.interceptors}};var H=class extends Ee{_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 sr=class extends Ee{constructor(e){super(new Ni(e,io))}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 Li({username:e.username,connectedApp:{clientId:e.clientId,secretId:e.secretId,secretValue:e.secretValue},scopes:e.scopes,additionalPayload:e.additionalPayload})}}})()}})).credentials},nr=class extends H{constructor(e,r){super(new Ni(e,io),r)}signOut=async()=>{await this._apiClient.signOut(void 0,{...this.authHeader})}};import{Zodios as Il}from"@zodios/core";import{makeApi as vl,makeEndpoint as Cl}from"@zodios/core";import{z as tt}from"zod";import{z as k}from"zod";var El=k.enum(["hitsTotal","hitsSmallSpanTotal","hitsMediumSpanTotal","hitsLargeSpanTotal","downstreamWorkbookCount"]),Ui=k.array(k.object({method:El,sortDirection:k.enum(["asc","desc"]).default("asc").optional()})).nonempty(),Fi=k.enum(["lens","datasource","virtualconnection","collection","project","flow","datarole","table","database","view","workbook"]),qi=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()]),so=k.object({contentTypes:k.array(Fi).nonempty(),ownerIds:k.array(k.number().int()).nonempty(),modifiedTime:qi}).partial(),ji=k.union([so.extend({contentTypes:k.array(Fi).nonempty()}).strict(),so.extend({ownerIds:k.array(k.number().int()).nonempty()}).strict(),so.extend({modifiedTime:qi}).strict()]),_l=k.object({uri:k.string(),content:k.record(k.string(),k.unknown())}),Vi=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(_l)}).partial();var Rl=Cl({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:tt.string().optional()},{name:"page",type:"Query",schema:tt.number().int().optional()},{name:"limit",type:"Query",schema:tt.number().int().optional()},{name:"order_by",type:"Query",schema:tt.string().optional()},{name:"filter",type:"Query",schema:tt.string().optional()}],response:tt.object({hits:Vi})}),xl=vl([Rl]),Bi=[...xl];var vt=class extends H{constructor(e,r){super(new Il(e,Bi),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 Ml}from"@zodios/core";import{makeApi as Pl,makeEndpoint as Wi}from"@zodios/core";import{z as Ve}from"zod";import{z as lr}from"zod";import{z as no}from"zod";var ar=no.object({name:no.string(),id:no.string()});var ao=lr.object({id:lr.string(),name:lr.string(),description:lr.string().optional(),project:ar});import{z as je}from"zod";var rt=je.object({pageNumber:je.coerce.number(),pageSize:je.coerce.number(),totalAvailable:je.coerce.number()}),fh=je.object({next_page_token:je.string().optional(),total_available:je.coerce.number().optional()});import{z as zi}from"zod";var ot=[{name:"pageSize",type:"Query",schema:zi.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:zi.number().optional(),description:"The offset for paging. The default is 1."}];var Dl=Wi({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:[...ot,{name:"siteId",type:"Path",schema:Ve.string()},{name:"filter",type:"Query",schema:Ve.string().optional(),description:"Filter string in the format field:operator:value (e.g., name:eq:Project Views)"}],response:Ve.object({pagination:rt,datasources:Ve.object({datasource:Ve.optional(Ve.array(ao))})})}),kl=Wi({method:"get",path:"/sites/:siteId/datasources/:datasourceId",alias:"queryDatasource",description:"Returns information about the specified data source.",response:Ve.object({datasource:ao})}),Ll=Pl([Dl,kl]),Hi=[...Ll];var Ct=class extends H{constructor(e,r){super(new Ml(e,Hi),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 jl}from"@zodios/core";import{makeApi as Ol,makeEndpoint as Nl}from"@zodios/core";import{z as L}from"zod";var Ul=L.object({data:L.object({publishedDatasources:L.array(L.object({name:L.string().nullable(),description:L.string().nullable(),owner:L.object({name:L.string().nullable()}),fields:L.array(L.object({name:L.string(),isHidden:L.boolean().nullable(),description:L.string().nullable(),descriptionInherited:L.array(L.object({attribute:L.string(),value:L.string().nullable()}).nullable()).nullable(),fullyQualifiedName:L.string(),__typename:L.string(),dataCategory:L.string().nullish(),role:L.string().nullish(),dataType:L.string().nullish(),defaultFormat:L.string().nullish(),semanticRole:L.string().nullish(),aggregation:L.string().nullish(),aggregationParam:L.string().nullish(),formula:L.string().nullish(),isAutoGenerated:L.boolean().nullish(),hasUserReference:L.boolean().nullish(),binSize:L.number().nullish(),hasOther:L.boolean().nullish(),delimiter:L.string().nullish(),combinationType:L.string().nullish()}))}))})}),Fl=Nl({method:"post",path:"/graphql",alias:"graphql",response:Ul,parameters:[{name:"query",type:"Body",schema:L.object({query:L.string()})}]}),ql=Ol([Fl]),$i=[...ql];var Rt=class extends H{constructor(e,r){super(new jl(e,$i),r)}graphql=async e=>await this._apiClient.graphql({query:e},{...this.authHeader})};import{Zodios as $u}from"@zodios/core";import{Err as Xs,Ok as Gu}from"ts-results-es";function xt(t,e){return function(){return t.apply(e,arguments)}}var{toString:Vl}=Object.prototype,{getPrototypeOf:co}=Object,{iterator:ur,toStringTag:Qi}=Symbol,dr=(t=>e=>{let r=Vl.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),he=t=>(t=t.toLowerCase(),e=>dr(e)===t),pr=t=>e=>typeof e===t,{isArray:st}=Array,it=pr("undefined");function It(t){return t!==null&&!it(t)&&t.constructor!==null&&!it(t.constructor)&&ie(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var Ki=he("ArrayBuffer");function Bl(t){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&Ki(t.buffer),e}var zl=pr("string"),ie=pr("function"),Ji=pr("number"),Pt=t=>t!==null&&typeof t=="object",Wl=t=>t===!0||t===!1,cr=t=>{if(dr(t)!=="object")return!1;let e=co(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Qi in t)&&!(ur in t)},Hl=t=>{if(!Pt(t)||It(t))return!1;try{return Object.keys(t).length===0&&Object.getPrototypeOf(t)===Object.prototype}catch{return!1}},$l=he("Date"),Gl=he("File"),Ql=he("Blob"),Kl=he("FileList"),Jl=t=>Pt(t)&&ie(t.pipe),Yl=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||ie(t.append)&&((e=dr(t))==="formdata"||e==="object"&&ie(t.toString)&&t.toString()==="[object FormData]"))},Zl=he("URLSearchParams"),[Xl,ec,tc,rc]=["ReadableStream","Request","Response","Headers"].map(he),oc=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Dt(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t>"u")return;let o,i;if(typeof t!="object"&&(t=[t]),st(t))for(o=0,i=t.length;o<i;o++)e.call(null,t[o],o,t);else{if(It(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 Yi(t,e){if(It(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 Be=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Zi=t=>!it(t)&&t!==Be;function lo(){let{caseless:t,skipUndefined:e}=Zi(this)&&this||{},r={},o=(i,n)=>{let s=t&&Yi(r,n)||n;cr(r[s])&&cr(i)?r[s]=lo(r[s],i):cr(i)?r[s]=lo({},i):st(i)?r[s]=i.slice():(!e||!it(i))&&(r[s]=i)};for(let i=0,n=arguments.length;i<n;i++)arguments[i]&&Dt(arguments[i],o);return r}var ic=(t,e,r,{allOwnKeys:o}={})=>(Dt(e,(i,n)=>{r&&ie(i)?t[n]=xt(i,r):t[n]=i},{allOwnKeys:o}),t),sc=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),nc=(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)},ac=(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&&co(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},lc=(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},cc=t=>{if(!t)return null;if(st(t))return t;let e=t.length;if(!Ji(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},uc=(t=>e=>t&&e instanceof t)(typeof Uint8Array<"u"&&co(Uint8Array)),dc=(t,e)=>{let o=(t&&t[ur]).call(t),i;for(;(i=o.next())&&!i.done;){let n=i.value;e.call(t,n[0],n[1])}},pc=(t,e)=>{let r,o=[];for(;(r=t.exec(e))!==null;)o.push(r);return o},mc=he("HTMLFormElement"),fc=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,o,i){return o.toUpperCase()+i}),Gi=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),hc=he("RegExp"),Xi=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),o={};Dt(r,(i,n)=>{let s;(s=e(i,n,t))!==!1&&(o[n]=s||i)}),Object.defineProperties(t,o)},gc=t=>{Xi(t,(e,r)=>{if(ie(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let o=t[r];if(ie(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+"'")})}})},yc=(t,e)=>{let r={},o=i=>{i.forEach(n=>{r[n]=!0})};return st(t)?o(t):o(String(t).split(e)),r},bc=()=>{},Tc=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function wc(t){return!!(t&&ie(t.append)&&t[Qi]==="FormData"&&t[ur])}var Ac=t=>{let e=new Array(10),r=(o,i)=>{if(Pt(o)){if(e.indexOf(o)>=0)return;if(It(o))return o;if(!("toJSON"in o)){e[i]=o;let n=st(o)?[]:{};return Dt(o,(s,a)=>{let l=r(s,i+1);!it(l)&&(n[a]=l)}),e[i]=void 0,n}}return o};return r(t,0)},Sc=he("AsyncFunction"),Ec=t=>t&&(Pt(t)||ie(t))&&ie(t.then)&&ie(t.catch),es=((t,e)=>t?setImmediate:e?((r,o)=>(Be.addEventListener("message",({source:i,data:n})=>{i===Be&&n===r&&o.length&&o.shift()()},!1),i=>{o.push(i),Be.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",ie(Be.postMessage)),_c=typeof queueMicrotask<"u"?queueMicrotask.bind(Be):typeof process<"u"&&process.nextTick||es,vc=t=>t!=null&&ie(t[ur]),d={isArray:st,isArrayBuffer:Ki,isBuffer:It,isFormData:Yl,isArrayBufferView:Bl,isString:zl,isNumber:Ji,isBoolean:Wl,isObject:Pt,isPlainObject:cr,isEmptyObject:Hl,isReadableStream:Xl,isRequest:ec,isResponse:tc,isHeaders:rc,isUndefined:it,isDate:$l,isFile:Gl,isBlob:Ql,isRegExp:hc,isFunction:ie,isStream:Jl,isURLSearchParams:Zl,isTypedArray:uc,isFileList:Kl,forEach:Dt,merge:lo,extend:ic,trim:oc,stripBOM:sc,inherits:nc,toFlatObject:ac,kindOf:dr,kindOfTest:he,endsWith:lc,toArray:cc,forEachEntry:dc,matchAll:pc,isHTMLForm:mc,hasOwnProperty:Gi,hasOwnProp:Gi,reduceDescriptors:Xi,freezeMethods:gc,toObjectSet:yc,toCamelCase:fc,noop:bc,toFiniteNumber:Tc,findKey:Yi,global:Be,isContextDefined:Zi,isSpecCompliantForm:wc,toJSONObject:Ac,isAsyncFn:Sc,isThenable:Ec,setImmediate:es,asap:_c,isIterable:vc};function nt(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(nt,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 ts=nt.prototype,rs={};["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=>{rs[t]={value:t}});Object.defineProperties(nt,rs);Object.defineProperty(ts,"isAxiosError",{value:!0});nt.from=(t,e,r,o,i,n)=>{let s=Object.create(ts);d.toFlatObject(t,s,function(u){return u!==Error.prototype},c=>c!=="isAxiosError");let a=t&&t.message?t.message:"Error",l=e==null&&t?t.code:e;return nt.call(s,a,l,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 w=nt;import Cc from"form-data";var mr=Cc;function uo(t){return d.isPlainObject(t)||d.isArray(t)}function is(t){return d.endsWith(t,"[]")?t.slice(0,-2):t}function os(t,e,r){return t?t.concat(e).map(function(i,n){return i=is(i),!r&&n?"["+i+"]":i}).join(r?".":""):e}function Rc(t){return d.isArray(t)&&!t.some(uo)}var xc=d.toFlatObject(d,{},null,function(e){return/^is[A-Z]/.test(e)});function Ic(t,e,r){if(!d.isObject(t))throw new TypeError("target must be an object");e=e||new(mr||FormData),r=d.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,T){return!d.isUndefined(T[y])});let o=r.metaTokens,i=r.visitor||u,n=r.dots,s=r.indexes,l=(r.Blob||typeof Blob<"u"&&Blob)&&d.isSpecCompliantForm(e);if(!d.isFunction(i))throw new TypeError("visitor must be a function");function c(m){if(m===null)return"";if(d.isDate(m))return m.toISOString();if(d.isBoolean(m))return m.toString();if(!l&&d.isBlob(m))throw new w("Blob is not supported. Use a Buffer instead.");return d.isArrayBuffer(m)||d.isTypedArray(m)?l&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function u(m,y,T){let v=m;if(m&&!T&&typeof m=="object"){if(d.endsWith(y,"{}"))y=o?y:y.slice(0,-2),m=JSON.stringify(m);else if(d.isArray(m)&&Rc(m)||(d.isFileList(m)||d.endsWith(y,"[]"))&&(v=d.toArray(m)))return y=is(y),v.forEach(function(S,C){!(d.isUndefined(S)||S===null)&&e.append(s===!0?os([y],C,n):s===null?y:y+"[]",c(S))}),!1}return uo(m)?!0:(e.append(os(T,y,n),c(m)),!1)}let p=[],g=Object.assign(xc,{defaultVisitor:u,convertValue:c,isVisitable:uo});function b(m,y){if(!d.isUndefined(m)){if(p.indexOf(m)!==-1)throw Error("Circular reference detected in "+y.join("."));p.push(m),d.forEach(m,function(v,P){(!(d.isUndefined(v)||v===null)&&i.call(e,v,d.isString(P)?P.trim():P,y,g))===!0&&b(v,y?y.concat(P):[P])}),p.pop()}}if(!d.isObject(t))throw new TypeError("data must be an object");return b(t),e}var Ie=Ic;function ss(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(o){return e[o]})}function ns(t,e){this._pairs=[],t&&Ie(t,this,e)}var as=ns.prototype;as.append=function(e,r){this._pairs.push([e,r])};as.toString=function(e){let r=e?function(o){return e.call(this,o,ss)}:ss;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};var ls=ns;function Pc(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function ze(t,e,r){if(!e)return t;let o=r&&r.encode||Pc;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 ls(e,r).toString(o),n){let s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+n}return t}var po=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)})}},mo=po;var at={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};import kc from"crypto";import Dc from"url";var cs=Dc.URLSearchParams;var fo="abcdefghijklmnopqrstuvwxyz",us="0123456789",ds={DIGIT:us,ALPHA:fo,ALPHA_DIGIT:fo+fo.toUpperCase()+us},Lc=(t=16,e=ds.ALPHA_DIGIT)=>{let r="",{length:o}=e,i=new Uint32Array(t);kc.randomFillSync(i);for(let n=0;n<t;n++)r+=e[i[n]%o];return r},ps={isNode:!0,classes:{URLSearchParams:cs,FormData:mr,Blob:typeof Blob<"u"&&Blob||null},ALPHABET:ds,generateString:Lc,protocols:["http","https","file","data"]};var yo={};Ja(yo,{hasBrowserEnv:()=>go,hasStandardBrowserEnv:()=>Mc,hasStandardBrowserWebWorkerEnv:()=>Oc,navigator:()=>ho,origin:()=>Nc});var go=typeof window<"u"&&typeof document<"u",ho=typeof navigator=="object"&&navigator||void 0,Mc=go&&(!ho||["ReactNative","NativeScript","NS"].indexOf(ho.product)<0),Oc=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Nc=go&&window.location.href||"http://localhost";var O={...yo,...ps};function bo(t,e){return Ie(t,new O.classes.URLSearchParams,{visitor:function(r,o,i,n){return O.isNode&&d.isBuffer(r)?(this.append(o,r.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)},...e})}function Uc(t){return d.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Fc(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 qc(t){function e(r,o,i,n){let s=r[n++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),l=n>=r.length;return s=!s&&d.isArray(i)?i.length:s,l?(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]=Fc(i[s])),!a)}if(d.isFormData(t)&&d.isFunction(t.entries)){let r={};return d.forEachEntry(t,(o,i)=>{e(Uc(o),i,r,0)}),r}return null}var fr=qc;function jc(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 To={transitional:at,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(fr(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 bo(e,this.formSerializer).toString();if((a=d.isFileList(e))||o.indexOf("multipart/form-data")>-1){let l=this.env&&this.env.FormData;return Ie(a?{"files[]":e}:e,l&&new l,this.formSerializer)}}return n||i?(r.setContentType("application/json",!1),jc(e)):e}],transformResponse:[function(e){let r=this.transitional||To.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"?w.from(a,w.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:O.classes.FormData,Blob:O.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=>{To.headers[t]={}});var lt=To;var Vc=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"]),ms=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]&&Vc[r])&&(r==="set-cookie"?e[r]?e[r].push(o):e[r]=[o]:e[r]=e[r]?e[r]+", "+o:o)}),e};var fs=Symbol("internals");function kt(t){return t&&String(t).trim().toLowerCase()}function hr(t){return t===!1||t==null?t:d.isArray(t)?t.map(hr):String(t)}function Bc(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 zc=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function wo(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 Wc(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,o)=>r.toUpperCase()+o)}function Hc(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 ct=class{constructor(e){e&&this.set(e)}set(e,r,o){let i=this;function n(a,l,c){let u=kt(l);if(!u)throw new Error("header name must be a non-empty string");let p=d.findKey(i,u);(!p||i[p]===void 0||c===!0||c===void 0&&i[p]!==!1)&&(i[p||l]=hr(a))}let s=(a,l)=>d.forEach(a,(c,u)=>n(c,u,l));if(d.isPlainObject(e)||e instanceof this.constructor)s(e,r);else if(d.isString(e)&&(e=e.trim())&&!zc(e))s(ms(e),r);else if(d.isObject(e)&&d.isIterable(e)){let a={},l,c;for(let u of e){if(!d.isArray(u))throw TypeError("Object iterator must return a key-value pair");a[c=u[0]]=(l=a[c])?d.isArray(l)?[...l,u[1]]:[l,u[1]]:u[1]}s(a,r)}else e!=null&&n(r,e,o);return this}get(e,r){if(e=kt(e),e){let o=d.findKey(this,e);if(o){let i=this[o];if(!r)return i;if(r===!0)return Bc(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=kt(e),e){let o=d.findKey(this,e);return!!(o&&this[o]!==void 0&&(!r||wo(this,this[o],o,r)))}return!1}delete(e,r){let o=this,i=!1;function n(s){if(s=kt(s),s){let a=d.findKey(o,s);a&&(!r||wo(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||wo(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]=hr(i),delete r[n];return}let a=e?Wc(n):String(n).trim();a!==n&&delete r[n],r[a]=hr(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[fs]=this[fs]={accessors:{}}).accessors,i=this.prototype;function n(s){let a=kt(s);o[a]||(Hc(i,s),o[a]=!0)}return d.isArray(e)?e.forEach(n):n(e),this}};ct.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);d.reduceDescriptors(ct.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(o){this[r]=o}}});d.freezeMethods(ct);var B=ct;function Lt(t,e){let r=this||lt,o=e||r,i=B.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 Mt(t){return!!(t&&t.__CANCEL__)}function hs(t,e,r){w.call(this,t??"canceled",w.ERR_CANCELED,e,r),this.name="CanceledError"}d.inherits(hs,w,{__CANCEL__:!0});var ae=hs;function we(t,e,r){let o=r.config.validateStatus;!r.status||!o||o(r.status)?t(r):e(new w("Request failed with status code "+r.status,[w.ERR_BAD_REQUEST,w.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function Ao(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function So(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function We(t,e,r){let o=!Ao(e);return t&&(o||r==!1)?So(t,e):e}import su from"proxy-from-env";import nu from"http";import au from"https";import lu from"util";import cu from"follow-redirects";import Pe from"zlib";var He="1.12.1";function Ot(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}var $c=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Eo(t,e,r){let o=r&&r.Blob||O.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=$c.exec(t);if(!n)throw new w("Invalid URL",w.ERR_INVALID_URL);let s=n[1],a=n[2],l=n[3],c=Buffer.from(decodeURIComponent(l),a?"base64":"utf8");if(e){if(!o)throw new w("Blob is not supported",w.ERR_NOT_SUPPORT);return new o([c],{type:s})}return c}throw new w("Unsupported protocol "+i,w.ERR_NOT_SUPPORT)}import pt from"stream";import Gc from"stream";var _o=Symbol("internals"),vo=class extends Gc.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[_o]={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[_o];return r.onReadCallback&&r.onReadCallback(),super._read(e)}_transform(e,r,o){let i=this[_o],n=i.maxRate,s=this.readableHighWaterMark,a=i.timeWindow,l=1e3/a,c=n/l,u=i.minChunkSize!==!1?Math.max(i.minChunkSize,c*.01):0,p=(b,m)=>{let y=Buffer.byteLength(b);i.bytesSeen+=y,i.bytes+=y,i.isCaptured&&this.emit("progress",i.bytesSeen),this.push(b)?process.nextTick(m):i.onReadCallback=()=>{i.onReadCallback=null,process.nextTick(m)}},g=(b,m)=>{let y=Buffer.byteLength(b),T=null,v=s,P,S=0;if(n){let C=Date.now();(!i.ts||(S=C-i.ts)>=a)&&(i.ts=C,P=c-i.bytes,i.bytes=P<0?-P:0,S=0),P=c-i.bytes}if(n){if(P<=0)return setTimeout(()=>{m(null,b)},a-S);P<v&&(v=P)}v&&y>v&&y-v>u&&(T=b.subarray(v),b=b.subarray(0,v)),p(b,T?()=>{process.nextTick(m,null,T)}:m)};g(e,function b(m,y){if(m)return o(m);y?g(y,b):o(null)})}},Co=vo;import{EventEmitter as uu}from"events";import Kc from"util";import{Readable as Jc}from"stream";var{asyncIterator:gs}=Symbol,Qc=async function*(t){t.stream?yield*t.stream():t.arrayBuffer?yield await t.arrayBuffer():t[gs]?yield*t[gs]():yield t},gr=Qc;var Yc=O.ALPHABET.ALPHA_DIGIT+"-_",Nt=typeof TextEncoder=="function"?new TextEncoder:new Kc.TextEncoder,$e=`\r
|
|
8
|
+
`,Zc=Nt.encode($e),Xc=2,Ro=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)}"`:""}${$e}`;i?r=Nt.encode(String(r).replace(/\r?\n|\r\n?/g,$e)):n+=`Content-Type: ${r.type||"application/octet-stream"}${$e}`,this.headers=Nt.encode(n+$e),this.contentLength=i?r.byteLength:r.size,this.size=this.headers.byteLength+this.contentLength+Xc,this.name=e,this.value=r}async*encode(){yield this.headers;let{value:e}=this;d.isTypedArray(e)?yield e:yield*gr(e),yield Zc}static escapeName(e){return String(e).replace(/[\r\n"]/g,r=>({"\r":"%0D","\n":"%0A",'"':"%22"})[r])}},eu=(t,e,r)=>{let{tag:o="form-data-boundary",size:i=25,boundary:n=o+"-"+O.generateString(i,Yc)}=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=Nt.encode("--"+n+$e),a=Nt.encode("--"+n+"--"+$e),l=a.byteLength,c=Array.from(t.entries()).map(([p,g])=>{let b=new Ro(p,g);return l+=b.size,b});l+=s.byteLength*c.length,l=d.toFiniteNumber(l);let u={"Content-Type":`multipart/form-data; boundary=${n}`};return Number.isFinite(l)&&(u["Content-Length"]=l),e&&e(u),Jc.from(async function*(){for(let p of c)yield s,yield*p.encode();yield a}())},ys=eu;import tu from"stream";var xo=class extends tu.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)}},bs=xo;var ru=(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,Ts=ru;function ou(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(l){let c=Date.now(),u=o[n];s||(s=c),r[i]=l,o[i]=c;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),c-s<e)return;let b=u&&c-u;return b?Math.round(g*1e3/b):void 0}}var ws=ou;function iu(t,e){let r=0,o=1e3/e,i,n,s=(c,u=Date.now())=>{r=u,i=null,n&&(clearTimeout(n),n=null),t(...c)};return[(...c)=>{let u=Date.now(),p=u-r;p>=o?s(c,u):(i=c,n||(n=setTimeout(()=>{n=null,s(i)},o-p)))},()=>i&&s(i)]}var As=iu;var _e=(t,e,r=3)=>{let o=0,i=ws(50,250);return As(n=>{let s=n.loaded,a=n.lengthComputable?n.total:void 0,l=s-o,c=i(l),u=s<=a;o=s;let p={loaded:s,total:a,progress:a?s/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&u?(a-s)/c:void 0,event:n,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(p)},r)},ut=(t,e)=>{let r=t!=null;return[o=>e[0]({lengthComputable:r,total:t,loaded:o}),e[1]]},dt=t=>(...e)=>d.asap(()=>t(...e));function Io(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),m=o.charCodeAt(g+2);(b>=48&&b<=57||b>=65&&b<=70||b>=97&&b<=102)&&(m>=48&&m<=57||m>=65&&m<=70||m>=97&&m<=102)&&(n-=2,g+=2)}let a=0,l=s-1,c=g=>g>=2&&o.charCodeAt(g-2)===37&&o.charCodeAt(g-1)===51&&(o.charCodeAt(g)===68||o.charCodeAt(g)===100);l>=0&&(o.charCodeAt(l)===61?(a++,l--):c(l)&&(a++,l-=3)),a===1&&l>=0&&(o.charCodeAt(l)===61||c(l))&&a++;let p=Math.floor(n/4)*3-(a||0);return p>0?p:0}return Buffer.byteLength(o,"utf8")}var Ss={flush:Pe.constants.Z_SYNC_FLUSH,finishFlush:Pe.constants.Z_SYNC_FLUSH},du={flush:Pe.constants.BROTLI_OPERATION_FLUSH,finishFlush:Pe.constants.BROTLI_OPERATION_FLUSH},Es=d.isFunction(Pe.createBrotliDecompress),{http:pu,https:mu}=cu,fu=/https:?/,_s=O.protocols.map(t=>t+":"),vs=(t,[e,r])=>(t.on("end",r).on("error",r),e);function hu(t,e){t.beforeRedirects.proxy&&t.beforeRedirects.proxy(t),t.beforeRedirects.config&&t.beforeRedirects.config(t,e)}function Rs(t,e,r){let o=e;if(!o&&o!==!1){let i=su.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){Rs(n,e,n.href)}}var gu=typeof process<"u"&&d.kindOf(process)==="process",yu=t=>new Promise((e,r)=>{let o,i,n=(l,c)=>{i||(i=!0,o&&o(l,c))},s=l=>{n(l),e(l)},a=l=>{n(l,!0),r(l)};t(s,a,l=>o=l).catch(a)}),bu=({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)}},Cs=(t,e)=>bu(d.isObject(t)?t:{address:t,family:e}),xs=gu&&function(e){return yu(async function(o,i,n){let{data:s,lookup:a,family:l}=e,{responseType:c,responseEncoding:u}=e,p=e.method.toUpperCase(),g,b=!1,m;if(a){let _=Ts(a,E=>d.isArray(E)?E:[E]);a=(E,W,K)=>{_(E,W,(j,re,me)=>{if(j)return K(j);let Z=d.isArray(re)?re.map(oe=>Cs(oe)):[Cs(re,me)];W.all?K(j,Z):K(j,Z[0].address,Z[0].family)})}}let y=new uu,T=()=>{e.cancelToken&&e.cancelToken.unsubscribe(v),e.signal&&e.signal.removeEventListener("abort",v),y.removeAllListeners()};n((_,E)=>{g=!0,E&&(b=!0,T())});function v(_){y.emit("abort",!_||_.type?new ae(null,e,m):_)}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 P=We(e.baseURL,e.url,e.allowAbsoluteUrls),S=new URL(P,O.hasBrowserEnv?O.origin:void 0),C=S.protocol||_s[0];if(C==="data:"){if(e.maxContentLength>-1){let E=String(e.url||P||"");if(Io(E)>e.maxContentLength)return i(new w("maxContentLength size of "+e.maxContentLength+" exceeded",w.ERR_BAD_RESPONSE,e))}let _;if(p!=="GET")return we(o,i,{status:405,statusText:"method not allowed",headers:{},config:e});try{_=Eo(e.url,c==="blob",{Blob:e.env&&e.env.Blob})}catch(E){throw w.from(E,w.ERR_BAD_REQUEST,e)}return c==="text"?(_=_.toString(u),(!u||u==="utf8")&&(_=d.stripBOM(_))):c==="stream"&&(_=pt.Readable.from(_)),we(o,i,{data:_,status:200,statusText:"OK",headers:new B,config:e})}if(_s.indexOf(C)===-1)return i(new w("Unsupported protocol "+C,w.ERR_BAD_REQUEST,e));let x=B.from(e.headers).normalize();x.set("User-Agent","axios/"+He,!1);let{onUploadProgress:q,onDownloadProgress:F}=e,te=e.maxRate,pe,Se;if(d.isSpecCompliantForm(s)){let _=x.getContentType(/boundary=([-_\w\d]{10,70})/i);s=ys(s,E=>{x.set(E)},{tag:`axios-${He}-boundary`,boundary:_&&_[1]||void 0})}else if(d.isFormData(s)&&d.isFunction(s.getHeaders)){if(x.set(s.getHeaders()),!x.hasContentLength())try{let _=await lu.promisify(s.getLength).call(s);Number.isFinite(_)&&_>=0&&x.setContentLength(_)}catch{}}else if(d.isBlob(s)||d.isFile(s))s.size&&x.setContentType(s.type||"application/octet-stream"),x.setContentLength(s.size||0),s=pt.Readable.from(gr(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 w("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",w.ERR_BAD_REQUEST,e));if(x.setContentLength(s.length,!1),e.maxBodyLength>-1&&s.length>e.maxBodyLength)return i(new w("Request body larger than maxBodyLength limit",w.ERR_BAD_REQUEST,e))}let ve=d.toFiniteNumber(x.getContentLength());d.isArray(te)?(pe=te[0],Se=te[1]):pe=Se=te,s&&(q||pe)&&(d.isStream(s)||(s=pt.Readable.from(s,{objectMode:!1})),s=pt.pipeline([s,new Co({maxRate:d.toFiniteNumber(pe)})],d.noop),q&&s.on("progress",vs(s,ut(ve,_e(dt(q),!1,3)))));let ne;if(e.auth){let _=e.auth.username||"",E=e.auth.password||"";ne=_+":"+E}if(!ne&&S.username){let _=S.username,E=S.password;ne=_+":"+E}ne&&x.delete("authorization");let le;try{le=ze(S.pathname+S.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(_){let E=new Error(_.message);return E.config=e,E.url=e.url,E.exists=!0,i(E)}x.set("Accept-Encoding","gzip, compress, deflate"+(Es?", br":""),!1);let G={path:le,method:p,headers:x.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:ne,protocol:C,family:l,beforeRedirect:hu,beforeRedirects:{}};!d.isUndefined(a)&&(G.lookup=a),e.socketPath?G.socketPath=e.socketPath:(G.hostname=S.hostname.startsWith("[")?S.hostname.slice(1,-1):S.hostname,G.port=S.port,Rs(G,e.proxy,C+"//"+S.hostname+(S.port?":"+S.port:"")+G.path));let J,Ce=fu.test(G.protocol);if(G.agent=Ce?e.httpsAgent:e.httpAgent,e.transport?J=e.transport:e.maxRedirects===0?J=Ce?au:nu:(e.maxRedirects&&(G.maxRedirects=e.maxRedirects),e.beforeRedirect&&(G.beforeRedirects.config=e.beforeRedirect),J=Ce?mu:pu),e.maxBodyLength>-1?G.maxBodyLength=e.maxBodyLength:G.maxBodyLength=1/0,e.insecureHTTPParser&&(G.insecureHTTPParser=e.insecureHTTPParser),m=J.request(G,function(E){if(m.destroyed)return;let W=[E],K=+E.headers["content-length"];if(F||Se){let oe=new Co({maxRate:d.toFiniteNumber(Se)});F&&oe.on("progress",vs(oe,ut(K,_e(dt(F),!0,3)))),W.push(oe)}let j=E,re=E.req||m;if(e.decompress!==!1&&E.headers["content-encoding"])switch((p==="HEAD"||E.statusCode===204)&&delete E.headers["content-encoding"],(E.headers["content-encoding"]||"").toLowerCase()){case"gzip":case"x-gzip":case"compress":case"x-compress":W.push(Pe.createUnzip(Ss)),delete E.headers["content-encoding"];break;case"deflate":W.push(new bs),W.push(Pe.createUnzip(Ss)),delete E.headers["content-encoding"];break;case"br":Es&&(W.push(Pe.createBrotliDecompress(du)),delete E.headers["content-encoding"])}j=W.length>1?pt.pipeline(W,d.noop):W[0];let me=pt.finished(j,()=>{me(),T()}),Z={status:E.statusCode,statusText:E.statusMessage,headers:new B(E.headers),config:e,request:re};if(c==="stream")Z.data=j,we(o,i,Z);else{let oe=[],tr=0;j.on("data",function(Q){oe.push(Q),tr+=Q.length,e.maxContentLength>-1&&tr>e.maxContentLength&&(b=!0,j.destroy(),i(new w("maxContentLength size of "+e.maxContentLength+" exceeded",w.ERR_BAD_RESPONSE,e,re)))}),j.on("aborted",function(){if(b)return;let Q=new w("stream has been aborted",w.ERR_BAD_RESPONSE,e,re);j.destroy(Q),i(Q)}),j.on("error",function(Q){m.destroyed||i(w.from(Q,null,e,re))}),j.on("end",function(){try{let Q=oe.length===1?oe[0]:Buffer.concat(oe);c!=="arraybuffer"&&(Q=Q.toString(u),(!u||u==="utf8")&&(Q=d.stripBOM(Q))),Z.data=Q}catch(Q){return i(w.from(Q,null,e,Z.request,Z))}we(o,i,Z)})}y.once("abort",oe=>{j.destroyed||(j.emit("error",oe),j.destroy())})}),y.once("abort",_=>{i(_),m.destroy(_)}),m.on("error",function(E){i(w.from(E,null,e,m))}),m.on("socket",function(E){E.setKeepAlive(!0,1e3*60)}),e.timeout){let _=parseInt(e.timeout,10);if(Number.isNaN(_)){i(new w("error trying to parse `config.timeout` to int",w.ERR_BAD_OPTION_VALUE,e,m));return}m.setTimeout(_,function(){if(g)return;let W=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded",K=e.transitional||at;e.timeoutErrorMessage&&(W=e.timeoutErrorMessage),i(new w(W,K.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,e,m)),v()})}if(d.isStream(s)){let _=!1,E=!1;s.on("end",()=>{_=!0}),s.once("error",W=>{E=!0,m.destroy(W)}),s.on("close",()=>{!_&&!E&&v(new ae("Request stream has been aborted",e,m))}),s.pipe(m)}else m.end(s)})};var Is=O.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,O.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(O.origin),O.navigator&&/(msie|trident)/i.test(O.navigator.userAgent)):()=>!0;var Ps=O.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 Ds=t=>t instanceof B?{...t}:t;function ge(t,e){e=e||{};let r={};function o(c,u,p,g){return d.isPlainObject(c)&&d.isPlainObject(u)?d.merge.call({caseless:g},c,u):d.isPlainObject(u)?d.merge({},u):d.isArray(u)?u.slice():u}function i(c,u,p,g){if(d.isUndefined(u)){if(!d.isUndefined(c))return o(void 0,c,p,g)}else return o(c,u,p,g)}function n(c,u){if(!d.isUndefined(u))return o(void 0,u)}function s(c,u){if(d.isUndefined(u)){if(!d.isUndefined(c))return o(void 0,c)}else return o(void 0,u)}function a(c,u,p){if(p in e)return o(c,u);if(p in t)return o(void 0,c)}let l={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:(c,u,p)=>i(Ds(c),Ds(u),p,!0)};return d.forEach(Object.keys({...t,...e}),function(u){let p=l[u]||i,g=p(t[u],e[u],u);d.isUndefined(g)&&p!==a||(r[u]=g)}),r}var yr=t=>{let e=ge({},t),{data:r,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:n,headers:s,auth:a}=e;if(e.headers=s=B.from(s),e.url=ze(We(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(O.hasStandardBrowserEnv||O.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(d.isFunction(r.getHeaders)){let l=r.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([u,p])=>{c.includes(u.toLowerCase())&&s.set(u,p)})}}if(O.hasStandardBrowserEnv&&(o&&d.isFunction(o)&&(o=o(e)),o||o!==!1&&Is(e.url))){let l=i&&n&&Ps.read(n);l&&s.set(i,l)}return e};var Tu=typeof XMLHttpRequest<"u",ks=Tu&&function(t){return new Promise(function(r,o){let i=yr(t),n=i.data,s=B.from(i.headers).normalize(),{responseType:a,onUploadProgress:l,onDownloadProgress:c}=i,u,p,g,b,m;function y(){b&&b(),m&&m(),i.cancelToken&&i.cancelToken.unsubscribe(u),i.signal&&i.signal.removeEventListener("abort",u)}let T=new XMLHttpRequest;T.open(i.method.toUpperCase(),i.url,!0),T.timeout=i.timeout;function v(){if(!T)return;let S=B.from("getAllResponseHeaders"in T&&T.getAllResponseHeaders()),x={data:!a||a==="text"||a==="json"?T.responseText:T.response,status:T.status,statusText:T.statusText,headers:S,config:t,request:T};we(function(F){r(F),y()},function(F){o(F),y()},x),T=null}"onloadend"in T?T.onloadend=v:T.onreadystatechange=function(){!T||T.readyState!==4||T.status===0&&!(T.responseURL&&T.responseURL.indexOf("file:")===0)||setTimeout(v)},T.onabort=function(){T&&(o(new w("Request aborted",w.ECONNABORTED,t,T)),T=null)},T.onerror=function(C){let x=C&&C.message?C.message:"Network Error",q=new w(x,w.ERR_NETWORK,t,T);q.event=C||null,o(q),T=null},T.ontimeout=function(){let C=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded",x=i.transitional||at;i.timeoutErrorMessage&&(C=i.timeoutErrorMessage),o(new w(C,x.clarifyTimeoutError?w.ETIMEDOUT:w.ECONNABORTED,t,T)),T=null},n===void 0&&s.setContentType(null),"setRequestHeader"in T&&d.forEach(s.toJSON(),function(C,x){T.setRequestHeader(x,C)}),d.isUndefined(i.withCredentials)||(T.withCredentials=!!i.withCredentials),a&&a!=="json"&&(T.responseType=i.responseType),c&&([g,m]=_e(c,!0),T.addEventListener("progress",g)),l&&T.upload&&([p,b]=_e(l),T.upload.addEventListener("progress",p),T.upload.addEventListener("loadend",b)),(i.cancelToken||i.signal)&&(u=S=>{T&&(o(!S||S.type?new ae(null,t,T):S),T.abort(),T=null)},i.cancelToken&&i.cancelToken.subscribe(u),i.signal&&(i.signal.aborted?u():i.signal.addEventListener("abort",u)));let P=Ot(i.url);if(P&&O.protocols.indexOf(P)===-1){o(new w("Unsupported protocol "+P+":",w.ERR_BAD_REQUEST,t));return}T.send(n||null)})};var wu=(t,e)=>{let{length:r}=t=t?t.filter(Boolean):[];if(e||r){let o=new AbortController,i,n=function(c){if(!i){i=!0,a();let u=c instanceof Error?c:this.reason;o.abort(u instanceof w?u:new ae(u instanceof Error?u.message:u))}},s=e&&setTimeout(()=>{s=null,n(new w(`timeout ${e} of ms exceeded`,w.ETIMEDOUT))},e),a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(c=>{c.unsubscribe?c.unsubscribe(n):c.removeEventListener("abort",n)}),t=null)};t.forEach(c=>c.addEventListener("abort",n));let{signal:l}=o;return l.unsubscribe=()=>d.asap(a),l}},Ls=wu;var Au=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},Su=async function*(t,e){for await(let r of Eu(t))yield*Au(r,e)},Eu=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()}},Po=(t,e,r,o)=>{let i=Su(t,e),n=0,s,a=l=>{s||(s=!0,o&&o(l))};return new ReadableStream({async pull(l){try{let{done:c,value:u}=await i.next();if(c){a(),l.close();return}let p=u.byteLength;if(r){let g=n+=p;r(g)}l.enqueue(new Uint8Array(u))}catch(c){throw a(c),c}},cancel(l){return a(l),i.return()}},{highWaterMark:2})};var Ms=64*1024,{isFunction:br}=d,Fs=(({fetch:t,Request:e,Response:r})=>({fetch:t,Request:e,Response:r}))(d.global),{ReadableStream:Os,TextEncoder:Ns}=d.global,Us=(t,...e)=>{try{return!!t(...e)}catch{return!1}},_u=t=>{let{fetch:e,Request:r,Response:o}=Object.assign({},Fs,t),i=br(e),n=br(r),s=br(o);if(!i)return!1;let a=i&&br(Os),l=i&&(typeof Ns=="function"?(m=>y=>m.encode(y))(new Ns):async m=>new Uint8Array(await new r(m).arrayBuffer())),c=n&&a&&Us(()=>{let m=!1,y=new r(O.origin,{body:new Os,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!y}),u=s&&a&&Us(()=>d.isReadableStream(new o("").body)),p={stream:u&&(m=>m.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!p[m]&&(p[m]=(y,T)=>{let v=y&&y[m];if(v)return v.call(y);throw new w(`Response type '${m}' is not supported`,w.ERR_NOT_SUPPORT,T)})});let g=async m=>{if(m==null)return 0;if(d.isBlob(m))return m.size;if(d.isSpecCompliantForm(m))return(await new r(O.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(d.isArrayBufferView(m)||d.isArrayBuffer(m))return m.byteLength;if(d.isURLSearchParams(m)&&(m=m+""),d.isString(m))return(await l(m)).byteLength},b=async(m,y)=>{let T=d.toFiniteNumber(m.getContentLength());return T??g(y)};return async m=>{let{url:y,method:T,data:v,signal:P,cancelToken:S,timeout:C,onDownloadProgress:x,onUploadProgress:q,responseType:F,headers:te,withCredentials:pe="same-origin",fetchOptions:Se}=yr(m);F=F?(F+"").toLowerCase():"text";let ve=Ls([P,S&&S.toAbortSignal()],C),ne=null,le=ve&&ve.unsubscribe&&(()=>{ve.unsubscribe()}),G;try{if(q&&c&&T!=="get"&&T!=="head"&&(G=await b(te,v))!==0){let K=new r(y,{method:"POST",body:v,duplex:"half"}),j;if(d.isFormData(v)&&(j=K.headers.get("content-type"))&&te.setContentType(j),K.body){let[re,me]=ut(G,_e(dt(q)));v=Po(K.body,Ms,re,me)}}d.isString(pe)||(pe=pe?"include":"omit");let J=n&&"credentials"in r.prototype,Ce={...Se,signal:ve,method:T.toUpperCase(),headers:te.normalize().toJSON(),body:v,duplex:"half",credentials:J?pe:void 0};ne=n&&new r(y,Ce);let _=await(n?e(ne,Se):e(y,Ce)),E=u&&(F==="stream"||F==="response");if(u&&(x||E&&le)){let K={};["status","statusText","headers"].forEach(Z=>{K[Z]=_[Z]});let j=d.toFiniteNumber(_.headers.get("content-length")),[re,me]=x&&ut(j,_e(dt(x),!0))||[];_=new o(Po(_.body,Ms,re,()=>{me&&me(),le&&le()}),K)}F=F||"text";let W=await p[d.findKey(p,F)||"text"](_,m);return!E&&le&&le(),await new Promise((K,j)=>{we(K,j,{data:W,headers:B.from(_.headers),status:_.status,statusText:_.statusText,config:m,request:ne})})}catch(J){throw le&&le(),J&&J.name==="TypeError"&&/Load failed|fetch/i.test(J.message)?Object.assign(new w("Network Error",w.ERR_NETWORK,m,ne),{cause:J.cause||J}):w.from(J,J&&J.code,m,ne)}}},vu=new Map,Do=t=>{let e=d.merge.call({skipUndefined:!0},Fs,t?t.env:null),{fetch:r,Request:o,Response:i}=e,n=[o,i,r],s=n.length,a=s,l,c,u=vu;for(;a--;)l=n[a],c=u.get(l),c===void 0&&u.set(l,c=a?new Map:_u(e)),u=c;return c},Lb=Do();var ko={http:xs,xhr:ks,fetch:{get:Do}};d.forEach(ko,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch{}Object.defineProperty(t,"adapterName",{value:e})}});var qs=t=>`- ${t}`,Ru=t=>d.isFunction(t)||t===null||t===!1,Tr={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,!Ru(o)&&(i=ko[(a=String(o)).toLowerCase()],i===void 0))throw new w(`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(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build")),a=r?s.length>1?`since :
|
|
9
|
+
`+s.map(qs).join(`
|
|
10
|
+
`):" "+qs(s[0]):"as no adapter specified";throw new w("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return i},adapters:ko};function Lo(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ae(null,t)}function wr(t){return Lo(t),t.headers=B.from(t.headers),t.data=Lt.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Tr.getAdapter(t.adapter||lt.adapter,t)(t).then(function(o){return Lo(t),o.data=Lt.call(t,t.transformResponse,o),o.headers=B.from(o.headers),o},function(o){return Mt(o)||(Lo(t),o&&o.response&&(o.response.data=Lt.call(t,t.transformResponse,o.response),o.response.headers=B.from(o.response.headers))),Promise.reject(o)})}var Ar={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{Ar[t]=function(o){return typeof o===t||"a"+(e<1?"n ":" ")+t}});var js={};Ar.transitional=function(e,r,o){function i(n,s){return"[Axios v"+He+"] Transitional option '"+n+"'"+s+(o?". "+o:"")}return(n,s,a)=>{if(e===!1)throw new w(i(s," has been removed"+(r?" in "+r:"")),w.ERR_DEPRECATED);return r&&!js[s]&&(js[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}};Ar.spelling=function(e){return(r,o)=>(console.warn(`${o} is likely a misspelling of ${e}`),!0)};function xu(t,e,r){if(typeof t!="object")throw new w("options must be an object",w.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],l=a===void 0||s(a,n,t);if(l!==!0)throw new w("option "+n+" must be "+l,w.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new w("Unknown option "+n,w.ERR_BAD_OPTION)}}var Ut={assertOptions:xu,validators:Ar};var Ae=Ut.validators,mt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new mo,response:new mo}}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&&Ut.assertOptions(o,{silentJSONParsing:Ae.transitional(Ae.boolean),forcedJSONParsing:Ae.transitional(Ae.boolean),clarifyTimeoutError:Ae.transitional(Ae.boolean)},!1),i!=null&&(d.isFunction(i)?r.paramsSerializer={serialize:i}:Ut.assertOptions(i,{encode:Ae.function,serialize:Ae.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Ut.assertOptions(r,{baseUrl:Ae.spelling("baseURL"),withXsrfToken:Ae.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"],m=>{delete n[m]}),r.headers=B.concat(s,n);let a=[],l=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(l=l&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let u,p=0,g;if(!l){let m=[wr.bind(this),void 0];for(m.unshift(...a),m.push(...c),g=m.length,u=Promise.resolve(r);p<g;)u=u.then(m[p++],m[p++]);return u}g=a.length;let b=r;for(p=0;p<g;){let m=a[p++],y=a[p++];try{b=m(b)}catch(T){y.call(this,T);break}}try{u=wr.call(this,b)}catch(m){return Promise.reject(m)}for(p=0,g=c.length;p<g;)u=u.then(c[p++],c[p++]);return u}getUri(e){e=ge(this.defaults,e);let r=We(e.baseURL,e.url,e.allowAbsoluteUrls);return ze(r,e.params,e.paramsSerializer)}};d.forEach(["delete","get","head","options"],function(e){mt.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}))}}mt.prototype[e]=r(),mt.prototype[e+"Form"]=r(!0)});var Ft=mt;var Mo=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 ae(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}}},Vs=Mo;function Oo(t){return function(r){return t.apply(null,r)}}function No(t){return d.isObject(t)&&t.isAxiosError===!0}var Uo={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(Uo).forEach(([t,e])=>{Uo[e]=t});var Bs=Uo;function zs(t){let e=new Ft(t),r=xt(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 zs(ge(t,i))},r}var $=zs(lt);$.Axios=Ft;$.CanceledError=ae;$.CancelToken=Vs;$.isCancel=Mt;$.VERSION=He;$.toFormData=Ie;$.AxiosError=w;$.Cancel=$.CanceledError;$.all=function(e){return Promise.all(e)};$.spread=Oo;$.isAxiosError=No;$.mergeConfig=ge;$.AxiosHeaders=B;$.formToJSON=t=>fr(d.isHTMLForm(t)?new FormData(t):t);$.getAdapter=Tr.getAdapter;$.HttpStatusCode=Bs;$.default=$;var qt=$;var{Axios:IT,AxiosError:PT,CanceledError:DT,isCancel:kT,CancelToken:LT,VERSION:MT,all:OT,Cancel:NT,isAxiosError:De,spread:UT,toFormData:FT,AxiosHeaders:qT,HttpStatusCode:jT,formToJSON:VT,getAdapter:BT,mergeConfig:zT}=qt;function Fo(t,e){let r=t[e]||"";return typeof r=="string"?r:""}import{makeApi as Fu,makeEndpoint as ft}from"@zodios/core";import{z as U}from"zod";import{z as h}from"zod";var Iu=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()}),Pu=h.object({id:h.string()}),Ws=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()}))}),Sr=h.object({measure:h.object({field:h.string(),aggregation:h.string()}),time_dimension:h.object({field:h.string()}),filters:h.array(Ws)}),Du=h.object({datasource:Pu,basic_specification:Sr.optional(),viz_state_specification:h.object({viz_state_string:h.string()}).optional(),is_running_total:h.boolean()}),Hs=h.object({allowed_dimensions:h.array(h.string()),allowed_granularities:h.array(h.string()),offset_from_today:h.number()}),$s=h.object({filters:h.array(Ws),measurement_period:h.object({granularity:h.string(),range:h.string()}),comparison:h.object({comparison:h.string()})}),Gs=h.object({target:h.object({value:h.number()}).optional()}),Er=h.object({id:h.string(),specification:$s,definition_id:h.string(),is_default:h.boolean(),schema_version:h.string(),metric_version:h.coerce.number(),goals:Gs.optional(),is_followed:h.boolean(),datasource_luid:h.string()}),Qs=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()}),Ks=h.object({settings:h.array(h.object({type:h.string(),disabled:h.boolean()}))}),ku=h.object({comparisons:h.array(h.object({compare_config:h.object({comparison:h.string()}),index:h.coerce.number()}))}),Lu=h.array(h.object({basic_specification:Sr.optional(),threshold_basic_specification:Sr.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()})),qo=h.object({metadata:Iu,specification:Du,extension_options:Hs,metrics:h.array(Er),total_metrics:h.coerce.number(),representation_options:Qs,insights_options:Ks,comparisons:ku,datasource_goals:Lu}),Js=h.object({id:h.string(),metric_id:h.string()}),Mu=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"]),Ou=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"]),Nu=h.enum(["OUTPUT_FORMAT_UNSPECIFIED","OUTPUT_FORMAT_HTML","OUTPUT_FORMAT_TEXT"]),_r=h.object({bundle_request:h.object({version:h.number(),options:h.object({output_format:Nu,time_zone:h.string(),language:Mu,locale:Ou}),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:Sr,is_running_total:h.boolean()}),metric_specification:$s,extension_options:Hs,representation_options:Qs,insights_options:Ks,goals:Gs.optional()})})})}),Uu=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()})}))}),Ys=h.object({bundle_response:h.object({result:h.object({insight_groups:h.array(Uu),has_errors:h.boolean(),characterization:h.string()})})}),vr=["ban","springboard","basic","detail"],Ge=["DEFINITION_VIEW_BASIC","DEFINITION_VIEW_FULL","DEFINITION_VIEW_DEFAULT"];var qu=ft({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:U.optional(U.enum(Ge)),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:U.optional(U.coerce.number().int().positive()),description:"Specifies the number of results in a paged response."},{name:"page_token",type:"Query",schema:U.optional(U.string()),description:"Token for retrieving the next page of results. Omit for the first page."}],response:U.object({definitions:U.array(qo),next_page_token:U.string().optional(),offset:U.coerce.number(),total_available:U.coerce.number()})}),ju=ft({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:U.object({definition_ids:U.array(U.string().nonempty()).min(1)}),description:"A list of metric definition IDs to retrieve."},{name:"view",type:"Query",schema:U.optional(U.enum(Ge)),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:j.object({definitions:j.array(Eo)})}),iu=ct({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:j.string().nonempty()}],response:j.object({metrics:j.array(hr),total_available:j.number()})}),su=ct({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:j.object({metric_ids:j.array(j.string().nonempty())})}],response:j.object({metrics:j.array(hr)})}),nu=ct({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:j.string().nonempty()}],response:j.object({subscriptions:j.array(Rs)})}),au=ct({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:gr},{name:"bundle_type",type:"Path",schema:j.enum(br)}],response:xs}),lu=tu([au,ru,ou,iu,nu,su]),Is=[...lu];var Lt=class extends H{constructor(e,r){super(new cu(e,Is),r)}listAllPulseMetricDefinitions=async e=>await ut(async()=>(await this._apiClient.listAllPulseMetricDefinitions({queries:{view:e},...this.authHeader})).definitions??[]);listPulseMetricDefinitionsFromMetricDefinitionIds=async(e,r)=>await ut(async()=>(await this._apiClient.listPulseMetricDefinitionsFromMetricDefinitionIds({definition_ids:e},{queries:{view:r},...this.authHeader})).definitions??[]);listPulseMetricsFromMetricDefinitionId=async e=>await ut(async()=>(await this._apiClient.listPulseMetricsFromMetricDefinitionId({params:{pulseMetricDefinitionID:e},...this.authHeader})).metrics??[]);listPulseMetricsFromMetricIds=async e=>await ut(async()=>(await this._apiClient.listPulseMetricsFromMetricIds({metric_ids:e},{...this.authHeader})).metrics??[]);listPulseMetricSubscriptionsForCurrentUser=async()=>await ut(async()=>(await this._apiClient.listPulseMetricSubscriptionsForCurrentUser({queries:{user_id:this.userId},...this.authHeader})).subscriptions??[]);generatePulseMetricValueInsightBundle=async(e,r)=>await ut(async()=>await this._apiClient.generatePulseMetricValueInsightBundle({bundle_request:e.bundle_request},{params:{bundle_type:r},...this.authHeader})??{})};async function ut(t){try{return new uu(await t())}catch(e){if(Ie(e)){if(e.response?.status===404)return new ks("tableau-server");if(e.response?.status===400&&e.response.headers.tableau_error_code==="0xd3408984"&&e.response.headers.validation_code==="400999")return new ks("pulse-disabled")}throw e}}import{isErrorFromAlias as gu,Zodios as bu}from"@zodios/core";import{Err as Co,Ok as yu}from"ts-results-es";import{makeApi as du,makeEndpoint as pu}from"@zodios/core";import{z as ze}from"zod";import{z as _o}from"zod";var Ds=_o.object({id:_o.string(),name:_o.string()});import{z as So}from"zod";var Ps=So.object({id:So.string(),name:So.string()});var mu=ze.object({site:Ds,user:Ps}),fu=pu({method:"get",path:"/sessions/current",alias:"getCurrentServerSession",description:"Returns details of the current session of Tableau Server.",response:ze.object({session:mu}),errors:[{status:401,schema:ze.object({error:ze.object({code:ze.string(),summary:ze.string(),detail:ze.string()})})}]}),hu=du([fu]),Ls=[...hu];var Ot=class extends H{constructor(e,r){super(new bu(e,Ls),r)}getCurrentServerSession=async()=>{try{let e=await this._apiClient.getCurrentServerSession({...this.authHeader});return yu(e.session)}catch(e){return gu(this._apiClient.api,"getCurrentServerSession",e)?Co({type:"unauthorized",message:e.response.data.error}):Ie(e)&&e.response?Co({type:"unknown",message:e.response.data}):Co({type:"unknown",message:W(e)})}}};import{Zodios as vu}from"@zodios/core";import{makeApi as wu,makeEndpoint as Mt}from"@zodios/core";import{z as te}from"zod";import{z as Y}from"zod";var dt=Y.object({id:Y.string(),name:Y.string(),createdAt:Y.string(),updatedAt:Y.string(),workbook:Y.object({id:Y.string()}).optional(),owner:Y.object({id:Y.string()}).optional(),project:Y.object({id:Y.string()}).optional(),tags:Y.object({tag:Y.array(Y.object({label:Y.string()})).optional()}),usage:Y.object({totalViewCount:Y.coerce.number()}).optional()});var Tu=Mt({method:"get",path:"/sites/:siteId/views/:viewId",alias:"getView",description:"Gets the details of a specific view.",response:te.object({view:dt})}),Au=Mt({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:te.string()}),Eu=Mt({method:"get",path:"/sites/:siteId/views/:viewId/image",alias:"queryViewImage",description:"Returns an image of the specified view.",parameters:[{name:"vizWidth",type:"Query",schema:te.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:te.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:te.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:te.string()}),_u=Mt({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:te.boolean().optional(),description:"true to return usage statistics. The default is false."}],response:te.object({views:te.object({view:te.array(dt)})})}),Su=Mt({method:"get",path:"/sites/:siteId/views",alias:"queryViewsForSite",description:"Returns all the views for the specified site, optionally including usage statistics.",parameters:[...Ye,{name:"includeUsageStatistics",type:"Query",schema:te.boolean().optional(),description:"true to return usage statistics. The default is false."},{name:"filter",type:"Query",schema:te.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:te.object({pagination:Ze,views:te.object({view:te.array(dt).optional()})})}),Cu=wu([Tu,Au,Eu,_u,Su]),Os=[...Cu];var Nt=class extends H{constructor(e,r){super(new vu(e,Os),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 Bs,Zodios as Qu,ZodiosError as Ku}from"@zodios/core";import{Err as wr,Ok as zs}from"ts-results-es";import{makeApi as Ru}from"@zodios/core";import{z as p}from"zod";var xu=p.object({connectionLuid:p.string().optional(),connectionUsername:p.string(),connectionPassword:p.string()}),Ms=p.object({datasourceLuid:p.string().nonempty(),connections:p.array(xu).optional()}),Iu=p.enum(["OBJECTS","ARRAYS"]),Ns=p.object({returnFormat:Iu,debug:p.boolean().default(!1)}).partial().passthrough(),ku=p.object({datasource:Ms,options:Ns.optional()}).passthrough(),xo=p.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"]),Fs=p.enum(["INTEGER","REAL","STRING","DATETIME","BOOLEAN","DATE","SPATIAL","UNKNOWN"]),Us=p.enum(["MINUTES","HOURS","DAYS","WEEKS","MONTHS","QUARTERS","YEARS"]),Du=p.object({fieldName:p.string(),fieldCaption:p.string(),dataType:Fs,defaultAggregation:xo,columnClass:p.enum(["COLUMN","BIN","GROUP","CALCULATION","TABLE_CALCULATION"]),formula:p.string(),logicalTableId:p.string()}).partial().passthrough(),qs=p.union([p.number(),p.string(),p.boolean(),p.null()]),yr=p.object({parameterCaption:p.string(),dataType:Fs.exclude(["DATETIME","SPATIAL","UNKNOWN"]),parameterName:p.string().optional(),value:qs}),Pu=p.discriminatedUnion("parameterType",[yr.extend({parameterType:p.literal("ANY_VALUE")}).strict(),yr.extend({parameterType:p.literal("LIST"),members:p.array(qs)}).strict(),yr.extend({parameterType:p.literal("QUANTITATIVE_DATE"),value:p.string().nullable(),minDate:p.string().nullish(),maxDate:p.string().nullish(),periodValue:p.number().nullish(),periodType:Us.nullish()}).strict(),yr.extend({parameterType:p.literal("QUANTITATIVE_RANGE"),value:p.number().nullable(),min:p.number().nullish(),max:p.number().nullish(),step:p.number().nullish()}).strict()]),Lu=p.object({data:p.array(Du),extraData:p.object({parameters:p.array(Pu)})}).partial().passthrough(),Ou=p.object({errorCode:p.string(),message:p.string(),datetime:p.string().datetime({offset:!0}),debug:p.object({}).partial().passthrough(),"tab-error-code":p.string()}).partial().passthrough(),Mu=p.enum(["ASC","DESC"]),vo=p.object({fieldCaption:p.string(),fieldAlias:p.string().optional(),maxDecimalPlaces:p.number().int().optional(),sortDirection:Mu.optional(),sortPriority:p.number().int().optional()}),Nu=p.union([vo.strict(),vo.extend({function:xo}).strict(),vo.extend({calculation:p.string()}).strict()]),js=p.union([p.object({fieldCaption:p.string()}).strict(),p.object({fieldCaption:p.string(),function:xo}).strict(),p.object({calculation:p.string()}).strict()]),Io=p.object({field:js,context:p.boolean().optional()}),ko=p.object({field:p.object({fieldCaption:p.string()}).strict(),context:p.boolean().optional()}),Fu=ko.extend({filterType:p.literal("SET"),values:p.union([p.array(p.string()),p.array(p.number()),p.array(p.boolean())]),exclude:p.boolean().optional()}),pt=ko.extend({filterType:p.literal("DATE"),periodType:Us,anchorDate:p.string().optional(),includeNulls:p.boolean().optional()}),Uu=p.discriminatedUnion("dateRangeType",[pt.extend({dateRangeType:p.literal("CURRENT")}).strict(),pt.extend({dateRangeType:p.literal("LAST")}).strict(),pt.extend({dateRangeType:p.literal("NEXT")}).strict(),pt.extend({dateRangeType:p.literal("TODATE")}).strict(),pt.extend({dateRangeType:p.literal("LASTN"),rangeN:p.number().int()}).strict(),pt.extend({dateRangeType:p.literal("NEXTN"),rangeN:p.number().int()}).strict()]),Ro=ko.extend({filterType:p.literal("MATCH"),startsWith:p.string().optional(),endsWith:p.string().optional(),contains:p.string().optional(),exclude:p.boolean().optional()}),qu=p.union([Ro.extend({startsWith:p.string()}).strict(),Ro.extend({endsWith:p.string()}).strict(),Ro.extend({contains:p.string()}).strict()]),Ft=Io.extend({filterType:p.literal("QUANTITATIVE_NUMERICAL")}),ju=p.discriminatedUnion("quantitativeFilterType",[Ft.extend({quantitativeFilterType:p.literal("RANGE"),min:p.number(),max:p.number(),includeNulls:p.boolean().optional()}).strict(),Ft.extend({quantitativeFilterType:p.literal("MIN"),min:p.number(),includeNulls:p.boolean().optional()}).strict(),Ft.extend({quantitativeFilterType:p.literal("MAX"),max:p.number(),includeNulls:p.boolean().optional()}).strict(),Ft.extend({quantitativeFilterType:p.literal("ONLY_NULL")}).strict(),Ft.extend({quantitativeFilterType:p.literal("ONLY_NON_NULL")}).strict()]),Ut=Io.extend({filterType:p.literal("QUANTITATIVE_DATE")}),Vu=p.discriminatedUnion("quantitativeFilterType",[Ut.extend({quantitativeFilterType:p.literal("RANGE"),minDate:p.string(),maxDate:p.string(),includeNulls:p.boolean().optional()}).strict(),Ut.extend({quantitativeFilterType:p.literal("MIN"),minDate:p.string(),includeNulls:p.boolean().optional()}).strict(),Ut.extend({quantitativeFilterType:p.literal("MAX"),maxDate:p.string(),includeNulls:p.boolean().optional()}).strict(),Ut.extend({quantitativeFilterType:p.literal("ONLY_NULL")}).strict(),Ut.extend({quantitativeFilterType:p.literal("ONLY_NON_NULL")}).strict()]),Bu=Io.extend({filterType:p.literal("TOP"),howMany:p.number().int(),fieldToMeasure:js,direction:p.enum(["TOP","BOTTOM"]).optional().default("TOP")}),zu=p.union([Fu.strict(),Bu.strict(),...qu.options,...ju.options,...Vu.options,...Uu.options]),qt=p.strictObject({fields:p.array(Nu),filters:p.array(zu).optional()}),Wu=Ns.and(p.object({disaggregate:p.boolean()}).partial().passthrough()),Hu=p.object({datasource:Ms,query:qt,options:Wu.optional()}).passthrough(),Gu=p.object({data:p.array(p.unknown())}).partial().passthrough(),$u=Ru([{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:Hu}],response:Gu,errors:[{status:"default",schema:Ou},{status:404,schema:p.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:ku}],response:Lu,errors:[{status:404,schema:p.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:p.string()}]),Vs=[...$u];var jt=class extends H{constructor(e,r){super(new Qu(e,Vs),r)}queryDatasource=async e=>{try{return zs(await this._apiClient.queryDatasource(e,{...this.authHeader}))}catch(r){if(Bs(this._apiClient.api,"queryDatasource",r))return r.response.status===404?wr("feature-disabled"):wr(r.response.data);if(r instanceof Ku)return wr(r);throw r}};readMetadata=async e=>{try{return zs(await this._apiClient.readMetadata(e,{...this.authHeader}))}catch(r){if(Bs(this._apiClient.api,"readMetadata",r)&&r.response.status===404)return wr("feature-disabled");throw r}}};import{Zodios as ed}from"@zodios/core";import{makeApi as Ju,makeEndpoint as Ws}from"@zodios/core";import{z as We}from"zod";import{z as re}from"zod";var Do=re.object({id:re.string(),name:re.string(),description:re.string().optional(),webpageUrl:re.string().optional(),contentUrl:re.string(),project:Xt.optional(),showTabs:re.coerce.boolean(),defaultViewId:re.string().optional(),tags:re.object({tag:re.array(re.object({label:re.string()})).optional()}),views:re.optional(re.object({view:re.array(dt)}))});var Zu=Ws({method:"get",path:"/sites/:siteId/workbooks/:workbookId",alias:"getWorkbook",description:"Returns information about the specified workbook, including information about views and tags.",response:We.object({workbook:Do})}),Yu=Ws({method:"get",path:"/sites/:siteId/workbooks",alias:"queryWorkbooksForSite",description:"Returns the workbooks on a site.",parameters:[...Ye,{name:"siteId",type:"Path",schema:We.string()},{name:"filter",type:"Query",schema:We.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:We.object({pagination:Ze,workbooks:We.object({workbook:We.optional(We.array(Do))})})}),Xu=Ju([Yu,Zu]),Hs=[...Xu];var Vt=class extends H{constructor(e,r){super(new ed(e,Hs),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 He=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 yt(this._baseUrl),this._addInterceptors(this._baseUrl,this._authenticationMethods.interceptors)),this._authenticationMethods}get authenticatedAuthenticationMethods(){return this._authenticatedAuthenticationMethods||(this._authenticatedAuthenticationMethods=new Yt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._authenticatedAuthenticationMethods.interceptors)),this._authenticatedAuthenticationMethods}get contentExplorationMethods(){return this._contentExplorationMethods||(this._contentExplorationMethods=new wt(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._contentExplorationMethods.interceptors)),this._contentExplorationMethods}get datasourcesMethods(){return this._datasourcesMethods||(this._datasourcesMethods=new Tt(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 At(e,this.creds),this._addInterceptors(e,this._metadataMethods.interceptors)}return this._metadataMethods}get pulseMethods(){return this._pulseMethods||(this._pulseMethods=new Lt(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._pulseMethods.interceptors)),this._pulseMethods}get serverMethods(){return this._serverMethods||(this._serverMethods=new Ot(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 jt(e,this.creds),this._addInterceptors(e,this._vizqlDataServiceMethods.interceptors)}return this._vizqlDataServiceMethods}get viewsMethods(){return this._viewsMethods||(this._viewsMethods=new Nt(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};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,...Jt(o)}),o),o=>(this._requestInterceptor?.[1]?.(o,e),Promise.reject(o))),r.response.use(o=>(this._responseInterceptor?.[0]({baseUrl:e,...Zt(o)}),o),o=>(this._responseInterceptor?.[1]?.(o,e),Promise.reject(o)))}};var td=async(t,e,r,o,i)=>{let n=t.server||i?.server;ue(n,"Tableau server could not be determined");let s=new He(n,{requestInterceptor:[rd(r,e),od(r,e)],responseInterceptor:[id(r,e),sd(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:nd(t,i),clientId:t.connectedAppClientId,secretId:t.connectedAppSecretId,secretValue:t.connectedAppSecretValue,scopes:o,additionalPayload:ad(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 td(t,e,r,new Set(i),n);try{return await o(s)}finally{t.auth!=="oauth"&&await s.signOut()}},rd=(t,e)=>r=>(r.headers["User-Agent"]=Tr,Gs(t,r,e),r),od=(t,e)=>(r,o)=>{if(!Ie(r)||!r.request){de.error(t,`Request ${e} failed with error: ${W(r)}`,{logger:"rest-api",requestId:e});return}let{request:i}=r;Gs(t,{baseUrl:o,...Jt(i)},e)},id=(t,e)=>r=>($s(t,r,e),r),sd=(t,e)=>(r,o)=>{if(!Ie(r)||!r.response){de.error(t,`Response from request ${e} failed with error: ${W(r)}`,{logger:"rest-api",requestId:e});return}let{response:i}=r;$s(t,{baseUrl:o,...Zt(i)},e)};function Gs(t,e,r){let i=E().disableLogMasking?e:ni(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(),...Pe("debug")&&{headers:i.headers,data:i.data,params:i.params}};de.info(t,s,{logger:"rest-api",requestId:r})}function $s(t,e,r){let i=E().disableLogMasking?e:ai(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,...Pe("debug")&&{headers:i.headers,data:i.data}};de.info(t,s,{logger:"rest-api",requestId:r})}function nd(t,e){return t.jwtSubClaim.replaceAll("{OAUTH_USERNAME}",e?.username??"")}function ad(t,e){let r=t.jwtAdditionalPayload.replaceAll("{OAUTH_USERNAME}",e?.username??"");return JSON.parse(r||"{}")}import{z as F}from"zod";import{z as ld}from"zod";var B=t=>ld.string({message:`${t} is required`}).nonempty({message:`${t} must be non-empty`});var Qs=F.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:F.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})),Ks=F.discriminatedUnion("grant_type",[F.object({grant_type:F.literal("authorization_code"),code:B("code"),redirect_uri:B("redirect_uri"),code_verifier:B("code_verifier")}),F.object({grant_type:F.literal("refresh_token"),refresh_token:B("refresh_token")}),F.object({grant_type:F.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(F.object({client_id:F.string().optional(),client_secret:F.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}}),Js=F.object({code:F.string().optional(),state:F.string().optional(),error:F.string().optional()}),Po=F.object({iss:B("iss"),aud:B("aud"),exp:F.number().int().nonnegative(),sub:B("sub"),clientId:B("clientId"),tableauServer:B("tableauServer"),tableauUserId:F.string().optional()}),Zs=Po.extend({tableauAccessToken:B("tableauAccessToken"),tableauRefreshToken:B("tableauRefreshToken"),tableauExpiresAt:F.number().int().nonnegative(),tableauUserId:B("tableauUserId")}),Ar=F.object({username:F.string(),userId:F.string(),server:F.string(),accessToken:F.string(),refreshToken:F.string()}).partial();var M=t=>{if(!t)return;let e=Ar.safeParse(t.extra);if(e.success)return e.data};import{ZodiosError as Ys}from"@zodios/core";import{fromError as cd,isZodErrorLike as ud}from"zod-validation-error";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,this.paramsSchema=i,this.annotations=n,this.argsValidator=s,this.callback=a}logInvocation({requestId:e,args:r,username:o}){de.debug(this.server,oi({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 d=o?.extra?Ar.safeParse(o.extra).data?.username:void 0;if(this.logInvocation({requestId:e,args:r,username:d}),r)try{this.argsValidator?.(r)}catch(l){return Er(e,l)}try{let l=await i();if(l.isOk()){let c=await a(l.value);return c.type!=="success"?{isError:c.type==="error",content:[{type:"text",text:c.message}]}:n?n(c.result):{isError:!1,content:[{type:"text",text:JSON.stringify(c.result)}]}}return l.error instanceof Ys?Er(e,l.error):s?{isError:!0,content:[{type:"text",text:s(l.error)}]}:Er(e,l.error)}catch(l){return Er(e,l)}}};function Er(t,e){if(e instanceof Ys&&ud(e.cause)){let r=cd(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 Xs(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 en(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 tn(t){let e=[];if(t.items)for(let r of t.items)e.push(dd(r.content));return e}function dd(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 rn({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"||n.type==="unifieddatasource")&&typeof n.datasourceLuid=="string"&&!o.has(n.datasourceLuid)))),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 md={terms:on.string().trim().nonempty().optional(),limit:on.number().int().min(1).max(2e3).default(100).optional(),orderBy:mi.optional(),filter:gi.optional()},sn=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:md,annotations:{title:"Search Content",readOnlyHint:!0,openWorldHint:!1},callback:async({terms:r,limit:o,orderBy:i,filter:n},{requestId:s,authInfo:a})=>{let d=E(),l=i?Xs(i):void 0,c=n?en(n):void 0;return await e.logAndExecute({requestId:s,authInfo:a,args:{},callback:async()=>new pd(await I({config:d,requestId:s,server:t,jwtScopes:["tableau:content:read"],authInfo:M(a),callback:async m=>{let g=await m.contentExplorationMethods.searchContent({terms:r,page:0,limit:d.maxResultLimit?Math.min(d.maxResultLimit,o??100):o??100,orderBy:l,filter:c});return tn(g)}})),constrainSuccessResult:m=>rn({items:m,boundedContext:d.boundedContext})})}});return e};import{Err as ln,Ok as Oo}from"ts-results-es";import{z as gd}from"zod";function _r(){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 Bt=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 d=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=d.workbook?.id??"",a=d.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(d){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(d)].join(" ")}}if(this.allowedProjectIds)try{if(a=a||await I({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async d=>(await d.viewsMethods.getView({siteId:d.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(d){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(d)].join(" ")}}return{allowed:!0}}},ge=Bt.create(),dA={createResourceAccessChecker:Bt.createForTesting,resetResourceAccessCheckerSingleton:()=>{ge=Bt.create()}};function Sr({datasourceLuid:t}){if(!t)throw new Error("datasourceLuid must be a non-empty string.")}import{z as v}from"zod";var fd=v.object({name:v.string(),columnClass:v.string(),dataType:v.string().nullable(),defaultAggregation:v.string().nullable(),description:v.string().nullable(),descriptionInherited:v.array(v.object({attribute:v.string(),value:v.string().nullable()}).nullable()).nullable(),dataCategory:v.string().nullable(),role:v.string().nullable(),defaultFormat:v.string().nullable(),semanticRole:v.string().nullable(),aggregation:v.string().nullable(),aggregationParam:v.string().nullable(),formula:v.string().nullable(),isAutoGenerated:v.boolean().nullable(),hasUserReference:v.boolean().nullable(),binSize:v.number().nullable()}).partial(),hd=v.object({name:v.string(),parameterType:v.string(),dataType:v.string().nullable(),value:v.union([v.number(),v.string(),v.boolean(),v.null()]),members:v.array(v.union([v.number(),v.string(),v.boolean(),v.null()])),min:v.number().nullable(),max:v.number().nullable(),step:v.number().nullable(),minDate:v.string().nullable(),maxDate:v.string().nullable(),periodValue:v.number().nullable(),periodType:v.string().nullable()}).partial(),hA=v.object({fields:v.array(fd),parameters:v.array(hd)});function Lo(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 an(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),nn(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&&nn(i,o)}return r}function nn(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 bd=t=>`
|
|
17
|
+
- 'DEFINITION_VIEW_DEFAULT' - Return the metric definition and the default metric.`}],response:U.object({definitions:U.array(qo)})}),Vu=ft({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:U.string().nonempty()}],response:U.object({metrics:U.array(Er),total_available:U.number()})}),Bu=ft({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:U.object({metric_ids:U.array(U.string().nonempty())})}],response:U.object({metrics:U.array(Er)})}),zu=ft({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:U.string().nonempty()}],response:U.object({subscriptions:U.array(Js)})}),Wu=ft({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:_r},{name:"bundle_type",type:"Path",schema:U.enum(vr)}],response:Ys}),Hu=Fu([Wu,qu,ju,Vu,zu,Bu]),Zs=[...Hu];var jt=class extends H{constructor(e,r){super(new $u(e,Zs),r)}listAllPulseMetricDefinitions=async(e,r,o)=>await ht(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 ht(async()=>(await this._apiClient.listPulseMetricDefinitionsFromMetricDefinitionIds({definition_ids:e},{queries:{view:r},...this.authHeader})).definitions??[]);listPulseMetricsFromMetricDefinitionId=async e=>await ht(async()=>(await this._apiClient.listPulseMetricsFromMetricDefinitionId({params:{pulseMetricDefinitionID:e},...this.authHeader})).metrics??[]);listPulseMetricsFromMetricIds=async e=>await ht(async()=>(await this._apiClient.listPulseMetricsFromMetricIds({metric_ids:e},{...this.authHeader})).metrics??[]);listPulseMetricSubscriptionsForCurrentUser=async()=>await ht(async()=>(await this._apiClient.listPulseMetricSubscriptionsForCurrentUser({queries:{user_id:this.userId},...this.authHeader})).subscriptions??[]);generatePulseMetricValueInsightBundle=async(e,r)=>await ht(async()=>await this._apiClient.generatePulseMetricValueInsightBundle({bundle_request:e.bundle_request},{params:{bundle_type:r},...this.authHeader})??{})};async function ht(t){try{return new Gu(await t())}catch(e){if(De(e)){if(e.response?.status===404)return new Xs("tableau-server");if(e.response?.status===400&&e.response.headers.tableau_error_code==="0xd3408984"&&e.response.headers.validation_code==="400999")return new Xs("pulse-disabled")}throw e}}import{isErrorFromAlias as Xu,Zodios as sn}from"@zodios/core";import{Err as zo,Ok as ed}from"ts-results-es";import{makeApi as Qu,makeEndpoint as on}from"@zodios/core";import{z as ke}from"zod";import{z as Vt}from"zod";var en=Vt.object({productVersion:Vt.object({value:Vt.string(),build:Vt.string()}),restApiVersion:Vt.string()});import{z as jo}from"zod";var tn=jo.object({id:jo.string(),name:jo.string()});import{z as Vo}from"zod";var rn=Vo.object({id:Vo.string(),name:Vo.string()});var Ku=ke.object({site:tn,user:rn}),Ju=on({method:"get",path:"/serverinfo",alias:"getServerInfo",description:"Returns the version of Tableau Server and the supported version of the REST API.",response:ke.object({serverInfo:en})}),Yu=on({method:"get",path:"/sessions/current",alias:"getCurrentServerSession",description:"Returns details of the current session of Tableau Server.",response:ke.object({session:Ku}),errors:[{status:401,schema:ke.object({error:ke.object({code:ke.string(),summary:ke.string(),detail:ke.string()})})}]}),Zu=Qu([Ju,Yu]),Bo=[...Zu];var Cr=class extends Ee{constructor(e){super(new sn(e,Bo))}getServerInfo=async()=>(await this._apiClient.getServerInfo()).serverInfo},Rr=class extends H{constructor(e,r){super(new sn(e,Bo),r)}getCurrentServerSession=async()=>{try{let e=await this._apiClient.getCurrentServerSession({...this.authHeader});return ed(e.session)}catch(e){return Xu(this._apiClient.api,"getCurrentServerSession",e)?zo({type:"unauthorized",message:e.response.data.error}):De(e)&&e.response?zo({type:"unknown",message:e.response.data}):zo({type:"unknown",message:V(e)})}}};import{Zodios as ld}from"@zodios/core";import{makeApi as td,makeEndpoint as Bt}from"@zodios/core";import{z as X}from"zod";import{z as Y}from"zod";var gt=Y.object({id:Y.string(),name:Y.string(),createdAt:Y.string(),updatedAt:Y.string(),workbook:Y.object({id:Y.string()}).optional(),owner:Y.object({id:Y.string()}).optional(),project:Y.object({id:Y.string()}).optional(),tags:Y.object({tag:Y.array(Y.object({label:Y.string()})).optional()}),usage:Y.object({totalViewCount:Y.coerce.number()}).optional()});var rd=Bt({method:"get",path:"/sites/:siteId/views/:viewId",alias:"getView",description:"Gets the details of a specific view.",response:X.object({view:gt})}),od=Bt({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()}),id=Bt({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()}),sd=Bt({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(gt)})})}),nd=Bt({method:"get",path:"/sites/:siteId/views",alias:"queryViewsForSite",description:"Returns all the views for the specified site, optionally including usage statistics.",parameters:[...ot,{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:rt,views:X.object({view:X.array(gt).optional()})})}),ad=td([rd,od,id,sd,nd]),nn=[...ad];var zt=class extends H{constructor(e,r){super(new ld(e,nn),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 mn,Zodios as Bd,ZodiosError as zd}from"@zodios/core";import{Err as Pr,Ok as fn}from"ts-results-es";import{makeApi as cd,makeEndpoint as Ho}from"@zodios/core";import{z as f}from"zod";var $o=f.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"]),an=f.enum(["INTEGER","REAL","STRING","DATETIME","BOOLEAN","DATE","SPATIAL","UNKNOWN"]),ln=f.enum(["MINUTES","HOURS","DAYS","WEEKS","MONTHS","QUARTERS","YEARS"]),ud=f.enum(["COLUMN","BIN","GROUP","CALCULATION","TABLE_CALCULATION"]),dd=f.object({fieldName:f.string(),fieldCaption:f.string(),dataType:an,defaultAggregation:$o,columnClass:ud,formula:f.string(),logicalTableId:f.string()}).partial().passthrough(),Go=f.union([f.number(),f.string(),f.boolean(),f.null()]),xr=f.object({parameterCaption:f.string(),dataType:an.exclude(["DATETIME","SPATIAL","UNKNOWN"]),parameterName:f.string().optional(),value:Go}),pd=f.discriminatedUnion("parameterType",[xr.extend({parameterType:f.literal("ANY_VALUE")}).strict(),xr.extend({parameterType:f.literal("LIST"),members:f.array(Go)}).strict(),xr.extend({parameterType:f.literal("QUANTITATIVE_DATE"),value:f.string().nullable(),minDate:f.string().nullish(),maxDate:f.string().nullish(),periodValue:f.number().nullish(),periodType:ln.nullish()}).strict(),xr.extend({parameterType:f.literal("QUANTITATIVE_RANGE"),value:f.number().nullable(),min:f.number().nullish(),max:f.number().nullish(),step:f.number().nullish()}).strict()]),md=f.enum(["ASC","DESC"]),Ir=f.object({fieldCaption:f.string(),fieldAlias:f.string().optional(),maxDecimalPlaces:f.number().int().gte(0).optional(),sortDirection:md.optional(),sortPriority:f.number().int().gt(0).optional()}),fd=Ir.strict(),hd=Ir.extend({function:$o}).strict(),gd=Ir.extend({calculation:f.string()}).strict(),yd=Ir.extend({binSize:f.number().gt(0)}).strict(),bd=f.union([fd,hd,gd,yd]),Td=f.object({fieldCaption:f.string()}).strict(),wd=f.object({fieldCaption:f.string(),function:$o}).strict(),Ad=f.object({calculation:f.string()}).strict(),cn=f.union([Td,wd,Ad]),Qo=f.object({field:cn,context:f.boolean().optional()}),Ko=f.object({field:f.object({fieldCaption:f.string()}).strict(),context:f.boolean().optional()}),Sd=Ko.extend({filterType:f.literal("SET"),values:f.union([f.array(f.string()),f.array(f.number()),f.array(f.boolean())]),exclude:f.boolean().optional()}),yt=Ko.extend({filterType:f.literal("DATE"),periodType:ln,anchorDate:f.string().optional(),includeNulls:f.boolean().optional()}),Ed=f.discriminatedUnion("dateRangeType",[yt.extend({dateRangeType:f.literal("CURRENT")}).strict(),yt.extend({dateRangeType:f.literal("LAST")}).strict(),yt.extend({dateRangeType:f.literal("NEXT")}).strict(),yt.extend({dateRangeType:f.literal("TODATE")}).strict(),yt.extend({dateRangeType:f.literal("LASTN"),rangeN:f.number().int()}).strict(),yt.extend({dateRangeType:f.literal("NEXTN"),rangeN:f.number().int()}).strict()]),Wo=Ko.extend({filterType:f.literal("MATCH"),startsWith:f.string().optional(),endsWith:f.string().optional(),contains:f.string().optional(),exclude:f.boolean().optional()}),_d=f.union([Wo.extend({startsWith:f.string()}).strict(),Wo.extend({endsWith:f.string()}).strict(),Wo.extend({contains:f.string()}).strict()]),Wt=Qo.extend({filterType:f.literal("QUANTITATIVE_NUMERICAL")}),vd=f.discriminatedUnion("quantitativeFilterType",[Wt.extend({quantitativeFilterType:f.literal("RANGE"),min:f.number(),max:f.number(),includeNulls:f.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:f.literal("MIN"),min:f.number(),includeNulls:f.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:f.literal("MAX"),max:f.number(),includeNulls:f.boolean().optional()}).strict(),Wt.extend({quantitativeFilterType:f.literal("ONLY_NULL")}).strict(),Wt.extend({quantitativeFilterType:f.literal("ONLY_NON_NULL")}).strict()]),Ht=Qo.extend({filterType:f.literal("QUANTITATIVE_DATE")}),Cd=f.discriminatedUnion("quantitativeFilterType",[Ht.extend({quantitativeFilterType:f.literal("RANGE"),minDate:f.string(),maxDate:f.string(),includeNulls:f.boolean().optional()}).strict(),Ht.extend({quantitativeFilterType:f.literal("MIN"),minDate:f.string(),includeNulls:f.boolean().optional()}).strict(),Ht.extend({quantitativeFilterType:f.literal("MAX"),maxDate:f.string(),includeNulls:f.boolean().optional()}).strict(),Ht.extend({quantitativeFilterType:f.literal("ONLY_NULL")}).strict(),Ht.extend({quantitativeFilterType:f.literal("ONLY_NON_NULL")}).strict()]),Rd=Qo.extend({filterType:f.literal("TOP"),howMany:f.number().int(),fieldToMeasure:cn,direction:f.enum(["TOP","BOTTOM"]).optional().default("TOP")}),xd=f.union([Sd.strict(),Rd.strict(),..._d.options,...vd.options,...Cd.options,...Ed.options]),Id=f.object({parameterCaption:f.string(),value:Go}),Pd=f.object({connectionLuid:f.string().optional(),connectionUsername:f.string(),connectionPassword:f.string()}),un=f.object({datasourceLuid:f.string().nonempty(),connections:f.array(Pd).optional()}),Dd=f.enum(["OBJECTS","ARRAYS"]),dn=f.object({returnFormat:Dd,debug:f.boolean().default(!1)}).partial().passthrough(),kd=f.object({datasource:un,options:dn.optional()}).passthrough(),Ld=f.object({data:f.array(dd),extraData:f.object({parameters:f.array(pd)})}).partial().passthrough(),Md=f.object({errorCode:f.string(),message:f.string(),datetime:f.string().datetime({offset:!0}),debug:f.object({}).partial().passthrough(),"tab-error-code":f.string()}).partial().passthrough(),$t=f.strictObject({fields:f.array(bd),filters:f.array(xd).optional(),parameters:f.array(Id).optional()}),Od=dn.and(f.object({disaggregate:f.boolean()}).partial().passthrough()),Nd=f.object({datasource:un,query:$t,options:Od.optional()}).passthrough(),Ud=f.object({data:f.array(f.unknown())}).partial().passthrough(),Fd=Ho({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:Ud,errors:[{status:"default",schema:Md},{status:404,schema:f.any()}]}),qd=Ho({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.','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:kd}],response:Ld,errors:[{status:404,schema:f.any()}]}),jd=Ho({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:f.string()}),Vd=cd([Fd,qd,jd]),pn=[...Vd];var Gt=class extends H{constructor(e,r){super(new Bd(e,pn),r)}queryDatasource=async e=>{try{return fn(await this._apiClient.queryDatasource(e,{...this.authHeader}))}catch(r){if(mn(this._apiClient.api,"queryDatasource",r))return r.response.status===404?Pr("feature-disabled"):Pr(r.response.data);if(r instanceof zd)return Pr(r);throw r}};readMetadata=async e=>{try{return fn(await this._apiClient.readMetadata(e,{...this.authHeader}))}catch(r){if(mn(this._apiClient.api,"readMetadata",r)&&r.response.status===404)return Pr("feature-disabled");throw r}}};import{Zodios as Qd}from"@zodios/core";import{makeApi as Wd,makeEndpoint as hn}from"@zodios/core";import{z as Qe}from"zod";import{z as ee}from"zod";var Jo=ee.object({id:ee.string(),name:ee.string(),description:ee.string().optional(),webpageUrl:ee.string().optional(),contentUrl:ee.string(),project:ar.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(gt)}))});var Hd=hn({method:"get",path:"/sites/:siteId/workbooks/:workbookId",alias:"getWorkbook",description:"Returns information about the specified workbook, including information about views and tags.",response:Qe.object({workbook:Jo})}),$d=hn({method:"get",path:"/sites/:siteId/workbooks",alias:"queryWorkbooksForSite",description:"Returns the workbooks on a site.",parameters:[...ot,{name:"siteId",type:"Path",schema:Qe.string()},{name:"filter",type:"Query",schema:Qe.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:Qe.object({pagination:rt,workbooks:Qe.object({workbook:Qe.optional(Qe.array(Jo))})})}),Gd=Wd([$d,Hd]),gn=[...Gd];var Qt=class extends H{constructor(e,r){super(new Qd(e,gn),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 Le=class t{_creds;_host;_baseUrl;_baseUrlWithoutVersion;_authenticationMethods;_authenticatedAuthenticationMethods;_authenticatedServerMethods;_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 sr(this._baseUrl),this._addInterceptors(this._baseUrl,this._authenticationMethods.interceptors)),this._authenticationMethods}get authenticatedAuthenticationMethods(){return this._authenticatedAuthenticationMethods||(this._authenticatedAuthenticationMethods=new nr(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._authenticatedAuthenticationMethods.interceptors)),this._authenticatedAuthenticationMethods}get authenticatedServerMethods(){return this._authenticatedServerMethods||(this._authenticatedServerMethods=new Rr(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._authenticatedServerMethods.interceptors)),this._authenticatedServerMethods}get contentExplorationMethods(){return this._contentExplorationMethods||(this._contentExplorationMethods=new vt(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._contentExplorationMethods.interceptors)),this._contentExplorationMethods}get datasourcesMethods(){return this._datasourcesMethods||(this._datasourcesMethods=new Ct(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 Rt(e,this.creds),this._addInterceptors(e,this._metadataMethods.interceptors)}return this._metadataMethods}get pulseMethods(){return this._pulseMethods||(this._pulseMethods=new jt(this._baseUrlWithoutVersion,this.creds),this._addInterceptors(this._baseUrlWithoutVersion,this._pulseMethods.interceptors)),this._pulseMethods}get serverMethods(){return this._serverMethods||(this._serverMethods=new Cr(this._baseUrl),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 zt(this._baseUrl,this.creds),this._addInterceptors(this._baseUrl,this._viewsMethods.interceptors)),this._viewsMethods}get workbooksMethods(){return this._workbooksMethods||(this._workbooksMethods=new Qt(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,...or(o)}),o),o=>(this._requestInterceptor?.[1]?.(o,e),Promise.reject(o))),r.response.use(o=>(this._responseInterceptor?.[0]({baseUrl:e,...ir(o)}),o),o=>(this._responseInterceptor?.[1]?.(o,e),Promise.reject(o)))}};var Kd=async(t,e,r,o,i)=>{let n=t.server||i?.server;ce(n,"Tableau server could not be determined");let s=new Le(n,{requestInterceptor:[Jd(r,e),Yd(r,e)],responseInterceptor:[Zd(r,e),Xd(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:tp(t,i),clientId:t.connectedAppClientId,secretId:t.connectedAppSecretId,secretValue:t.connectedAppSecretValue,scopes:o,additionalPayload:rp(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},D=async({config:t,requestId:e,server:r,callback:o,jwtScopes:i,authInfo:n})=>{let s=await Kd(t,e,r,new Set(i),n);try{return await o(s)}finally{t.auth!=="oauth"&&await s.signOut()}},Jd=(t,e)=>r=>(r.headers["User-Agent"]=ep(t),yn(t,r,e),r),Yd=(t,e)=>(r,o)=>{if(!De(r)||!r.request){ue.error(t,`Request ${e} failed with error: ${V(r)}`,{logger:"rest-api",requestId:e});return}let{request:i}=r;yn(t,{baseUrl:o,...or(i)},e)},Zd=(t,e)=>r=>(bn(t,r,e),r),Xd=(t,e)=>(r,o)=>{if(!De(r)||!r.response){ue.error(t,`Response from request ${e} failed with error: ${V(r)}`,{logger:"rest-api",requestId:e});return}let{response:i}=r;bn(t,{baseUrl:o,...ir(i)},e)};function yn(t,e,r){let i=A().disableLogMasking?e:Pi(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(),...Ue("debug")&&{headers:i.headers,data:i.data,params:i.params}};ue.info(t,s,{logger:"rest-api",requestId:r})}function bn(t,e,r){let i=A().disableLogMasking?e:Di(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,...Ue("debug")&&{headers:i.headers,data:i.data}};ue.info(t,s,{logger:"rest-api",requestId:r})}function ep(t){let e=[Dr];if(t.clientInfo){let{name:r,version:o}=t.clientInfo;r&&e.push(o?`(${r} ${o})`:`(${r})`)}return e.join(" ")}function tp(t,e){return t.jwtSubClaim.replaceAll("{OAUTH_USERNAME}",e?.username??"")}function rp(t,e){let r=t.jwtAdditionalPayload.replaceAll("{OAUTH_USERNAME}",e?.username??"");return JSON.parse(r||"{}")}import{z as I}from"zod";import{z as op}from"zod";var z=t=>op.string({message:`${t} is required`}).nonempty({message:`${t} must be non-empty`});var Tn=I.object({client_id:z("client_id"),redirect_uri:z("redirect_uri"),response_type:z("response_type"),code_challenge:z("code_challenge"),code_challenge_method:z("code_challenge_method"),state:I.string().optional()}),wn=I.discriminatedUnion("grant_type",[I.object({grant_type:I.literal("authorization_code"),code:z("code"),redirect_uri:z("redirect_uri"),code_verifier:z("code_verifier")}),I.object({grant_type:I.literal("refresh_token"),refresh_token:z("refresh_token")}),I.object({grant_type:I.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(I.object({client_id:I.string().optional(),client_secret:I.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}}),An=I.object({code:I.string().optional(),state:I.string().optional(),error:I.string().optional()}),Yo=I.object({iss:z("iss"),aud:z("aud"),exp:I.number().int().nonnegative(),sub:z("sub"),clientId:z("clientId"),tableauServer:z("tableauServer"),tableauUserId:I.string().optional()}),Sn=Yo.extend({tableauAccessToken:z("tableauAccessToken"),tableauRefreshToken:z("tableauRefreshToken"),tableauExpiresAt:I.number().int().nonnegative(),tableauUserId:z("tableauUserId")}),kr=I.object({username:I.string(),userId:I.string(),server:I.string(),accessToken:I.string(),refreshToken:I.string()}).partial(),En=I.object({client_id:I.string(),redirect_uris:I.array(I.string().url()).min(1),client_name:I.string().optional(),logo_uri:I.string().url().optional(),client_uri:I.string().url().optional(),tos_uri:I.string().url().optional(),policy_uri:I.string().url().optional(),grant_types:I.array(I.string()).optional(),response_types:I.array(I.enum(["code","token"])).optional(),post_logout_redirect_uris:I.array(I.string().url()).optional(),scope:I.string().default("read").optional(),token_endpoint_auth_method:I.enum(["none","client_secret_basic","client_secret_post"]).optional()});var M=t=>{if(!t)return;let e=kr.safeParse(t.extra);if(e.success)return e.data};import{ZodiosError as _n}from"@zodios/core";import{fromError as ip,isZodErrorLike as sp}from"zod-validation-error";var ye=class t{_provider;constructor(e){this._provider=e}get(){return this._provider()}static async from(e){return e===void 0?void 0:e instanceof t?await e.get():e}};var N=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,this.paramsSchema=i,this.annotations=n,this.argsValidator=s,this.callback=a}logInvocation({requestId:e,args:r,username:o}){ue.debug(this.server,Ri({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 l=o?.extra?kr.safeParse(o.extra).data?.username:void 0;if(this.logInvocation({requestId:e,args:r,username:l}),r)try{(await ye.from(this.argsValidator))?.(r)}catch(c){return Lr(e,c)}try{let c=await i();if(c.isOk()){let u=await a(c.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 c.error instanceof _n?Lr(e,c.error):s?{isError:!0,content:[{type:"text",text:s(c.error)}]}:Lr(e,c.error)}catch(c){return Lr(e,c)}}};function Lr(t,e){if(e instanceof _n&&sp(e.cause)){let r=ip(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: ${V(e)}`}]}}function vn(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 Cn(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 Rn(t){let e=[];if(t.items)for(let o of t.items)e.push(np(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 np(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 xn({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 lp={terms:In.string().trim().nonempty().optional(),limit:In.number().int().min(1).max(2e3).default(100).optional(),orderBy:Ui.optional(),filter:ji.optional()},Pn=t=>{let e=new N({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:lp,annotations:{title:"Search Content",readOnlyHint:!0,openWorldHint:!1},callback:async({terms:r,limit:o,orderBy:i,filter:n},{requestId:s,authInfo:a})=>{let l=A(),c=i?vn(i):void 0,u=n?Cn(n):void 0;return await e.logAndExecute({requestId:s,authInfo:a,args:{},callback:async()=>new ap(await D({config:l,requestId:s,server:t,jwtScopes:["tableau:content:read"],authInfo:M(a),callback:async p=>{let g=await p.contentExplorationMethods.searchContent({terms:r,page:0,limit:l.maxResultLimit?Math.min(l.maxResultLimit,o??100):o??100,orderBy:c,filter:u});return Rn(g)}})),constrainSuccessResult:p=>xn({items:p,boundedContext:l.boundedContext})})}});return e};import{Err as Ln,Ok as Xo}from"ts-results-es";import{z as dp}from"zod";function Mr(){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 Kt=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=A().boundedContext.projectIds),this._allowedProjectIds}get allowedDatasourceIds(){return this._allowedDatasourceIds===void 0&&(this._allowedDatasourceIds=A().boundedContext.datasourceIds),this._allowedDatasourceIds}get allowedWorkbookIds(){return this._allowedWorkbookIds===void 0&&(this._allowedWorkbookIds=A().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 D({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:`,V(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 D({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:`,V(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 l=await D({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async c=>await c.viewsMethods.getView({siteId:c.siteId,viewId:e})});if(s=l.workbook?.id??"",a=l.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(l){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:`,V(l)].join(" ")}}if(this.allowedProjectIds)try{if(a=a||await D({config:r,requestId:o,server:i,jwtScopes:["tableau:content:read"],callback:async l=>(await l.viewsMethods.getView({siteId:l.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(l){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:`,V(l)].join(" ")}}return{allowed:!0}}},be=Kt.create(),LS={createResourceAccessChecker:Kt.createForTesting,resetResourceAccessCheckerSingleton:()=>{be=Kt.create()}};function Or({datasourceLuid:t}){if(!t)throw new Error("datasourceLuid must be a non-empty string.")}import{z as R}from"zod";var cp=R.object({name:R.string(),columnClass:R.string(),dataType:R.string().nullable(),defaultAggregation:R.string().nullable(),description:R.string().nullable(),descriptionInherited:R.array(R.object({attribute:R.string(),value:R.string().nullable()}).nullable()).nullable(),dataCategory:R.string().nullable(),role:R.string().nullable(),defaultFormat:R.string().nullable(),semanticRole:R.string().nullable(),aggregation:R.string().nullable(),aggregationParam:R.string().nullable(),formula:R.string().nullable(),isAutoGenerated:R.boolean().nullable(),hasUserReference:R.boolean().nullable(),binSize:R.number().nullable()}).partial(),up=R.object({name:R.string(),parameterType:R.string(),dataType:R.string().nullable(),value:R.union([R.number(),R.string(),R.boolean(),R.null()]),members:R.array(R.union([R.number(),R.string(),R.boolean(),R.null()])),min:R.number().nullable(),max:R.number().nullable(),step:R.number().nullable(),minDate:R.string().nullable(),maxDate:R.string().nullable(),periodValue:R.number().nullable(),periodType:R.string().nullable()}).partial(),US=R.object({fields:R.array(cp),parameters:R.array(up)});function Zo(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 kn(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),Dn(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&&Dn(i,o)}return r}function Dn(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 pp=t=>`
|
|
18
18
|
query datasourceFieldInfo {
|
|
19
19
|
publishedDatasources(filter: { luid: "${t}" }) {
|
|
20
20
|
name
|
|
@@ -75,11 +75,12 @@ var pa=Object.defineProperty;var ma=(t,e)=>{for(var r in e)pa(t,r,{get:e[r],enum
|
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
|
-
}`,
|
|
79
|
-
This tool retrieves
|
|
80
|
-
The
|
|
78
|
+
}`,mp={datasourceLuid:dp.string().nonempty()},Mn=t=>{let e=new N({server:t,name:"get-datasource-metadata",description:`
|
|
79
|
+
This tool retrieves 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
|
+
The metadata provided by this tool consists of the fields and parameters that belong to the datasource.
|
|
81
|
+
Fields will contain properties such as name and dataType, but may also expose richer context such as descriptions, dataCategories, roles, etc.
|
|
81
82
|
This tool should be used for getting the metadata to ground the use of a tool that queries Tableau published data sources.
|
|
82
|
-
`,paramsSchema:
|
|
83
|
+
`,paramsSchema:mp,annotations:{title:"Get Datasource Metadata",readOnlyHint:!0,openWorldHint:!1},argsValidator:Or,callback:async({datasourceLuid:r},{requestId:o,authInfo:i})=>{let n=A(),s=pp(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 D({config:n,requestId:o,server:t,jwtScopes:["tableau:content:read","tableau:viz_data_service:read"],authInfo:M(i),callback:async l=>{let c=await l.vizqlDataServiceMethods.readMetadata({datasource:{datasourceLuid:r}});if(c.isErr())return Ln({type:"feature-disabled"});if(n.disableMetadataApiRequests)return Xo(Zo(c.value));let u;try{u=await l.metadataMethods.graphql(s)}catch{return Xo(Zo(c.value))}return Xo(kn(c.value,u))}}):new Ln({type:"datasource-not-allowed",message:a.message})},constrainSuccessResult:a=>({type:"success",result:a}),getErrorText:a=>{switch(a.type){case"feature-disabled":return Mr();case"datasource-not-allowed":return a.message}}})}});return e};import{Ok as Ap}from"ts-results-es";import{z as ti}from"zod";import{Ok as fp}from"ts-results-es";import{z as Ke}from"zod";var hp=Ke.object({pageSize:Ke.coerce.number().gt(0),pageNumber:Ke.coerce.number().gt(0),limit:Ke.coerce.number().gt(0)}).partial();async function bt({pageConfig:t,getDataFn:e}){let{pageSize:r,limit:o}=hp.parse(t),{pagination:i,data:n}=await e(t),s=[...n],{totalAvailable:a,pageNumber:l}=i;for(;a>s.length&&(!o||o>s.length);){let{pagination:c,data:u}=await e({pageSize:r,pageNumber:l+1,limit:o});if(u.length===0)throw new Error(`No more data available. Last fetched page number: ${l}, Total available: ${a}, Total fetched: ${s.length}`);({totalAvailable:a,pageNumber:l}=c),s.push(...u)}return o&&o<s.length&&(s.length=o),s}var gp=Ke.object({limit:Ke.coerce.number().gt(0).optional(),pageSize:Ke.coerce.number().gt(0).optional()}).optional();async function On({config:t,getDataFn:e}){let r=gp.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,l=[...a],c=s.total_available,u=s.next_page_token;for(!i&&c&&(i=Math.min(c-l.length,o?o-l.length:Number.MAX_SAFE_INTEGER));u&&(!o||o>l.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: ${l.length}`);({next_page_token:u}=g),l.push(...b)}return o&&o<l.length&&(l.length=o),new fp(l)}var Tt="**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 ei}from"zod";import yp from"zod";var Je=yp.enum(["eq","in","gt","gte","lt","lte"]);function bp(t){return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(t)}var Tp=["createdAt","updatedAt"];function wt({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,l,...c]=s.split(":");if(!a||!l||c.length===0)throw new Error(`Invalid filter expression format: "${s}"`);let u=c.join(":"),p=r.parse(a),g=Je.parse(l);if(!o(p,g))throw new Error(`Operator '${g}' is not allowed for field '${p}'. Allowed operators: ${e[p].join(", ")}`);if(Tp.includes(p)&&!bp(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 Nn=ei.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"]),wp={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"]},nE=ei.object({field:Nn,operator:Je,value:ei.string()});function Un(t){return wt({filterString:t,allowedOperatorsByField:wp,filterFieldSchema:Nn})}var Sp={filter:ti.string().optional(),pageSize:ti.number().gt(0).optional(),limit:ti.number().gt(0).optional()},Fn=t=>{let e=new N({server:t,name:"list-datasources",description:`
|
|
83
84
|
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
85
|
|
|
85
86
|
**Supported Filter Fields and Operators**
|
|
@@ -116,7 +117,7 @@ var pa=Object.defineProperty;var ma=(t,e)=>{for(var r in e)pa(t,r,{get:e[r],enum
|
|
|
116
117
|
| type | eq |
|
|
117
118
|
| updatedAt | eq, gt, gte, lt, lte |
|
|
118
119
|
|
|
119
|
-
${
|
|
120
|
+
${Tt}
|
|
120
121
|
|
|
121
122
|
**Example Usage:**
|
|
122
123
|
- List all data sources on a site
|
|
@@ -128,7 +129,7 @@ var pa=Object.defineProperty;var ma=(t,e)=>{for(var r in e)pa(t,r,{get:e[r],enum
|
|
|
128
129
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
129
130
|
- List data sources with the name "Project Views" in the "Finance" project and created after January 1, 2023:
|
|
130
131
|
filter: "name:eq:Project Views,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"
|
|
131
|
-
`,paramsSchema:
|
|
132
|
+
`,paramsSchema:Sp,annotations:{title:"List Datasources",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=A(),l=r?Un(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{filter:r,pageSize:o,limit:i},callback:async()=>{let c=await D({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:M(s),callback:async u=>await bt({pageConfig:{pageSize:o,limit:a.maxResultLimit?Math.min(a.maxResultLimit,i??Number.MAX_SAFE_INTEGER):i},getDataFn:async g=>{let{pagination:b,datasources:m}=await u.datasourcesMethods.listDatasources({siteId:u.siteId,filter:l??"",pageSize:g.pageSize,pageNumber:g.pageNumber});return{pagination:b,data:m}}})});return new Ap(c)},constrainSuccessResult:c=>Ep({datasources:c,boundedContext:a.boundedContext})})}});return e};function Ep({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 qn}from"ts-results-es";import jn 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 _p={bundleRequest:_r,bundleType:jn.optional(jn.enum(vr))},Vn=t=>{let e=new N({server:t,name:"generate-pulse-metric-value-insight-bundle",description:`
|
|
132
133
|
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
134
|
|
|
134
135
|
**Parameters:**
|
|
@@ -235,7 +236,7 @@ Generate an insight bundle for the current aggregated value for Pulse Metric usi
|
|
|
235
236
|
- Generate the detail insight bundle for the Pulse metric:
|
|
236
237
|
bundleType: 'detail',
|
|
237
238
|
bundleRequest: (See default example above)
|
|
238
|
-
`,paramsSchema:
|
|
239
|
+
`,paramsSchema:_p,annotations:{title:"Generate Pulse Metric Value Insight Bundle",readOnlyHint:!0,openWorldHint:!1},callback:async({bundleRequest:r,bundleType:o},{requestId:i,authInfo:n})=>{let s=A();return await e.logAndExecute({requestId:i,authInfo:n,args:{bundleRequest:r,bundleType:o},callback:async()=>{let{datasourceIds:a}=s.boundedContext;if(a){let c=r.bundle_request.input.metric.definition.datasource.id;if(!a.has(c))return new qn({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 ${c}, which is not in the allowed set of data sources.`].join(" ")})}let l=await D({config:s,requestId:i,server:t,jwtScopes:["tableau:insights:read"],authInfo:M(n),callback:async c=>await c.pulseMethods.generatePulseMetricValueInsightBundle(r,o??"ban")});return l.isErr()?new qn({type:"feature-disabled",reason:l.error}):l},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 vp}from"ts-results-es";import{z as Ur}from"zod";function Nr({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 Cp={view:Ur.optional(Ur.enum(Ge)),limit:Ur.coerce.number().gt(0).optional(),pageSize:Ur.coerce.number().gt(0).optional()},Bn=t=>{let e=new N({server:t,name:"list-all-pulse-metric-definitions",description:`
|
|
239
240
|
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
241
|
|
|
241
242
|
**Parameters:**
|
|
@@ -243,11 +244,15 @@ Retrieves a list of all published Pulse Metric Definitions using the Tableau RES
|
|
|
243
244
|
- \`DEFINITION_VIEW_BASIC\` - Return only the specified metric definition.
|
|
244
245
|
- \`DEFINITION_VIEW_FULL\` - Return the metric definition and the specified number of metrics.
|
|
245
246
|
- \`DEFINITION_VIEW_DEFAULT\` - Return the metric definition and the default metric.
|
|
247
|
+
- \`limit\` (optional): Maximum number of metric definitions to return. If not specified, all definitions are returned.
|
|
248
|
+
- \`pageSize\` (optional): Number of results per page. Controls how many definitions are fetched in each API request during pagination.
|
|
246
249
|
|
|
247
250
|
**Example Usage:**
|
|
248
251
|
- List all Pulse Metric Definitions on the current site
|
|
249
252
|
- List all Pulse Metric Definitions on the current site with the default view:
|
|
250
253
|
view: 'DEFINITION_VIEW_DEFAULT'
|
|
254
|
+
- List the first 50 Pulse Metric Definitions:
|
|
255
|
+
limit: 50
|
|
251
256
|
- List all Pulse Metric Definitions on the current site with the full view:
|
|
252
257
|
view: 'DEFINITION_VIEW_FULL'
|
|
253
258
|
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 +261,7 @@ Retrieves a list of all published Pulse Metric Definitions using the Tableau RES
|
|
|
256
261
|
- See all metrics for my Pulse Metric Definitions:
|
|
257
262
|
view: 'DEFINITION_VIEW_FULL'
|
|
258
263
|
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:
|
|
264
|
+
`,paramsSchema:Cp,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=A();return await e.logAndExecute({requestId:n,authInfo:s,args:{view:r,limit:o,pageSize:i},callback:async()=>await D({config:a,requestId:n,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:M(s),callback:async l=>await On({config:{limit:a.maxResultLimit?Math.min(a.maxResultLimit,o??Number.MAX_SAFE_INTEGER):o,pageSize:i},getDataFn:async(u,p)=>{let g=await l.pulseMethods.listAllPulseMetricDefinitions(r,u,p);return g.isOk()?new vp({pagination:g.value.pagination,data:g.value.definitions}):g}})}),constrainSuccessResult:l=>Nr({definitions:l,boundedContext:a.boundedContext}),getErrorText:de})}});return e};import{z as Fr}from"zod";var Rp={metricDefinitionIds:Fr.array(Fr.string().length(36)).min(1),view:Fr.optional(Fr.enum(Ge))},zn=t=>{let e=new N({server:t,name:"list-pulse-metric-definitions-from-definition-ids",description:`
|
|
260
265
|
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
266
|
|
|
262
267
|
**Parameters:**
|
|
@@ -285,7 +290,7 @@ Retrieves a list of specific Pulse Metric Definitions using the Tableau REST API
|
|
|
285
290
|
metricDefinitionIds: ['BBC908D8-29ED-48AB-A78E-ACF8A424C8C3', 'BBC908D8-29ED-48AB-A78E-ACF8A424C8C4'],
|
|
286
291
|
view: 'DEFINITION_VIEW_FULL'
|
|
287
292
|
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:
|
|
293
|
+
`,paramsSchema:Rp,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=A();return await e.logAndExecute({requestId:i,authInfo:n,args:{metricDefinitionIds:o,view:r},callback:async()=>await D({config:s,requestId:i,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:M(n),callback:async a=>await a.pulseMethods.listPulseMetricDefinitionsFromMetricDefinitionIds(o,r)}),constrainSuccessResult:a=>Nr({definitions:a,boundedContext:s.boundedContext}),getErrorText:de})}});return e};import{z as xp}from"zod";function qr({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 Ip={pulseMetricDefinitionID:xp.string().length(36)},Wn=t=>{let e=new N({server:t,name:"list-pulse-metrics-from-metric-definition-id",description:`
|
|
289
294
|
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
295
|
|
|
291
296
|
**Parameters:**
|
|
@@ -293,7 +298,7 @@ Retrieves a list of published Pulse Metrics from a Pulse Metric Definition using
|
|
|
293
298
|
|
|
294
299
|
**Example Usage:**
|
|
295
300
|
- List all Pulse Metrics for this Pulse Metric Definition
|
|
296
|
-
`,paramsSchema:
|
|
301
|
+
`,paramsSchema:Ip,annotations:{title:"List Pulse Metrics from Metric Definition ID",readOnlyHint:!0,openWorldHint:!1},callback:async({pulseMetricDefinitionID:r},{requestId:o,authInfo:i})=>{let n=A();return await e.logAndExecute({requestId:o,authInfo:i,args:{pulseMetricDefinitionID:r},callback:async()=>await D({config:n,requestId:o,server:t,jwtScopes:["tableau:insight_definitions_metrics:read"],authInfo:M(i),callback:async s=>await s.pulseMethods.listPulseMetricsFromMetricDefinitionId(r)}),constrainSuccessResult:s=>qr({metrics:s,boundedContext:n.boundedContext}),getErrorText:de})}});return e};import{z as Hn}from"zod";var Pp={metricIds:Hn.array(Hn.string().length(36))},$n=t=>{let e=new N({server:t,name:"list-pulse-metrics-from-metric-ids",description:`
|
|
297
302
|
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
303
|
|
|
299
304
|
**Parameters:**
|
|
@@ -307,7 +312,7 @@ Retrieves a list of published Pulse Metrics from a list of metric IDs using the
|
|
|
307
312
|
- This tool is recommended for use with data in Pulse Metric Subscriptions.
|
|
308
313
|
- 00000000-0000-0000-0000-000000000000 is not a valid datasource id.
|
|
309
314
|
- 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:
|
|
315
|
+
`,paramsSchema:Pp,annotations:{title:"List Pulse Metrics from Metric IDs",readOnlyHint:!0,openWorldHint:!1},callback:async({metricIds:r},{requestId:o,authInfo:i})=>{let n=A();return await e.logAndExecute({requestId:o,authInfo:i,args:{metricIds:r},callback:async()=>await D({config:n,requestId:o,server:t,jwtScopes:["tableau:insight_metrics:read"],authInfo:M(i),callback:async s=>await s.pulseMethods.listPulseMetricsFromMetricIds(r)}),constrainSuccessResult:s=>qr({metrics:s,boundedContext:n.boundedContext}),getErrorText:de})}});return e};var Dp={},Gn=t=>{let e=new N({server:t,name:"list-pulse-metric-subscriptions",description:`
|
|
311
316
|
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
317
|
|
|
313
318
|
**Example Usage:**
|
|
@@ -318,13 +323,14 @@ Retrieves a list of published Pulse Metric Subscriptions for the current user us
|
|
|
318
323
|
- 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
324
|
1. Retrieve Pulse Metrics from the metric ids returned in the Pulse Metric Subscriptions.
|
|
320
325
|
2. Retrieve Pulse Metric Definitions from the metric definition id returned in the Pulse Metrics.
|
|
321
|
-
`,paramsSchema:Ld,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:M(i),callback:async s=>await s.pulseMethods.listPulseMetricSubscriptionsForCurrentUser()}),constrainSuccessResult:async s=>await Od({subscriptions:s,boundedContext:n.boundedContext,restApiArgs:{config:n,requestId:o,server:t}}),getErrorText:pe})}});return e};async function Od({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(c=>c.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 d=new Set(a.value.filter(l=>o.has(l.datasource_luid)).map(l=>l.id));return t=t.filter(l=>d.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 zd}from"@zodios/core";import{Err as jo}from"ts-results-es";import{z as Wd}from"zod";import{z as $e}from"zod";var Md=$e.record($e.string().nonempty(),$e.array($e.object({luid:$e.string().optional(),u:$e.string().nonempty(),p:$e.string().nonempty()}).transform(({luid:t,u:e,p:r})=>({connectionLuid:t,connectionUsername:e,connectionPassword:r})))),_n,Sn=!1,Cn=t=>{if(!Sn){Sn=!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=Md.parse(r);_n=new Map(Object.entries(o))}return _n?.get(t)};function vn(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 Rn(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(Nd))throw new Error("The query must not include any fields with an empty fieldCaption.");{let e=t.reduce((o,i)=>(o[i.fieldCaption]||(o[i.fieldCaption]=0),o[i.fieldCaption]++,o),{}),r=Object.entries(e).filter(([o,i])=>i>1);if(r.length>0)throw new Error(`The query must not include duplicate fields. The following fields are duplicated: ${r.map(([o])=>o).join(", ")}.`)}{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(Fo).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(Fd).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 Nd(t){return!t.fieldCaption}function Fo(t){return!!("function"in t&&t.function&&"calculation"in t&&t.calculation)}function xn(t){return!!("fieldCaption"in t&&t.fieldCaption&&"calculation"in t&&t.calculation)}function Fd(t){return t.maxDecimalPlaces!==void 0&&t.maxDecimalPlaces<0}import{Err as Uo,Ok as Ud}from"ts-results-es";function kn(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=In(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=In(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 In(t){if(qd(t))return new Uo("The fieldCaption property must be a non-empty string.");if(xn(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new Uo(`The field ${e} must not contain both a fieldCaption and a calculation.`.replace(" "," "))}if(Fo(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new Uo(`The field ${e} must not contain both a function and a calculation.`.replace(" "," "))}return Ud.EMPTY}function qd(t){return"fieldCaption"in t&&!t.fieldCaption}function Dn({datasourceLuid:t,query:e}){Sr({datasourceLuid:t});let{fields:r,filters:o}=e;if(Rn(r),kn(o),!qt.safeParse(e).success)throw new Error("The query does not match the expected schema.")}var Pn=`# Query Tableau Data Source Tool
|
|
326
|
+
`,paramsSchema:Dp,annotations:{title:"List Pulse Metric Subscriptions for Current User",readOnlyHint:!0,openWorldHint:!1},callback:async(r,{requestId:o,authInfo:i})=>{let n=A();return await e.logAndExecute({requestId:o,authInfo:i,args:{},callback:async()=>await D({config:n,requestId:o,server:t,jwtScopes:["tableau:metric_subscriptions:read"],authInfo:M(i),callback:async s=>await s.pulseMethods.listPulseMetricSubscriptionsForCurrentUser()}),constrainSuccessResult:async s=>await kp({subscriptions:s,boundedContext:n.boundedContext,restApiArgs:{config:n,requestId:o,server:t}}),getErrorText:de})}});return e};async function kp({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 D({config:i,requestId:n,server:s,jwtScopes:["tableau:insight_metrics:read"],callback:async c=>await c.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.",V(a.error)].join(" ")};let l=new Set(a.value.filter(c=>o.has(c.datasource_luid)).map(c=>c.id));return t=t.filter(c=>l.has(c.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.",V(a)].join(" ")}}}import{ZodiosError as Kp}from"@zodios/core";import{Err as Vr}from"ts-results-es";import{z as Jp}from"zod";import{ZodiosError as Lp}from"@zodios/core";import{fromError as Mp,isZodErrorLike as Op}from"zod-validation-error";var At=class extends Map{timeouts;expirationTimeMs;constructor({defaultExpirationTimeMs:e}){if(super(),e<=0)throw new Error("Expiration time must be greater than 0");if(e>2**31-1)throw new Error(`Expiration time must be at most ${2**31-1}`);this.timeouts=new Map,this.expirationTimeMs=e}get defaultExpirationTimeMs(){return this.expirationTimeMs}set=(e,r,o=this.expirationTimeMs)=>{if(o<=0)throw new Error("Expiration time must be greater than 0");if(o>2**31-1)throw new Error(`Expiration time must be at most ${2**31-1}`);let i=this.timeouts.get(e);i&&clearTimeout(i),super.set(e,r);let n=setTimeout(()=>{this.delete(e)},o);return this.timeouts.set(e,n),this};delete=e=>{let r=this.timeouts.get(e);return r&&(clearTimeout(r),this.timeouts.delete(e)),super.delete(e)};clear=()=>{this.timeouts.forEach(e=>clearTimeout(e)),this.timeouts.clear(),super.clear()};[Symbol.dispose](){this.clear()}};var jr,Qn=async t=>{if(!t)throw new Error("server cannot be empty");jr||(jr=new At({defaultExpirationTimeMs:A().tableauServerVersionCheckIntervalInHours*60*60*1e3}));let e=jr.get(t);if(e)return e;let r=new Le(t);try{let o=(await r.serverMethods.getServerInfo()).productVersion;return jr.set(t,o),o}catch(o){let i=o instanceof Lp&&Op(o.cause)?Mp(o.cause).toString():V(o);throw new Error(`Failed to get server version: ${i}`)}};async function Kn({server:t,mappings:e}){let r=await Qn(t);for(let[o,i]of Object.entries(e))if(Np({productVersion:r,minVersion:o}))return i;return e.default}function Np({productVersion:t,minVersion:e}){let{value:r}=t;if(r==="main")return!0;let[o,i,n]=r.split(".").map(Number);if([o,i,n].some(isNaN))return!0;let[s,a,l]=e.split(".").map(Number);return o>s||o===s&&i>a||o===s&&i===a&&n>=l}import{z as Ye}from"zod";var Up=Ye.record(Ye.string().nonempty(),Ye.array(Ye.object({luid:Ye.string().optional(),u:Ye.string().nonempty(),p:Ye.string().nonempty()}).transform(({luid:t,u:e,p:r})=>({connectionLuid:t,connectionUsername:e,connectionPassword:r})))),Jn,Yn=!1,Zn=t=>{if(!Yn){Yn=!0;let{datasourceCredentials:e}=A();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=Up.parse(r);Jn=new Map(Object.entries(o))}return Jn?.get(t)};function Xn(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 ea(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(Fp))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(ri).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(qp).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 Fp(t){return!t.fieldCaption}function ri(t){return!!("function"in t&&t.function&&"calculation"in t&&t.calculation)}function ta(t){return!!("fieldCaption"in t&&t.fieldCaption&&"calculation"in t&&t.calculation)}function qp(t){return t.maxDecimalPlaces!==void 0&&t.maxDecimalPlaces<0}import{Err as oi,Ok as jp}from"ts-results-es";function oa(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=ra(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=ra(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 ra(t){if(Vp(t))return new oi("The fieldCaption property must be a non-empty string.");if(ta(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new oi(`The field ${e} must not contain both a fieldCaption and a calculation.`.replace(" "," "))}if(ri(t)){let e="fieldCaption"in t?`"${t.fieldCaption}" `:"";return new oi(`The field ${e} must not contain both a function and a calculation.`.replace(" "," "))}return jp.EMPTY}function Vp(t){return"fieldCaption"in t&&!t.fieldCaption}function ia({datasourceLuid:t,query:e}){Or({datasourceLuid:t});let{fields:r,filters:o}=e;if(ea(r),oa(o),!$t.safeParse(e).success)throw new Error("The query does not match the expected schema.")}var sa=`# Query Tableau Data Source Tool
|
|
322
327
|
|
|
323
328
|
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
329
|
|
|
325
330
|
## Prerequisites
|
|
326
331
|
Before using this tool, you should:
|
|
327
332
|
1. Understand available fields and their types
|
|
333
|
+
2. Understand what parameters are available and their types
|
|
328
334
|
3. Understand the data structure and field relationships
|
|
329
335
|
|
|
330
336
|
## Best Practices
|
|
@@ -350,8 +356,52 @@ Before using this tool, you should:
|
|
|
350
356
|
### Field Usage Guidelines
|
|
351
357
|
- **Prefer existing fields** - Use fields already modeled in the data source rather than creating custom calculations
|
|
352
358
|
- **Use calculations sparingly** - Only create calculated fields when absolutely necessary and the calculation cannot be achieved through existing fields and aggregations
|
|
359
|
+
- **Use bins for distribution analysis** - Create bins to group continuous data into discrete ranges (e.g., age groups, price ranges)
|
|
353
360
|
- **Validate field availability** - Always check field metadata before constructing queries
|
|
354
361
|
|
|
362
|
+
### Field Types
|
|
363
|
+
|
|
364
|
+
#### Dimension Fields
|
|
365
|
+
Basic fields without aggregation:
|
|
366
|
+
\`\`\`json
|
|
367
|
+
{
|
|
368
|
+
"fieldCaption": "Category",
|
|
369
|
+
"fieldAlias": "Product Category"
|
|
370
|
+
}
|
|
371
|
+
\`\`\`
|
|
372
|
+
|
|
373
|
+
#### Measure Fields
|
|
374
|
+
Fields with aggregation functions (SUM, AVG, COUNT, etc.):
|
|
375
|
+
\`\`\`json
|
|
376
|
+
{
|
|
377
|
+
"fieldCaption": "Sales",
|
|
378
|
+
"function": "SUM",
|
|
379
|
+
"fieldAlias": "Total Sales",
|
|
380
|
+
"maxDecimalPlaces": 2
|
|
381
|
+
}
|
|
382
|
+
\`\`\`
|
|
383
|
+
|
|
384
|
+
#### Calculated Fields
|
|
385
|
+
Custom fields defined using Tableau calculation syntax:
|
|
386
|
+
\`\`\`json
|
|
387
|
+
{
|
|
388
|
+
"fieldCaption": "Profit Margin",
|
|
389
|
+
"calculation": "SUM([Profit]) / SUM([Sales])",
|
|
390
|
+
"fieldAlias": "Margin %"
|
|
391
|
+
}
|
|
392
|
+
\`\`\`
|
|
393
|
+
|
|
394
|
+
#### Bin Fields
|
|
395
|
+
Group continuous data into discrete ranges:
|
|
396
|
+
\`\`\`json
|
|
397
|
+
{
|
|
398
|
+
"fieldCaption": "Sales",
|
|
399
|
+
"binSize": 1000,
|
|
400
|
+
"fieldAlias": "Sales Range"
|
|
401
|
+
}
|
|
402
|
+
\`\`\`
|
|
403
|
+
This creates bins of $1,000 intervals (0-1000, 1000-2000, etc.)
|
|
404
|
+
|
|
355
405
|
### Query Construction
|
|
356
406
|
- **Group by meaningful dimensions** - Ensure grouping supports the business question being asked
|
|
357
407
|
- **Order results logically** - Use sortDirection and sortPriority to present data in a meaningful way
|
|
@@ -394,6 +444,107 @@ When a query might return large amounts of data, follow this profiling approach:
|
|
|
394
444
|
|
|
395
445
|
**Step 3: Apply appropriate aggregation or filtering based on counts**
|
|
396
446
|
|
|
447
|
+
## Parameters
|
|
448
|
+
|
|
449
|
+
Parameters are dynamic values defined in the Tableau datasource that can be used to control calculations, filters, and query behavior. They allow for interactive, user-controlled queries without modifying the query structure.
|
|
450
|
+
|
|
451
|
+
### When to Use Parameters
|
|
452
|
+
- **Dynamic filtering** - Let users control date ranges, regions, or categories
|
|
453
|
+
- **What-if analysis** - Adjust values like growth rates, targets, or thresholds
|
|
454
|
+
- **Calculation control** - Switch between different metrics or calculation methods
|
|
455
|
+
- **User preferences** - Currency selection, display units, or other settings
|
|
456
|
+
|
|
457
|
+
### Parameter Types
|
|
458
|
+
- **LIST** - Predefined values (e.g., regions, categories)
|
|
459
|
+
- **ANY_VALUE** - Free-form values matching data type
|
|
460
|
+
- **QUANTITATIVE_RANGE** - Numeric values with optional min/max/step
|
|
461
|
+
- **QUANTITATIVE_DATE** - Date values with optional range constraints
|
|
462
|
+
|
|
463
|
+
### Usage Example
|
|
464
|
+
\`\`\`json
|
|
465
|
+
{
|
|
466
|
+
"datasourceLuid": "abc123",
|
|
467
|
+
"query": {
|
|
468
|
+
"fields": [...],
|
|
469
|
+
"filters": [...],
|
|
470
|
+
"parameters": [
|
|
471
|
+
{
|
|
472
|
+
"name": "Selected Year",
|
|
473
|
+
"value": 2024
|
|
474
|
+
},
|
|
475
|
+
{
|
|
476
|
+
"name": "Currency",
|
|
477
|
+
"value": "USD"
|
|
478
|
+
}
|
|
479
|
+
]
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
\`\`\`
|
|
483
|
+
|
|
484
|
+
- Parameters affect entire query; filters restrict returned data
|
|
485
|
+
|
|
486
|
+
## Bins
|
|
487
|
+
|
|
488
|
+
Bins group continuous numerical data into discrete ranges, enabling distribution analysis and histogram creation. Unlike parameters and filters, bins are created dynamically in the query.
|
|
489
|
+
|
|
490
|
+
### Creating Bin Fields
|
|
491
|
+
|
|
492
|
+
To create a bin field in a query, you **must** include:
|
|
493
|
+
1. A **measure field** with the base field and aggregation function
|
|
494
|
+
2. A **bin field** with the same fieldCaption and a binSize property
|
|
495
|
+
|
|
496
|
+
**Example:**
|
|
497
|
+
\`\`\`json
|
|
498
|
+
{
|
|
499
|
+
"fields": [
|
|
500
|
+
{
|
|
501
|
+
"fieldCaption": "Sales",
|
|
502
|
+
"function": "SUM",
|
|
503
|
+
"fieldAlias": "Total Sales"
|
|
504
|
+
},
|
|
505
|
+
{
|
|
506
|
+
"fieldCaption": "Sales",
|
|
507
|
+
"binSize": 1000,
|
|
508
|
+
"fieldAlias": "Sales Range"
|
|
509
|
+
}
|
|
510
|
+
]
|
|
511
|
+
}
|
|
512
|
+
\`\`\`
|
|
513
|
+
|
|
514
|
+
This creates bins of $1,000 intervals (0-1000, 1000-2000, etc.)
|
|
515
|
+
|
|
516
|
+
### When to Use Bins
|
|
517
|
+
- Analyzing distribution patterns (age groups, price ranges, score brackets)
|
|
518
|
+
- Creating histograms or frequency distributions
|
|
519
|
+
- Grouping continuous numerical data into meaningful categories
|
|
520
|
+
- User asks questions like "How many customers in each age range?" or "What's the distribution of order sizes?"
|
|
521
|
+
|
|
522
|
+
### Bin Restrictions
|
|
523
|
+
- **Cannot override existing bin fields** - If a bin field already exists in the datasource, query it without binSize
|
|
524
|
+
- **binSize must be positive** - Only values > 0 are allowed
|
|
525
|
+
- **Measure fields only** - Can only bin numeric/quantitative fields
|
|
526
|
+
- **Choose appropriate bin sizes** - Consider your data range (e.g., bin size 100 for values 0-10,000)
|
|
527
|
+
|
|
528
|
+
### Querying Existing Bin Fields
|
|
529
|
+
|
|
530
|
+
If a bin field already exists in the datasource (e.g., "Profit (bin)"), query it as a regular dimension field:
|
|
531
|
+
|
|
532
|
+
\`\`\`json
|
|
533
|
+
{
|
|
534
|
+
"fields": [
|
|
535
|
+
{
|
|
536
|
+
"fieldCaption": "Profit (bin)"
|
|
537
|
+
},
|
|
538
|
+
{
|
|
539
|
+
"fieldCaption": "Profit",
|
|
540
|
+
"function": "SUM"
|
|
541
|
+
}
|
|
542
|
+
]
|
|
543
|
+
}
|
|
544
|
+
\`\`\`
|
|
545
|
+
|
|
546
|
+
To control existing bin field behavior, use parameters if available (e.g., "Profit Bin Size").
|
|
547
|
+
|
|
397
548
|
## Filter Types and Usage
|
|
398
549
|
|
|
399
550
|
### SET Filters
|
|
@@ -607,6 +758,69 @@ Filter relative date periods:
|
|
|
607
758
|
}
|
|
608
759
|
\`\`\`
|
|
609
760
|
|
|
761
|
+
### Example 5: Distribution Analysis Using Bins
|
|
762
|
+
**Question:** "How are our sales distributed across different price ranges?"
|
|
763
|
+
|
|
764
|
+
\`\`\`json
|
|
765
|
+
{
|
|
766
|
+
"datasourceLuid": "abc123",
|
|
767
|
+
"query": {
|
|
768
|
+
"fields": [
|
|
769
|
+
{
|
|
770
|
+
"fieldCaption": "Sales",
|
|
771
|
+
"binSize": 1000,
|
|
772
|
+
"fieldAlias": "Sales Range",
|
|
773
|
+
"sortDirection": "ASC",
|
|
774
|
+
"sortPriority": 1
|
|
775
|
+
},
|
|
776
|
+
{
|
|
777
|
+
"fieldCaption": "Order ID",
|
|
778
|
+
"function": "COUNT",
|
|
779
|
+
"fieldAlias": "Number of Orders"
|
|
780
|
+
},
|
|
781
|
+
{
|
|
782
|
+
"fieldCaption": "Sales",
|
|
783
|
+
"function": "SUM",
|
|
784
|
+
"fieldAlias": "Total Sales in Range"
|
|
785
|
+
}
|
|
786
|
+
]
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
\`\`\`
|
|
790
|
+
|
|
791
|
+
### Example 6: Using Parameters for Dynamic Analysis
|
|
792
|
+
**Question:** "Show me sales for the selected region and year"
|
|
793
|
+
|
|
794
|
+
\`\`\`json
|
|
795
|
+
{
|
|
796
|
+
"datasourceLuid": "abc123",
|
|
797
|
+
"query": {
|
|
798
|
+
"fields": [
|
|
799
|
+
{
|
|
800
|
+
"fieldCaption": "Category"
|
|
801
|
+
},
|
|
802
|
+
{
|
|
803
|
+
"fieldCaption": "Sales",
|
|
804
|
+
"function": "SUM",
|
|
805
|
+
"fieldAlias": "Total Sales",
|
|
806
|
+
"sortDirection": "DESC",
|
|
807
|
+
"sortPriority": 1
|
|
808
|
+
}
|
|
809
|
+
],
|
|
810
|
+
"parameters": [
|
|
811
|
+
{
|
|
812
|
+
"name": "Selected Region",
|
|
813
|
+
"value": "West"
|
|
814
|
+
},
|
|
815
|
+
{
|
|
816
|
+
"name": "Analysis Year",
|
|
817
|
+
"value": 2024
|
|
818
|
+
}
|
|
819
|
+
]
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
\`\`\`
|
|
823
|
+
|
|
610
824
|
## Error Prevention and Data Management
|
|
611
825
|
|
|
612
826
|
**When to profile data first:**
|
|
@@ -627,7 +841,318 @@ Filter relative date periods:
|
|
|
627
841
|
**Instead:**
|
|
628
842
|
- Use metadata tools to understand available fields
|
|
629
843
|
- Suggest alternative questions that can be answered with available data
|
|
630
|
-
- Recommend appropriate aggregation levels for the business question`;
|
|
844
|
+
- Recommend appropriate aggregation levels for the business question`;var na=`# Query Tableau Data Source Tool
|
|
845
|
+
|
|
846
|
+
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.
|
|
847
|
+
|
|
848
|
+
## Prerequisites
|
|
849
|
+
Before using this tool, you should:
|
|
850
|
+
1. Understand available fields and their types
|
|
851
|
+
3. Understand the data structure and field relationships
|
|
852
|
+
|
|
853
|
+
## Best Practices
|
|
854
|
+
|
|
855
|
+
### Data Volume Management
|
|
856
|
+
- **Always prefer aggregation** - Use aggregated fields (SUM, COUNT, AVG, etc.) instead of raw row-level data to reduce response size
|
|
857
|
+
- **Profile data before querying** - When unsure about data volume, first run a COUNT query to understand the scale:
|
|
858
|
+
\`\`\`json
|
|
859
|
+
{
|
|
860
|
+
"fields": [
|
|
861
|
+
{
|
|
862
|
+
"fieldCaption": "Order ID",
|
|
863
|
+
"function": "COUNT",
|
|
864
|
+
"fieldAlias": "Total Records"
|
|
865
|
+
}
|
|
866
|
+
]
|
|
867
|
+
}
|
|
868
|
+
\`\`\`
|
|
869
|
+
- **Use TOP filters for rankings** - When users ask for "top N" results, use TOP filter type to limit results at the database level
|
|
870
|
+
- **Apply restrictive filters** - Use SET, QUANTITATIVE, or DATE filters to reduce data volume before processing
|
|
871
|
+
- **Avoid row-level queries when possible** - Only retrieve individual records when specifically requested and the business need is clear
|
|
872
|
+
|
|
873
|
+
### Field Usage Guidelines
|
|
874
|
+
- **Prefer existing fields** - Use fields already modeled in the data source rather than creating custom calculations
|
|
875
|
+
- **Use calculations sparingly** - Only create calculated fields when absolutely necessary and the calculation cannot be achieved through existing fields and aggregations
|
|
876
|
+
- **Validate field availability** - Always check field metadata before constructing queries
|
|
877
|
+
|
|
878
|
+
### Query Construction
|
|
879
|
+
- **Group by meaningful dimensions** - Ensure grouping supports the business question being asked
|
|
880
|
+
- **Order results logically** - Use sortDirection and sortPriority to present data in a meaningful way
|
|
881
|
+
- **Use appropriate date functions** - Choose the right date aggregation (YEAR, QUARTER, MONTH, WEEK, DAY, or TRUNC_* variants)
|
|
882
|
+
- **Leverage filter capabilities** - Use the extensive filter options to narrow results
|
|
883
|
+
|
|
884
|
+
## Data Profiling Strategy
|
|
885
|
+
|
|
886
|
+
When a query might return large amounts of data, follow this profiling approach:
|
|
887
|
+
|
|
888
|
+
**Step 1: Count total records**
|
|
889
|
+
\`\`\`json
|
|
890
|
+
{
|
|
891
|
+
"fields": [
|
|
892
|
+
{
|
|
893
|
+
"fieldCaption": "Primary_Key_Field",
|
|
894
|
+
"function": "COUNT",
|
|
895
|
+
"fieldAlias": "Total Records"
|
|
896
|
+
}
|
|
897
|
+
]
|
|
898
|
+
}
|
|
899
|
+
\`\`\`
|
|
900
|
+
|
|
901
|
+
**Step 2: Count by key dimensions**
|
|
902
|
+
\`\`\`json
|
|
903
|
+
{
|
|
904
|
+
"fields": [
|
|
905
|
+
{
|
|
906
|
+
"fieldCaption": "Category",
|
|
907
|
+
"fieldAlias": "Category"
|
|
908
|
+
},
|
|
909
|
+
{
|
|
910
|
+
"fieldCaption": "Order ID",
|
|
911
|
+
"function": "COUNT",
|
|
912
|
+
"fieldAlias": "Record Count"
|
|
913
|
+
}
|
|
914
|
+
]
|
|
915
|
+
}
|
|
916
|
+
\`\`\`
|
|
917
|
+
|
|
918
|
+
**Step 3: Apply appropriate aggregation or filtering based on counts**
|
|
919
|
+
|
|
920
|
+
## Filter Types and Usage
|
|
921
|
+
|
|
922
|
+
### SET Filters
|
|
923
|
+
Filter by specific values:
|
|
924
|
+
\`\`\`json
|
|
925
|
+
{
|
|
926
|
+
"field": {"fieldCaption": "Region"},
|
|
927
|
+
"filterType": "SET",
|
|
928
|
+
"values": ["North", "South", "East"],
|
|
929
|
+
"exclude": false
|
|
930
|
+
}
|
|
931
|
+
\`\`\`
|
|
932
|
+
|
|
933
|
+
### TOP Filters
|
|
934
|
+
Get top/bottom N records by a measure:
|
|
935
|
+
\`\`\`json
|
|
936
|
+
{
|
|
937
|
+
"field": {"fieldCaption": "Customer Name"},
|
|
938
|
+
"filterType": "TOP",
|
|
939
|
+
"howMany": 10,
|
|
940
|
+
"direction": "TOP",
|
|
941
|
+
"fieldToMeasure": {"fieldCaption": "Sales", "function": "SUM"}
|
|
942
|
+
}
|
|
943
|
+
\`\`\`
|
|
944
|
+
|
|
945
|
+
### QUANTITATIVE Filters
|
|
946
|
+
Filter numeric ranges:
|
|
947
|
+
\`\`\`json
|
|
948
|
+
{
|
|
949
|
+
"field": {"fieldCaption": "Sales"},
|
|
950
|
+
"filterType": "QUANTITATIVE_NUMERICAL",
|
|
951
|
+
"quantitativeFilterType": "RANGE",
|
|
952
|
+
"min": 1000,
|
|
953
|
+
"max": 50000,
|
|
954
|
+
"includeNulls": false
|
|
955
|
+
}
|
|
956
|
+
\`\`\`
|
|
957
|
+
|
|
958
|
+
### DATE Filters
|
|
959
|
+
Filter relative date periods:
|
|
960
|
+
\`\`\`json
|
|
961
|
+
{
|
|
962
|
+
"field": {"fieldCaption": "Order Date"},
|
|
963
|
+
"filterType": "DATE",
|
|
964
|
+
"periodType": "MONTHS",
|
|
965
|
+
"dateRangeType": "LAST"
|
|
966
|
+
}
|
|
967
|
+
\`\`\`
|
|
968
|
+
|
|
969
|
+
## Example Queries
|
|
970
|
+
|
|
971
|
+
### Example 1: Data Profiling Before Large Query
|
|
972
|
+
**Question:** "Show me all customer orders this year"
|
|
973
|
+
|
|
974
|
+
**Step 1 - Profile the data volume:**
|
|
975
|
+
\`\`\`json
|
|
976
|
+
{
|
|
977
|
+
"datasourceLuid": "abc123",
|
|
978
|
+
"query": {
|
|
979
|
+
"fields": [
|
|
980
|
+
{
|
|
981
|
+
"fieldCaption": "Order ID",
|
|
982
|
+
"function": "COUNT",
|
|
983
|
+
"fieldAlias": "Total Orders This Year"
|
|
984
|
+
}
|
|
985
|
+
],
|
|
986
|
+
"filters": [
|
|
987
|
+
{
|
|
988
|
+
"field": {"fieldCaption": "Order Date"},
|
|
989
|
+
"filterType": "DATE",
|
|
990
|
+
"periodType": "YEARS",
|
|
991
|
+
"dateRangeType": "CURRENT"
|
|
992
|
+
}
|
|
993
|
+
]
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
\`\`\`
|
|
997
|
+
|
|
998
|
+
**If count is manageable (< 10,000), proceed with detail query. If large, suggest aggregation:**
|
|
999
|
+
\`\`\`json
|
|
1000
|
+
{
|
|
1001
|
+
"datasourceLuid": "abc123",
|
|
1002
|
+
"query": {
|
|
1003
|
+
"fields": [
|
|
1004
|
+
{
|
|
1005
|
+
"fieldCaption": "Customer Name"
|
|
1006
|
+
},
|
|
1007
|
+
{
|
|
1008
|
+
"fieldCaption": "Order Date",
|
|
1009
|
+
"function": "TRUNC_MONTH",
|
|
1010
|
+
"sortDirection": "DESC",
|
|
1011
|
+
"sortPriority": 1
|
|
1012
|
+
},
|
|
1013
|
+
{
|
|
1014
|
+
"fieldCaption": "Sales",
|
|
1015
|
+
"function": "SUM",
|
|
1016
|
+
"fieldAlias": "Monthly Sales"
|
|
1017
|
+
}
|
|
1018
|
+
],
|
|
1019
|
+
"filters": [
|
|
1020
|
+
{
|
|
1021
|
+
"field": {"fieldCaption": "Order Date"},
|
|
1022
|
+
"filterType": "DATE",
|
|
1023
|
+
"periodType": "YEARS",
|
|
1024
|
+
"dateRangeType": "CURRENT"
|
|
1025
|
+
}
|
|
1026
|
+
]
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
\`\`\`
|
|
1030
|
+
|
|
1031
|
+
### Example 2: Top Customers Query (Using TOP Filter)
|
|
1032
|
+
**Question:** "Who are our top 10 customers by revenue?"
|
|
1033
|
+
|
|
1034
|
+
\`\`\`json
|
|
1035
|
+
{
|
|
1036
|
+
"datasourceLuid": "abc123",
|
|
1037
|
+
"query": {
|
|
1038
|
+
"fields": [
|
|
1039
|
+
{
|
|
1040
|
+
"fieldCaption": "Customer Name"
|
|
1041
|
+
},
|
|
1042
|
+
{
|
|
1043
|
+
"fieldCaption": "Sales",
|
|
1044
|
+
"function": "SUM",
|
|
1045
|
+
"fieldAlias": "Total Revenue",
|
|
1046
|
+
"sortDirection": "DESC",
|
|
1047
|
+
"sortPriority": 1
|
|
1048
|
+
}
|
|
1049
|
+
],
|
|
1050
|
+
"filters": [
|
|
1051
|
+
{
|
|
1052
|
+
"field": {"fieldCaption": "Customer Name"},
|
|
1053
|
+
"filterType": "TOP",
|
|
1054
|
+
"howMany": 10,
|
|
1055
|
+
"direction": "TOP",
|
|
1056
|
+
"fieldToMeasure": {"fieldCaption": "Sales", "function": "SUM"}
|
|
1057
|
+
}
|
|
1058
|
+
]
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
\`\`\`
|
|
1062
|
+
|
|
1063
|
+
### Example 3: Time Series with Aggregation
|
|
1064
|
+
**Question:** "What are our monthly sales trends?"
|
|
1065
|
+
|
|
1066
|
+
\`\`\`json
|
|
1067
|
+
{
|
|
1068
|
+
"datasourceLuid": "abc123",
|
|
1069
|
+
"query": {
|
|
1070
|
+
"fields": [
|
|
1071
|
+
{
|
|
1072
|
+
"fieldCaption": "Order Date",
|
|
1073
|
+
"function": "TRUNC_MONTH",
|
|
1074
|
+
"fieldAlias": "Month",
|
|
1075
|
+
"sortDirection": "ASC",
|
|
1076
|
+
"sortPriority": 1
|
|
1077
|
+
},
|
|
1078
|
+
{
|
|
1079
|
+
"fieldCaption": "Sales",
|
|
1080
|
+
"function": "SUM",
|
|
1081
|
+
"fieldAlias": "Monthly Sales"
|
|
1082
|
+
},
|
|
1083
|
+
{
|
|
1084
|
+
"fieldCaption": "Order ID",
|
|
1085
|
+
"function": "COUNT",
|
|
1086
|
+
"fieldAlias": "Order Count"
|
|
1087
|
+
}
|
|
1088
|
+
]
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
\`\`\`
|
|
1092
|
+
|
|
1093
|
+
### Example 4: Filtered Category Analysis
|
|
1094
|
+
**Question:** "What's the performance by product category for high-value orders?"
|
|
1095
|
+
|
|
1096
|
+
\`\`\`json
|
|
1097
|
+
{
|
|
1098
|
+
"datasourceLuid": "abc123",
|
|
1099
|
+
"query": {
|
|
1100
|
+
"fields": [
|
|
1101
|
+
{
|
|
1102
|
+
"fieldCaption": "Category"
|
|
1103
|
+
},
|
|
1104
|
+
{
|
|
1105
|
+
"fieldCaption": "Sales",
|
|
1106
|
+
"function": "SUM",
|
|
1107
|
+
"fieldAlias": "Total Sales"
|
|
1108
|
+
},
|
|
1109
|
+
{
|
|
1110
|
+
"fieldCaption": "Sales",
|
|
1111
|
+
"function": "AVG",
|
|
1112
|
+
"fieldAlias": "Average Order Value",
|
|
1113
|
+
"maxDecimalPlaces": 2
|
|
1114
|
+
},
|
|
1115
|
+
{
|
|
1116
|
+
"fieldCaption": "Order ID",
|
|
1117
|
+
"function": "COUNT",
|
|
1118
|
+
"fieldAlias": "Order Count"
|
|
1119
|
+
}
|
|
1120
|
+
],
|
|
1121
|
+
"filters": [
|
|
1122
|
+
{
|
|
1123
|
+
"field": {"fieldCaption": "Sales"},
|
|
1124
|
+
"filterType": "QUANTITATIVE_NUMERICAL",
|
|
1125
|
+
"quantitativeFilterType": "MIN",
|
|
1126
|
+
"min": 500
|
|
1127
|
+
}
|
|
1128
|
+
]
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
\`\`\`
|
|
1132
|
+
|
|
1133
|
+
## Error Prevention and Data Management
|
|
1134
|
+
|
|
1135
|
+
**When to profile data first:**
|
|
1136
|
+
- User asks for "all records" or similar broad requests
|
|
1137
|
+
- Query involves high-cardinality fields without filters
|
|
1138
|
+
- Request could potentially return row-level data for large tables
|
|
1139
|
+
|
|
1140
|
+
**Suggest aggregation when:**
|
|
1141
|
+
- Profile queries return very high counts (> 10,000 records)
|
|
1142
|
+
- User asks questions that can be answered with summaries
|
|
1143
|
+
- Performance or response size might be an issue
|
|
1144
|
+
|
|
1145
|
+
**Don't call this tool if:**
|
|
1146
|
+
- The requested fields are not available in the data source
|
|
1147
|
+
- The question requires data not present in the current data source
|
|
1148
|
+
- Field validation shows incompatible field types for the requested operation
|
|
1149
|
+
|
|
1150
|
+
**Instead:**
|
|
1151
|
+
- Use metadata tools to understand available fields
|
|
1152
|
+
- Suggest alternative questions that can be answered with available data
|
|
1153
|
+
- Recommend appropriate aggregation levels for the business question`;import Jt from"fast-levenshtein";import{Err as ii,Ok as Ze}from"ts-results-es";async function aa(t,e,r,o){if(!e.filters)return Ze.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 Ze.EMPTY;for(let s of n){let a=s.field.fieldCaption;try{if(s.filterType==="SET"){let l=await Bp(s,r,o);l.isErr()&&i.push(l.error)}else if(s.filterType==="MATCH"){let l=await zp(s,r,o);l.isErr()&&i.push(l.error)}}catch(l){ue.warning(t,`Filter value validation failed for field ${a}: ${l}`)}}return i.length>0?new ii(i):Ze.EMPTY}async function Bp(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 Ze.EMPTY;let l=a.value.data||[],c=new Set(l.map(p=>String(p.DistinctValues||p[o]||""))),u=i.filter(p=>!c.has(p));if(u.length>0){let p=Wp(u,Array.from(c),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 ii({field:o,invalidValues:u,sampleValues:p,message:g})}return Ze.EMPTY}async function zp(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 Ze.EMPTY;let l=(s.value.data||[]).map(u=>String(u.SampleValues||u[o]||""));if(!l.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 m of l){if(u.size>=5)break;let y=m.toLowerCase(),T=t.startsWith?(()=>{let S=t.startsWith.toLowerCase(),C=S.length,x=Math.min(2,Math.floor(C/2)),q=y.slice(0,C);return Jt.get(S,q)<=x})():!0,v=t.endsWith?(()=>{let S=t.endsWith.toLowerCase(),C=S.length,x=Math.min(2,Math.floor(C/2)),q=y.slice(-C);return Jt.get(S,q)<=x})():!0,P=t.contains?(()=>{let S=t.contains.toLowerCase(),C=S.length,x=Math.min(2,Math.floor(C/2));return y.length>=C?Array.from({length:y.length-C+1},(q,F)=>Jt.get(S,y.slice(F,F+C))).some(q=>q<=x):Jt.get(S,y)<=x})():!0;T&&v&&P&&u.add(m)}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 ii({field:o,invalidValues:p,sampleValues:Array.from(u),message:b})}return Ze.EMPTY}function Wp(t,e,r=3,o=5){let i=[];for(let l of e){let c=t.map(u=>({value:u,distance:Jt.get(u.toLowerCase(),l.toLowerCase())})).filter(u=>u.distance<=r).sort((u,p)=>u.distance-p.distance);if(c.length>0){let u=c[0];i.push({invalidValue:u.value,suggestionForInvalidValue:l,distance:u.distance})}}i.sort((l,c)=>l.distance-c.distance);let n=[],s=Math.ceil(o/t.length),a=new Map;for(let l of t)a.set(l,0);for(let{invalidValue:l,suggestionForInvalidValue:c}of i){if(n.length===o)break;a.get(l)!==s&&(n.push(c),a.set(l,a.get(l)+1))}for(let{suggestionForInvalidValue:l}of i){if(n.length===o)break;if(n.includes(l))continue;n.push(l)}return n}import{Err as Hp,Ok as si}from"ts-results-es";async function la(t,e,r){let o=[];try{let i=await e.readMetadata({datasource:{datasourceLuid:r.datasourceLuid}});if(i.isErr()||!i.value.data)return si.EMPTY;$p(t.fields,i.value,o),t.parameters&&Gp(t.parameters,i.value,o)}catch{return si.EMPTY}return o.length>0?new Hp(o):si.EMPTY}function $p(t,e,r){for(let o of t){if("binSize"in o){if(e.data?.find(a=>a.fieldCaption===o.fieldCaption&&a.columnClass==="BIN")){r.push({field:o.fieldCaption,message:`The bin field '${o.fieldCaption}' has a fixed bin size defined in the datasource and can not be modified. To create a new bin on a field, use the field caption of the measure field you want to group. To use this bin, omit the binSize property.`});continue}t.find(a=>a.fieldCaption===o.fieldCaption&&"function"in a&&a.function)||r.push({field:o.fieldCaption,message:`The bin field '${o.fieldCaption}' was provided in the query, but no corresponding measure field was found. To create a new bin on a field, use the field caption of the measure field you want to group.`});continue}let i=e.data?.find(n=>n.fieldCaption===o.fieldCaption);if(i){if("calculation"in o){"formula"in i?r.push({field:o.fieldCaption,message:`A custom calculation was provided for field '${o.fieldCaption}', but this field already has a calculation and can not be overwritten. To query this field, omit the calculation property. To create a new calculation, provide a new field caption.`}):r.push({field:o.fieldCaption,message:`A custom calculation was provided for field '${o.fieldCaption}', but this field already exists in the datasource. To create a new calculation, provide a new field caption. To query this field, omit the calculation property.`});continue}}else{"calculation"in o||r.push({field:o.fieldCaption,message:`Field '${o.fieldCaption}' was not found in the datasource. Fields must either belong to the datasource or provide a custom calculation.`});continue}if("function"in o)switch(i.dataType){case"INTEGER":case"REAL":["SUM","AVG","MEDIAN","COUNT","COUNTD","MIN","MAX","STDEV","VAR"].includes(o.function)||r.push({field:o.fieldCaption,message:`The '${o.fieldCaption}' field is of type '${i.dataType}'. The '${o.function}' function can not be applied to fields of this data type.`});continue;case"STRING":case"BOOLEAN":["MIN","MAX","COUNT","COUNTD"].includes(o.function)||r.push({field:o.fieldCaption,message:`The '${o.fieldCaption}' field is of type '${i.dataType}'. The '${o.function}' function can not be applied to fields of this data type.`});continue;case"DATE":case"DATETIME":["MIN","MAX","COUNT","COUNTD","YEAR","QUARTER","MONTH","WEEK","DAY","TRUNC_YEAR","TRUNC_QUARTER","TRUNC_MONTH","TRUNC_WEEK","TRUNC_DAY"].includes(o.function)||r.push({field:o.fieldCaption,message:`The '${o.fieldCaption}' field is of type '${i.dataType}'. The '${o.function}' function can not be applied to fields of this data type.`});continue;default:continue}}}function Gp(t,e,r){for(let o of t){let i=e.extraData?.parameters?.find(n=>n.parameterCaption===o.parameterCaption);if(!i){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was not found in the datasource. Only parameters that are defined in the datasource can be used in a query.`});continue}switch(i.parameterType){case"ANY_VALUE":Qp(o.value,i.dataType)||r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' has '${i.dataType}' data type but was provided a value that does not match the data type: ${o.value}.`});continue;case"LIST":i.members.includes(o.value)||r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' has a value that is not in the list of allowed values for the parameter. The list of allowed values is [${i.members.join(", ")}].`});continue;case"QUANTITATIVE_DATE":if(typeof o.value!="string"||isNaN(Date.parse(o.value))){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was provided a value that is not a valid date. Dates must use the RFC 3339 standard. Example: 2025-03-14`});continue}if(i.minDate&&new Date(o.value)<new Date(i.minDate)){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was provided a value that is less than the minimum allowed date of ${i.minDate}.`});continue}if(i.maxDate&&new Date(o.value)>new Date(i.maxDate)){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was provided a value that is greater than the maximum allowed date of ${i.maxDate}.`});continue}continue;case"QUANTITATIVE_RANGE":if(typeof o.value!="number"){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' is a quantitative range parameter, and can only be assigned numerical values.`});continue}if(i.min!=null&&o.value<i.min){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was provided a value that is less than the minimum allowed value of ${i.min}.`});continue}if(i.max!=null&&o.value>i.max){r.push({parameter:o.parameterCaption,message:`Parameter '${o.parameterCaption}' was provided a value that is greater than the maximum allowed value of ${i.max}.`});continue}continue;default:continue}}}function Qp(t,e){if(t===null)return!0;switch(e){case"INTEGER":return typeof t=="number"&&Number.isInteger(t);case"REAL":return typeof t=="number";case"STRING":return typeof t=="string";case"BOOLEAN":return typeof t=="boolean";case"DATE":return typeof t=="string"&&!isNaN(Date.parse(t));default:return!1}}var Yp={datasourceLuid:Jp.string().nonempty(),query:$t},ca=(t,e)=>{let r=A(),o=new N({server:t,name:"query-datasource",description:new ye(async()=>await Kn({server:r.server||e?.server,mappings:{"2025.3.0":sa,default:na}})),paramsSchema:Yp,annotations:{title:"Query Datasource",readOnlyHint:!0,openWorldHint:!1},argsValidator:ia,callback:async({datasourceLuid:i,query:n},{requestId:s,authInfo:a})=>await o.logAndExecute({requestId:s,authInfo:a,args:{datasourceLuid:i,query:n},callback:async()=>{let l=await be.isDatasourceAllowed({datasourceLuid:i,restApiArgs:{config:r,requestId:s,server:t}});if(!l.allowed)return new Vr({type:"datasource-not-allowed",message:l.message});let c={datasourceLuid:i},u={returnFormat:"OBJECTS",debug:!0,disaggregate:!1},p=Zn(i);p&&(c.connections=p);let g={datasource:c,query:n,options:u};return await D({config:r,requestId:s,server:t,jwtScopes:["tableau:viz_data_service:read"],authInfo:M(a),callback:async b=>{if(!r.disableQueryDatasourceValidationRequests){let y=await la(n,b.vizqlDataServiceMethods,c);if(y.isErr()){let P=y.error.map(S=>S.message).join(`
|
|
1154
|
+
|
|
1155
|
+
`);return new Vr({type:"query-validation",message:P})}let T=await aa(t,n,b.vizqlDataServiceMethods,c);if(T.isErr()){let P=T.error.map(S=>S.message).join(", ");return new Vr({type:"query-validation",message:P})}}let m=await b.vizqlDataServiceMethods.queryDatasource(g);return m.isErr()?new Vr(m.error instanceof Kp?m.error:m.error==="feature-disabled"?{type:"feature-disabled"}:{type:"tableau-error",error:m.error}):m}})},constrainSuccessResult:l=>({type:"success",result:l}),getErrorText:l=>{switch(l.type){case"feature-disabled":return Mr();case"datasource-not-allowed":return l.message;case"query-validation":return JSON.stringify({requestId:s,errorType:"validation",message:l.message});case"tableau-error":return JSON.stringify({requestId:s,...Xn(l.error)})}}})});return o};import{Err as Zp,Ok as Xp}from"ts-results-es";import{z as em}from"zod";var tm={viewId:em.string()},ua=t=>{let e=new N({server:t,name:"get-view-data",description:"Retrieves data in comma separated value (CSV) format for the specified view in a Tableau workbook.",paramsSchema:tm,annotations:{title:"Get View Data",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r},{requestId:o,authInfo:i})=>{let n=A();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 Xp(await D({config:n,requestId:o,server:t,jwtScopes:["tableau:views:download"],authInfo:M(i),callback:async a=>await a.viewsMethods.queryViewData({viewId:r,siteId:a.siteId})})):new Zp({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 rm,Ok as om}from"ts-results-es";import{z as ni}from"zod";function da(t){return{isError:!1,content:[{type:"image",data:Buffer.from(t).toString("base64"),mimeType:"image/png"}]}}var im={viewId:ni.string(),width:ni.number().gt(0).optional(),height:ni.number().gt(0).optional()},pa=t=>{let e=new N({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:im,annotations:{title:"Get View Image",readOnlyHint:!0,openWorldHint:!1},callback:async({viewId:r,width:o,height:i},{requestId:n,authInfo:s})=>{let a=A();return await e.logAndExecute({requestId:n,authInfo:s,args:{viewId:r},callback:async()=>{let l=await be.isViewAllowed({viewId:r,restApiArgs:{config:a,requestId:n,server:t}});return l.allowed?new om(await D({config:a,requestId:n,server:t,jwtScopes:["tableau:views:download"],authInfo:M(s),callback:async c=>await c.viewsMethods.queryViewImage({viewId:r,siteId:c.siteId,width:o,height:i,resolution:"high"})})):new rm({type:"view-not-allowed",message:l.message})},constrainSuccessResult:l=>({type:"success",result:l}),getSuccessResult:da,getErrorText:l=>{switch(l.type){case"view-not-allowed":return l.message}}})}});return e};import{Ok as nm}from"ts-results-es";import{z as li}from"zod";import{z as ai}from"zod";var ma=ai.enum(["caption","contentUrl","createdAt","favoritesTotal","fields","hitsTotal","name","ownerDomain","ownerEmail","ownerName","projectName","sheetNumber","sheetType","tags","title","updatedAt","viewUrlname","workbookDescription","workbookName"]),sm={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"]},Jv=ai.object({field:ma,operator:Je,value:ai.string()});function fa(t){return wt({filterString:t,allowedOperatorsByField:sm,filterFieldSchema:ma})}var am={filter:li.string().optional(),pageSize:li.number().gt(0).optional(),limit:li.number().gt(0).optional()},ha=t=>{let e=new N({server:t,name:"list-views",description:`
|
|
631
1156
|
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.
|
|
632
1157
|
|
|
633
1158
|
**Supported Filter Fields and Operators**
|
|
@@ -653,7 +1178,7 @@ Filter relative date periods:
|
|
|
653
1178
|
| workbookDescription | eq, in |
|
|
654
1179
|
| workbookName | eq, in |
|
|
655
1180
|
|
|
656
|
-
${
|
|
1181
|
+
${Tt}
|
|
657
1182
|
|
|
658
1183
|
**Example Usage:**
|
|
659
1184
|
- List all views on a site
|
|
@@ -664,7 +1189,7 @@ Filter relative date periods:
|
|
|
664
1189
|
- List views created after January 1, 2023:
|
|
665
1190
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
666
1191
|
- List views with the name "Overview" in the "Finance" project and created after January 1, 2023:
|
|
667
|
-
filter: "name:eq:Overview,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:
|
|
1192
|
+
filter: "name:eq:Overview,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:am,annotations:{title:"List Views",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=A(),l=r?fa(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{},callback:async()=>new nm(await D({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:M(s),callback:async c=>await bt({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 c.viewsMethods.queryViewsForSite({siteId:c.siteId,filter:l??"",includeUsageStatistics:!0,pageSize:p.pageSize,pageNumber:p.pageNumber});return{pagination:g,data:b}}})})),constrainSuccessResult:c=>lm({views:c,boundedContext:a.boundedContext})})}});return e};function lm({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 cm,Ok as um}from"ts-results-es";import{z as dm}from"zod";var pm={workbookId:dm.string()},ga=t=>{let e=new N({server:t,name:"get-workbook",description:"Retrieves information about the specified workbook, including information about the views contained in the workbook.",paramsSchema:pm,annotations:{title:"Get Workbook",readOnlyHint:!0,openWorldHint:!1},callback:async({workbookId:r},{requestId:o,authInfo:i})=>{let n=A();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 um(await D({config:n,requestId:o,server:t,jwtScopes:["tableau:content:read"],authInfo:M(i),callback:async a=>{let l=s.content??await a.workbooksMethods.getWorkbook({workbookId:r,siteId:a.siteId});if(l.views){let c=await a.viewsMethods.queryViewsForWorkbook({workbookId:r,siteId:a.siteId,includeUsageStatistics:!0});l.views.view=c}return l}})):new cm({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 fm}from"ts-results-es";import{z as ui}from"zod";import{z as ci}from"zod";var ya=ci.enum(["createdAt","contentUrl","displayTabs","favoritesTotal","hasAlerts","hasExtracts","name","ownerDomain","ownerEmail","ownerName","projectName","sheetCount","size","subscriptionTotal","tags","updatedAt"]),mm={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"]},AC=ci.object({field:ya,operator:Je,value:ci.string()});function ba(t){return wt({filterString:t,allowedOperatorsByField:mm,filterFieldSchema:ya})}var hm={filter:ui.string().optional(),pageSize:ui.number().gt(0).optional(),limit:ui.number().gt(0).optional()},Ta=t=>{let e=new N({server:t,name:"list-workbooks",description:`
|
|
668
1193
|
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.
|
|
669
1194
|
|
|
670
1195
|
**Supported Filter Fields and Operators**
|
|
@@ -687,7 +1212,7 @@ Filter relative date periods:
|
|
|
687
1212
|
| tags | eq, in |
|
|
688
1213
|
| updatedAt | eq, gt, gte, lt, lte |
|
|
689
1214
|
|
|
690
|
-
${
|
|
1215
|
+
${Tt}
|
|
691
1216
|
|
|
692
1217
|
**Example Usage:**
|
|
693
1218
|
- List all workbooks on a site
|
|
@@ -698,18 +1223,18 @@ Filter relative date periods:
|
|
|
698
1223
|
- List workbooks created after January 1, 2023:
|
|
699
1224
|
filter: "createdAt:gt:2023-01-01T00:00:00Z"
|
|
700
1225
|
- List workbooks with the name "Superstore" in the "Finance" project and created after January 1, 2023:
|
|
701
|
-
filter: "name:eq:Superstore,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:
|
|
1226
|
+
filter: "name:eq:Superstore,projectName:eq:Finance,createdAt:gt:2023-01-01T00:00:00Z"`,paramsSchema:hm,annotations:{title:"List Workbooks",readOnlyHint:!0,openWorldHint:!1},callback:async({filter:r,pageSize:o,limit:i},{requestId:n,authInfo:s})=>{let a=A(),l=r?ba(r):void 0;return await e.logAndExecute({requestId:n,authInfo:s,args:{},callback:async()=>new fm(await D({config:a,requestId:n,server:t,jwtScopes:["tableau:content:read"],authInfo:M(s),callback:async c=>await bt({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 c.workbooksMethods.queryWorkbooksForSite({siteId:c.siteId,filter:l??"",pageSize:p.pageSize,pageNumber:p.pageNumber});return{pagination:g,data:b}}})})),constrainSuccessResult:c=>gm({workbooks:c,boundedContext:a.boundedContext})})}});return e};function gm({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 wa=[Mn,Fn,ca,Bn,zn,Wn,$n,Gn,Vn,ga,ua,pa,Ta,ha,Pn];var Me="tableau-mcp",Yt=xi.version,Dr=`${Me}/${Yt}`,Xe=class extends ym{name;version;_clientInfo;get clientInfo(){return this._clientInfo??this.server.getClientVersion()}constructor({clientInfo:e}={}){super({name:Me,version:Yt},{capabilities:{logging:{},tools:{}}}),this.name=Me,this.version=Yt,this._clientInfo=e}registerTools=async e=>{for(let{name:r,description:o,paramsSchema:i,annotations:n,callback:s}of this._getToolsToRegister(e))this.tool(r,await ye.from(o),await ye.from(i),await ye.from(n),await ye.from(s))};registerRequestHandlers=()=>{this.server.setRequestHandler(bm,async e=>(et(this,e.params.level),{}))};_getToolsToRegister=e=>{let{includeTools:r,excludeTools:o}=A(),n=wa.map(s=>s(this,e)).filter(s=>r.length>0?r.includes(s.name):o.length>0?!o.includes(s.name):!0);if(n.length===0)throw new Error(`
|
|
702
1227
|
No tools to register.
|
|
703
|
-
Tools available = [${
|
|
704
|
-
EXCLUDE_TOOLS = [${
|
|
705
|
-
INCLUDE_TOOLS = [${
|
|
706
|
-
`);return
|
|
1228
|
+
Tools available = [${Jr.join(", ")}].
|
|
1229
|
+
EXCLUDE_TOOLS = [${o.join(", ")}].
|
|
1230
|
+
INCLUDE_TOOLS = [${r.join(", ")}]
|
|
1231
|
+
`);return n}};import{StreamableHTTPServerTransport as Gm}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as Qm}from"@modelcontextprotocol/sdk/types.js";import Km from"cors";import gi from"express";import za,{existsSync as Wa}from"fs";import Jm from"http";import Ym from"https";import{StreamableHTTPServerTransport as Tm}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{randomUUID as wm}from"crypto";var di={},Aa=({clientInfo:t})=>{let e=new Tm({sessionIdGenerator:()=>wm(),onsessioninitialized:r=>{di[r]={transport:e,clientInfo:t}}});return e.onclose=()=>{e.sessionId&&Am(e.sessionId)},e},pi=t=>di[t],Am=t=>{delete di[t]};function Sa(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 Wm,createPublicKey as Hm}from"crypto";import{readFileSync as $m}from"fs";function Ea(t){t.get("/.well-known/oauth-authorization-server",(e,r)=>{let o=A().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"],client_id_metadata_document_supported:!0})})}function _a(t){t.get("/.well-known/oauth-protected-resource",(e,r)=>{let o=A().oauth.issuer;r.json({resource:`${o}/${Me}`,authorization_servers:[o],bearer_methods_supported:["header"]})})}import{compactDecrypt as Sm}from"jose";import{Err as Zt,Ok as Em}from"ts-results-es";import{fromError as va}from"zod-validation-error";function Ca(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
|
|
707
1232
|
`),r.write(`data: {"error": "unauthorized", "error_description": "Authorization required"}
|
|
708
1233
|
|
|
709
|
-
`),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
|
|
1234
|
+
`),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 _m(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
|
|
710
1235
|
`),r.write(`data: {"error": "invalid_token", "error_description": "${s.error}"}
|
|
711
1236
|
|
|
712
|
-
`),r.end();return}r.status(401).json({error:"invalid_token",error_description:s.error});return}e.auth=s.value,o()}}async function hp(t,e){let r=E();try{let{plaintext:o}=await mp(t,e),i=JSON.parse(new TextDecoder().decode(o)),n=Po.safeParse(i);if(!n.success)return Ht(`Invalid access token: ${Kn(n.error).toString()}`);let{iss:s,aud:a,exp:d,clientId:l}=n.data;if(s!==r.oauth.issuer||a!==Gt||d<Math.floor(Date.now()/1e3))return new Ht("Invalid or expired access token");let c;if(r.auth==="oauth"){let m=Zs.safeParse(i);if(!m.success)return Ht(`Invalid access token: ${Kn(m.error).toString()}`);let{tableauAccessToken:g,tableauRefreshToken:w,tableauExpiresAt:f,tableauUserId:b,tableauServer:y,sub:S}=m.data;if(f<Math.floor(Date.now()/1e3))return new Ht("Invalid or expired access token");c={username:S,userId:b,server:y,accessToken:g,refreshToken:w}}else{let{tableauUserId:m,tableauServer:g,sub:w}=n.data;c={username:w,server:g,...m?{userId:m}:{}}}return fp({token:t,clientId:l,scopes:[],expiresAt:i.exp,extra:c})}catch{return new Ht("Invalid or expired access token")}}import{randomBytes as Go,randomUUID as Zn}from"crypto";import{fromError as bp}from"zod-validation-error";function $t(t,e,...r){return e>2147483647?setTimeout(()=>{$t(t,e-2147483647,...r)},2147483647):setTimeout(t,e,...r)}import{createHash as gp}from"crypto";function Ir(t){return gp("sha256").update(t).digest("base64url")}function kr(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 Yn(t,e){let r=E();t.get("/oauth/authorize",(o,i)=>{let n=Qs.safeParse(o.query);if(!n.success){i.status(400).json({error:"invalid_request",error_description:bp(n.error).toString()});return}let{clientId:s,redirectUri:a,responseType:d,codeChallenge:l,codeChallengeMethod:c,state:m}=n.data;if(d!=="code"){i.status(400).json({error:"unsupported_response_type",error_description:"Only authorization code flow is supported"});return}if(c!=="S256"){i.status(400).json({error:"invalid_request",error_description:"Only S256 code challenge method is supported"});return}if(!kr(a)){i.status(400).json({error:"invalid_request",error_description:`Invalid redirect URI: ${a}`});return}let g=Go(32).toString("hex"),w=Go(32).toString("hex"),f=Zn(),b=Math.floor(Math.random()*43)+22,y=Go(b).toString("hex"),S=Ir(y);e.set(w,{clientId:s,redirectUri:a,codeChallenge:l,state:m??"",tableauState:g,tableauClientId:f,tableauCodeVerifier:y}),$t(()=>e.delete(w),r.oauth.authzCodeTimeoutMs);let P=r.server||Dr,A=new URL(`${P}/oauth2/v1/auth`);A.searchParams.set("client_id",f),A.searchParams.set("code_challenge",S),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",`${w}:${g}`),A.searchParams.set("device_id",Zn()),A.searchParams.set("target_site",r.siteName),A.searchParams.set("device_name",yp(a,m??"")),A.searchParams.set("client_type","tableau-mcp"),i.redirect(A.toString())})}function yp(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 Ap}from"crypto";import{Err as Ep,Ok as _p}from"ts-results-es";import{fromError as Sp}from"zod-validation-error";import{Zodios as Tp}from"@zodios/core";import{makeApi as wp}from"@zodios/core";import{z as se}from"zod";var Xn=se.discriminatedUnion("grant_type",[se.object({grant_type:se.literal("authorization_code"),code:se.string(),code_verifier:se.string(),redirect_uri:se.string(),client_id:se.string()}),se.object({grant_type:se.literal("refresh_token"),client_id:se.string(),refresh_token:se.string(),site_namespace:se.string()})]),ea=se.object({access_token:B("access_token"),expires_in:se.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 ta=wp([{method:"post",path:"/oauth2/v1/token",alias:"token",response:ea,parameters:[{name:"body",type:"Body",schema:Xn}]}]);var ra=t=>new Tp(t,ta);async function Pr(t,e){return await ra(t).token(e,{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Tr}})}function oa(t,e,r){let o=E();t.get("/Callback",async(i,n)=>{let s=Js.safeParse(i.query);if(!s.success){n.status(400).json({error:"invalid_request",error_description:Sp(s.error).toString()});return}let{error:a,code:d,state:l}=s.data;if(a){n.status(400).json({error:"access_denied",error_description:"User denied authorization"});return}try{let[c,m]=l?.split(":")??[],g=e.get(c);if(!g||g.tableauState!==m){n.status(400).json({error:"invalid_request",error_description:"Invalid state parameter"});return}let w=await Cp({server:o.server||Dr,code:d??"",redirectUri:o.oauth.redirectUri,clientId:g.tableauClientId,codeVerifier:g.tableauCodeVerifier});if(w.isErr()){n.status(400).json({error:"invalid_request",error_description:w.error});return}let{accessToken:f,refreshToken:b,expiresInSeconds:y,originHost:S}=w.value,P=new URL(`https://${S}`);if(o.server){let le=new URL(o.server);if(P.hostname!==le.hostname){n.status(400).json({error:"invalid_request",error_description:`Invalid origin host: ${S}. Expected: ${new URL(o.server).hostname}`});return}}let A=P.toString(),R=new He(A);R.setCredentials(f,"unknown user id");let x=await R.serverMethods.getCurrentServerSession();if(x.isErr()){x.error.type==="unauthorized"?n.status(401).json({error:"unauthorized",error_description:`Unable to get the Tableau server session. Error: ${JSON.stringify(x.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 q=Ap(32).toString("hex");r.set(q,{clientId:g.clientId,redirectUri:g.redirectUri,codeChallenge:g.codeChallenge,user:x.value.user,server:A,tableauClientId:g.tableauClientId,tokens:{accessToken:f,refreshToken:b,expiresInSeconds:y},expiresAt:Math.floor((Date.now()+o.oauth.authzCodeTimeoutMs)/1e3)}),e.delete(c);let U=new URL(g.redirectUri);U.searchParams.set("code",q),U.searchParams.set("state",g.state),n.redirect(U.toString())}catch(c){console.error("OAuth callback error:",c),n.status(500).json({error:"server_error",error_description:"Internal server error during authorization. Contact your administrator."})}})}async function Cp({server:t,code:e,redirectUri:r,clientId:o,codeVerifier:i}){try{let n=await Pr(t,{grant_type:"authorization_code",code:e,redirect_uri:r,client_id:o,code_verifier:i});return _p(n)}catch{return Ep("Failed to exchange authorization code")}}import vp from"express";function ia(t){t.post("/oauth/register",vp.json(),(e,r)=>{let{redirect_uris:o}=e.body,i=[];if(o&&Array.isArray(o))for(let n of o){if(!kr(n)){r.status(400).json({error:"invalid_redirect_uri",error_description:`Invalid redirect URI: ${n}`});return}i.push(n)}r.json({client_id:"mcp-public-client",redirect_uris:i,grant_types:["authorization_code","client_credentials"],response_types:["code"],token_endpoint_auth_method:"client_secret_basic",application_type:"native"})})}import{randomBytes as sa,timingSafeEqual as Rp}from"crypto";import{CompactEncrypt as na}from"jose";import{Err as De,Ok as Qo}from"ts-results-es";import{fromError as xp}from"zod-validation-error";function aa(t,e,r,o){let i=E();t.post("/oauth/token",async(n,s)=>{let a=Ks.safeParse(n.body);if(!a.success){s.status(400).json({error:"invalid_request",error_description:xp(a.error).toString()});return}let d=Dp({required:a.data.grantType==="client_credentials",clientId:a.data.clientId,clientSecret:a.data.clientSecret,clientIdSecretPairs:E().oauth.clientIdSecretPairs,authorizationHeader:n.headers.authorization});if(d.isErr()){s.status(401).json({error:"invalid_client",error_description:d.error});return}try{switch(a.data.grantType){case"authorization_code":{let{code:l,codeVerifier:c}=a.data,m=e.get(l);if(!m||m.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(Ir(c)!==m.codeChallenge){s.status(400).json({error:"invalid_grant",error_description:"Invalid code verifier"});return}let w=sa(32).toString("hex"),f=await $o(m,o);r.set(w,{user:m.user,server:m.server,clientId:m.clientId,tokens:m.tokens,expiresAt:Math.floor((Date.now()+i.oauth.refreshTokenTimeoutMs)/1e3),tableauClientId:m.tableauClientId}),$t(()=>r.delete(w),i.oauth.refreshTokenTimeoutMs),e.delete(l),s.json({access_token:f,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3,refresh_token:w});return}case"client_credentials":{let l=await Ip({clientId:d.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,c=r.get(l);if(!c||c.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 m,{refreshToken:g}=c.tokens,w=await kp(c.server,g,c.tableauClientId);if(w.isErr())m=await $o({user:c.user,clientId:c.clientId,server:c.server,tokens:c.tokens},o);else{let{accessToken:b,refreshToken:y,expiresInSeconds:S}=w.value;m=await $o({user:c.user,clientId:c.clientId,server:c.server,tokens:{accessToken:b,refreshToken:y,expiresInSeconds:S}},o)}r.delete(l);let f=sa(32).toString("hex");r.set(f,{user:c.user,server:c.server,clientId:c.clientId,tokens:c.tokens,expiresAt:Math.floor((Date.now()+i.oauth.refreshTokenTimeoutMs)/1e3),tableauClientId:c.tableauClientId}),s.json({access_token:m,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 $o(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:Gt,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 na(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function Ip(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:Gt,iss:r.oauth.issuer});return await new na(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function kp(t,e,r){try{let o=await Pr(t,{grant_type:"refresh_token",refresh_token:e,client_id:r,site_namespace:""});return Qo(o)}catch{return De("Failed to exchange refresh token")}}function Dp({required:t,clientId:e,clientSecret:r,clientIdSecretPairs:o,authorizationHeader:i}){if(!e&&!r&&t){if(!i)return De("Authorization header is required");let[l,c]=i.split(" ");if(l!=="Basic")return De("Invalid authorization type");if([e,r]=Buffer.from(c,"base64").toString().split(":"),!e||!r)return De("Invalid client credentials")}if(!t)return Qo({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),d=s.encode(n);return a.byteLength!==d.byteLength||!Rp(a,d)?De("Invalid client credentials"):Qo({clientId:e})}var Dr="https://online.tableau.com",Gt="tableau-mcp-server",Lr=class{config=E();pendingAuthorizations=new Map;authorizationCodes=new Map;refreshTokens=new Map;privateKey;publicKey;constructor(){this.privateKey=this.getPrivateKey(),this.publicKey=Lp(this.privateKey)}get authMiddleware(){return Jn(this.privateKey)}setupRoutes(e){$n(e),Qn(e),ia(e),Yn(e,this.pendingAuthorizations),oa(e,this.pendingAuthorizations,this.authorizationCodes),aa(e,this.authorizationCodes,this.refreshTokens,this.publicKey)}getPrivateKey(){let e=this.config.oauth.jwePrivateKey.replace(/\\n/g,`
|
|
713
|
-
`);if(!e)try{e
|
|
1237
|
+
`),r.end();return}r.status(401).json({error:"invalid_token",error_description:s.error});return}e.auth=s.value,o()}}async function _m(t,e){let r=A();try{let{plaintext:o}=await Sm(t,e),i=JSON.parse(new TextDecoder().decode(o)),n=Yo.safeParse(i);if(!n.success)return Zt(`Invalid access token: ${va(n.error).toString()}`);let{iss:s,aud:a,exp:l,clientId:c}=n.data;if(s!==r.oauth.issuer||a!==Xt||l<Math.floor(Date.now()/1e3))return new Zt("Invalid or expired access token");let u;if(r.auth==="oauth"){let p=Sn.safeParse(i);if(!p.success)return Zt(`Invalid access token: ${va(p.error).toString()}`);let{tableauAccessToken:g,tableauRefreshToken:b,tableauExpiresAt:m,tableauUserId:y,tableauServer:T,sub:v}=p.data;if(m<Math.floor(Date.now()/1e3))return new Zt("Invalid or expired access token");u={username:v,userId:y,server:T,accessToken:g,refreshToken:b}}else{let{tableauUserId:p,tableauServer:g,sub:b}=n.data;u={username:b,server:g,...p?{userId:p}:{}}}return Em({token:t,clientId:c,scopes:[],expiresAt:i.exp,extra:u})}catch{return new Zt("Invalid or expired access token")}}import Ia from"axios-retry";import{randomBytes as mi,randomUUID as Pa}from"crypto";import{isIP as Rm}from"net";import{isSSRFSafeURL as xm}from"ssrfcheck";import{Err as Oe,Ok as Da}from"ts-results-es";import{fromError as ka}from"zod-validation-error";function Ra(t){try{return new URL(t)}catch{return}}function er(t,e,...r){return e>2147483647?setTimeout(()=>{er(t,e-2147483647,...r)},2147483647):setTimeout(t,e,...r)}var Br=new At({defaultExpirationTimeMs:ro});import{Resolver as vm}from"dns/promises";var zr=null;function xa(){return zr||(zr=new vm,zr.setServers(A().oauth.dnsServers)),zr}import{createHash as Cm}from"crypto";function Wr(t){return Cm("sha256").update(t).digest("base64url")}function Hr(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 La(t,e){let r=A();t.get("/oauth/authorize",async(o,i)=>{let n=Tn.safeParse(o.query);if(!n.success){i.status(400).json({error:"invalid_request",error_description:ka(n.error).toString()});return}let{client_id:s,redirect_uri:a,response_type:l,code_challenge:c,code_challenge_method:u,state:p}=n.data,g=Ra(s);if(g){let x=await Im(g);if(x.isErr()){i.status(400).json(x.error);return}let{redirect_uris:q,response_types:F}=x.value;if(F&&!F.find(te=>te===l)){i.status(400).json({error:"unsupported_response_type",error_description:`Unsupported response type: ${l}`});return}if(q&&!q.includes(a)){i.status(400).json({error:"invalid_request",error_description:`Invalid redirect URI: ${a}`});return}}if(l!=="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(!Hr(a)){i.status(400).json({error:"invalid_request",error_description:`Invalid redirect URI: ${a}`});return}let b=mi(32).toString("hex"),m=mi(32).toString("hex"),y=Pa(),T=Math.floor(Math.random()*43)+22,v=mi(T).toString("hex"),P=Wr(v);e.set(m,{clientId:s,redirectUri:a,codeChallenge:c,state:p??"",tableauState:b,tableauClientId:y,tableauCodeVerifier:v}),er(()=>e.delete(m),r.oauth.authzCodeTimeoutMs);let S=r.server||$r,C=new URL(`${S}/oauth2/v1/auth`);C.searchParams.set("client_id",y),C.searchParams.set("code_challenge",P),C.searchParams.set("code_challenge_method","S256"),C.searchParams.set("response_type","code"),C.searchParams.set("redirect_uri",r.oauth.redirectUri),C.searchParams.set("state",`${m}:${b}`),C.searchParams.set("device_id",Pa()),C.searchParams.set("target_site",r.siteName),C.searchParams.set("device_name",Pm(a,p??"")),C.searchParams.set("client_type","tableau-mcp"),i.redirect(C.toString())})}async function Im(t){let e=t.toString(),r=Br.get(e);if(r)return Da(r);let o=t.hostname;if(!Rm(t.hostname))try{let g=xa(),m=(await g.resolve4(t.hostname)).find(Boolean);if(!m&&(m=(await g.resolve6(t.hostname)).find(Boolean),!m))return Oe({error:"invalid_request",error_description:"IP address of Client Metadata URL could not be resolved"});t.hostname=m}catch{return Oe({error:"invalid_request",error_description:"IP address of Client Metadata URL could not be resolved"})}if(!xm(t.toString(),{allowedProtocols:["https"],autoPrependProtocol:!1}))return Oe({error:"invalid_request",error_description:"Client Metadata URL is not allowed"});let n;try{let g=qt.create();Ia(g,{retries:3,retryDelay:Ia.exponentialDelay}),n=await g.get(t.toString(),{timeout:5e3,maxContentLength:5*1024,maxRedirects:3,headers:{Accept:"application/json",Host:o}})}catch{return Oe({error:"invalid_request",error_description:"Unable to fetch client metadata"})}let s=Fo(n.headers,"content-type");if(!s)return Oe({error:"invalid_client_metadata",error_description:"Client Metadata URL must return a valid Content-Type header"});if(!s.split(";").map(g=>g.trim()).includes("application/json"))return Oe({error:"invalid_client_metadata",error_description:"Client Metadata URL must return a JSON response"});let l=En.safeParse(n.data);if(!l.success)return Oe({error:"invalid_client_metadata",error_description:`Client metadata is invalid: ${ka(l.error).toString()}`});if(l.data.client_id!==e)return Oe({error:"invalid_client_metadata",error_description:"Client ID mismatch"});let c=Fo(n.headers,"cache-control"),u;if(c){let g=c.split(",").map(b=>b.trim()).find(b=>/^max-age\s*=\s*\d+$/i.test(b));g&&(u=g.split("=")[1].trim())}let p=Br.defaultExpirationTimeMs;if(u){let g=parseInt(u);!isNaN(g)&&g>=0&&(p=Math.min(Ei,g*1e3))}return p>0&&Br.set(e,l.data,p),Da(l.data)}function Pm(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 Lm}from"crypto";import{Err as Mm,Ok as Om}from"ts-results-es";import{fromError as Nm}from"zod-validation-error";import{Zodios as km}from"@zodios/core";import{makeApi as Dm}from"@zodios/core";import{z as se}from"zod";var Ma=se.discriminatedUnion("grant_type",[se.object({grant_type:se.literal("authorization_code"),code:se.string(),code_verifier:se.string(),redirect_uri:se.string(),client_id:se.string()}),se.object({grant_type:se.literal("refresh_token"),client_id:se.string(),refresh_token:se.string(),site_namespace:se.string()})]),Oa=se.object({access_token:z("access_token"),expires_in:se.number().int().nonnegative(),refresh_token:z("refresh_token"),origin_host:z("origin_host")}).transform(t=>({accessToken:t.access_token,expiresInSeconds:t.expires_in,refreshToken:t.refresh_token,originHost:t.origin_host}));var Na=Dm([{method:"post",path:"/oauth2/v1/token",alias:"token",response:Oa,parameters:[{name:"body",type:"Body",schema:Ma}]}]);var Ua=t=>new km(t,Na);async function Gr(t,e){return await Ua(t).token(e,{headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":Dr}})}function Fa(t,e,r){let o=A();t.get("/Callback",async(i,n)=>{let s=An.safeParse(i.query);if(!s.success){n.status(400).json({error:"invalid_request",error_description:Nm(s.error).toString()});return}let{error:a,code:l,state:c}=s.data;if(a){n.status(400).json({error:"access_denied",error_description:"User denied authorization"});return}try{let[u,p]=c?.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 Um({server:o.server||$r,code:l??"",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:m,refreshToken:y,expiresInSeconds:T,originHost:v}=b.value,P=new URL(`https://${v}`);if(o.server){let te=new URL(o.server);if(P.hostname!==te.hostname){n.status(400).json({error:"invalid_request",error_description:`Invalid origin host: ${v}. Expected: ${new URL(o.server).hostname}`});return}}let S=P.toString(),C=new Le(S);C.setCredentials(m,"unknown user id");let x=await C.authenticatedServerMethods.getCurrentServerSession();if(x.isErr()){x.error.type==="unauthorized"?n.status(401).json({error:"unauthorized",error_description:`Unable to get the Tableau server session. Error: ${JSON.stringify(x.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 q=Lm(32).toString("hex");r.set(q,{clientId:g.clientId,redirectUri:g.redirectUri,codeChallenge:g.codeChallenge,user:x.value.user,server:S,tableauClientId:g.tableauClientId,tokens:{accessToken:m,refreshToken:y,expiresInSeconds:T},expiresAt:Math.floor((Date.now()+o.oauth.authzCodeTimeoutMs)/1e3)}),e.delete(u);let F=new URL(g.redirectUri);F.searchParams.set("code",q),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 Um({server:t,code:e,redirectUri:r,clientId:o,codeVerifier:i}){try{let n=await Gr(t,{grant_type:"authorization_code",code:e,redirect_uri:r,client_id:o,code_verifier:i});return Om(n)}catch{return Mm("Failed to exchange authorization code")}}import Fm from"express";function qa(t){t.post("/oauth/register",Fm.json(),(e,r)=>{let{redirect_uris:o}=e.body,i=[];if(o&&Array.isArray(o))for(let s of o){if(!Hr(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 ja,timingSafeEqual as qm}from"crypto";import{CompactEncrypt as Va}from"jose";import{Err as Ne,Ok as hi}from"ts-results-es";import{fromError as jm}from"zod-validation-error";function Ba(t,e,r,o){let i=A();t.post("/oauth/token",async(n,s)=>{let a=wn.safeParse(n.body);if(!a.success){s.status(400).json({error:"invalid_request",error_description:jm(a.error).toString()});return}let l=zm({required:a.data.grantType==="client_credentials",clientId:a.data.clientId,clientSecret:a.data.clientSecret,clientIdSecretPairs:A().oauth.clientIdSecretPairs,authorizationHeader:n.headers.authorization});if(l.isErr()){s.status(401).json({error:"invalid_client",error_description:l.error});return}try{switch(a.data.grantType){case"authorization_code":{let{code:c,codeVerifier:u}=a.data,p=e.get(c);if(!p||p.expiresAt<Math.floor(Date.now()/1e3)){e.delete(c),s.status(400).json({error:"invalid_grant",error_description:"Invalid or expired authorization code"});return}if(Wr(u)!==p.codeChallenge){s.status(400).json({error:"invalid_grant",error_description:"Invalid code verifier"});return}let b=ja(32).toString("hex"),m=await fi(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}),er(()=>r.delete(b),i.oauth.refreshTokenTimeoutMs),e.delete(c),s.json({access_token:m,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3,refresh_token:b});return}case"client_credentials":{let c=await Vm({clientId:l.value.clientId,server:i.server},o);s.json({access_token:c,token_type:"Bearer",expires_in:i.oauth.accessTokenTimeoutMs/1e3});return}case"refresh_token":{let{refreshToken:c}=a.data,u=r.get(c);if(!u||u.expiresAt<Math.floor(Date.now()/1e3)){r.delete(c),s.status(400).json({error:"invalid_grant",error_description:"Invalid or expired refresh token"});return}let p,{refreshToken:g}=u.tokens,b=await Bm(u.server,g,u.tableauClientId);if(b.isErr())p=await fi({user:u.user,clientId:u.clientId,server:u.server,tokens:u.tokens},o);else{let{accessToken:y,refreshToken:T,expiresInSeconds:v}=b.value;p=await fi({user:u.user,clientId:u.clientId,server:u.server,tokens:{accessToken:y,refreshToken:T,expiresInSeconds:v}},o)}r.delete(c);let m=ja(32).toString("hex");r.set(m,{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:m});return}}}catch(c){console.error("Token endpoint error:",c),s.status(500).json({error:"server_error",error_description:"Internal server error"});return}})}async function fi(t,e){let r=A(),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:Xt,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 Va(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function Vm(t,e){let r=A(),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:Xt,iss:r.oauth.issuer});return await new Va(new TextEncoder().encode(o)).setProtectedHeader({alg:"RSA-OAEP-256",enc:"A256GCM"}).encrypt(e)}async function Bm(t,e,r){try{let o=await Gr(t,{grant_type:"refresh_token",refresh_token:e,client_id:r,site_namespace:""});return hi(o)}catch{return Ne("Failed to exchange refresh token")}}function zm({required:t,clientId:e,clientSecret:r,clientIdSecretPairs:o,authorizationHeader:i}){if(!e&&!r&&t){if(!i)return Ne("Authorization header is required");let[c,u]=i.split(" ");if(c!=="Basic")return Ne("Invalid authorization type");if([e,r]=Buffer.from(u,"base64").toString().split(":"),!e||!r)return Ne("Invalid client credentials")}if(!t)return hi({clientId:""});if(!e)return Ne("Client ID is required");if(!r)return Ne("Client secret is required");let n=o?.[e];if(!n||r.length!==n.length)return Ne("Invalid client credentials");let s=new TextEncoder,a=s.encode(r),l=s.encode(n);return a.byteLength!==l.byteLength||!qm(a,l)?Ne("Invalid client credentials"):hi({clientId:e})}var $r="https://online.tableau.com",Xt="tableau-mcp-server",Qr=class{config=A();pendingAuthorizations=new Map;authorizationCodes=new Map;refreshTokens=new Map;privateKey;publicKey;constructor(){this.privateKey=this.getPrivateKey(),this.publicKey=Hm(this.privateKey)}get authMiddleware(){return Ca(this.privateKey)}setupRoutes(e){Ea(e),_a(e),qa(e),La(e,this.pendingAuthorizations),Fa(e,this.pendingAuthorizations,this.authorizationCodes),Ba(e,this.authorizationCodes,this.refreshTokens,this.publicKey)}getPrivateKey(){let e=this.config.oauth.jwePrivateKey.replace(/\\n/g,`
|
|
1238
|
+
`);if(!e)try{e=$m(this.config.oauth.jwePrivateKeyPath,"utf8")}catch{throw new Error("Failed to read private key file")}try{return Wm({key:e,format:"pem",passphrase:this.config.oauth.jwePrivateKeyPassphrase})}catch{throw new Error("Failed to create private key")}}};var yi="mcp-session-id";async function Qa({basePath:t,config:e,logLevel:r}){let o=gi();o.use(gi.json()),o.use(gi.urlencoded()),o.use(Km({origin:e.corsOriginConfig,credentials:!0,allowedHeaders:["Content-Type","Authorization","Cache-Control","Accept","MCP-Protocol-Version"],exposedHeaders:[yi,"x-session-id"]})),e.trustProxyConfig!==null&&o.set("trust proxy",e.trustProxyConfig);let i=[];if(e.oauth.enabled){let c=new Qr;c.setupRoutes(o),i.push(c.authMiddleware),i.push(Sa)}let n=`/${t}`;if(o.post(n,...i,l),o.get(n,...i,e.disableSessionManagement?$a:Ga),o.delete(n,...i,e.disableSessionManagement?$a:Ga),!!!(e.sslKey&&e.sslCert))return new Promise(c=>{let u=Jm.createServer(o).listen(e.httpPort,()=>c({url:`http://localhost:${e.httpPort}/${t}`,app:o,server:u}))});if(!Wa(e.sslKey))throw new Error("SSL key file does not exist");if(!Wa(e.sslCert))throw new Error("SSL cert file does not exist");let a={key:za.readFileSync(e.sslKey),cert:za.readFileSync(e.sslCert)};return new Promise(c=>{let u=Ym.createServer(a,o).listen(e.httpPort,()=>c({url:`https://localhost:${e.httpPort}/${t}`,app:o,server:u}))});async function l(c,u){try{let p;if(e.disableSessionManagement){let g=new Xe;p=new Gm({sessionIdGenerator:void 0}),u.on("close",()=>{p.close(),g.close()}),await Ha(g,p,r,M(c.auth))}else{let g=c.headers[yi],b;if(g&&(b=pi(g)))p=b.transport;else if(!g&&Qm(c.body)){let m=c.body.params.clientInfo;p=Aa({clientInfo:m});let y=new Xe({clientInfo:m});await Ha(y,p,r,M(c.auth))}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(c,u,c.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 Ha(t,e,r,o){await t.registerTools(o),t.registerRequestHandlers(),await t.connect(e),et(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 Ga(t,e){let r=t.headers[yi],o;if(!r||!(o=pi(r))){e.status(400).send("Invalid or missing session ID");return}await o.transport.handleRequest(t,e)}async function ef(){Xm.config();let t=A(),e=vi(t.defaultLogLevel)?t.defaultLogLevel:"debug";switch(t.enableServerLogging&&Ci(new rr({logDirectory:t.serverLogDirectory})),t.transport){case"stdio":{let r=new Xe;await r.registerTools(),r.registerRequestHandlers();let o=new Zm;await r.connect(o),et(r,e),ue.info(r,`${r.name} v${r.version} running on stdio`);break}case"http":{let{url:r}=await Qa({basePath:Me,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(`${Me} v${Yt} ${t.disableSessionManagement?"stateless ":""}streamable HTTP server available at ${r}`);break}}t.disableLogMasking&&Fe("\u26A0\uFE0F Log masking is disabled!")}try{await ef()}catch(t){Fe(`Fatal error when starting the server: ${V(t)}`),process.exit(1)}
|
|
714
1239
|
/* v8 ignore file -- @preserve */
|
|
715
1240
|
//# sourceMappingURL=index.js.map
|