UNPKG

qlik

Version:

A collection of helpful utilities for using the Qlik Capability APIs

3 lines (2 loc) 13.1 kB
function e(e,t,i,s){return new(i||(i=Promise))(function(n,o){function r(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(r,a)}l((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;const t="api/v1/audits";class i{constructor(e){this.docList=[],this.currApps=[];const{host:t,port:i,prefix:s="/",isSecure:n,ticket:o,webIntegrationId:r="",isCssRequired:a=!0}=e;this.isCssRequired=!1!==a;const l=n?"https://":"http://",c=i?`:${i}`:"";this.config=e,this.ticket=o,this.isSaaS=!!r,this.webIntegrationId=r,this.baseUrl=`${l}${t}${c}${s}resources`,this.saasURL=`${l}${t}${c}${s}`}appendScript(e,t){return new Promise((i,s)=>{const n=document.createElement("script");n.src=e,n.id=t,n.onload=()=>i(),n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}appendStylesheet(e){return new Promise((t,i)=>{const s=document.querySelector('link[href*="qlik-styles.css"]');s&&s.remove();const n=document.createElement("link");n.href=e,n.type="text/css",n.rel="stylesheet",n.onload=()=>{const e=document.createElement("div");e.id="qlik-style-container",document.body.appendChild(e),t()},n.onerror=()=>i(new Error(`Failed to load stylesheet: ${e}`)),document.head.prepend(n)})}callRequire(){return e(this,void 0,void 0,function*(){if(document.getElementById("qlik-require-file"))return;const e=this.ticket?`${this.baseUrl}/assets/external/requirejs/require.js?${this.ticket}`:`${this.baseUrl}/assets/external/requirejs/require.js`;if(yield this.appendScript(e,"qlik-require-file"),this.isCssRequired){const e=this.ticket?`${this.baseUrl}/autogenerated/qlik-styles.css?${this.ticket}`:`${this.baseUrl}/autogenerated/qlik-styles.css`;yield this.appendStylesheet(e)}window.Promise||(yield this.appendScript(`${this.baseUrl}/assets/external/es6-promise/es6-promise.auto.js`,"es6-promise"))})}setQlik(){return e(this,void 0,void 0,function*(){return yield this.callRequire(),new Promise((e,t)=>{window.require.config({baseUrl:this.baseUrl,paths:{qlik:`${this.baseUrl}/js/qlik`},config:{text:{useXhr:()=>!0}},webIntegrationId:this.isSaaS?this.webIntegrationId:"",waitSeconds:20,onError:e=>{console.error("Failed to load Qlik module:",e),t(e)}}),window.require(["js/qlik"],i=>{i?(i.setOnError(e=>{console.error("Qlik engine error:",e)}),this.qlik=i,e(i)):t(new Error("Failed to initialize Qlik"))})})})}fetchAPI(e,t="GET",i=null){const s={"Content-Type":"application/json"};return this.isSaaS?s["qlik-web-integration-id"]=this.webIntegrationId:this.ticket&&(s["X-Qlik-Session"]=this.ticket),fetch(e,{method:t,mode:"cors",credentials:"include",headers:s,body:i?JSON.stringify(i):null}).then(e=>e.ok?e.json():Promise.reject(new Error(`HTTP ${e.status}: ${e.statusText}`)))}fetchEnterpriseAPI(e,t="GET",i=null){const s=`${this.saasURL}${e}`;return this.fetchAPI(s,t,i)}openAuthPopup(i){return e(this,arguments,void 0,function*(i,s=600,n=600){return new Promise((o,r)=>{const a=window.screenX+(window.outerWidth-s)/2,l=window.screenY+(window.outerHeight-n)/2,c=window.open(i,"QlikLogin",`width=${s},height=${n},left=${a},top=${l}`);if(!c)return void r(new Error("Failed to open authentication popup. Please allow popups for this site."));const d=setTimeout(()=>{f(),r(new Error("Authentication popup timed out after 5 minutes"))},3e5),h=setInterval(()=>e(this,void 0,void 0,function*(){try{200===(yield fetch(`${this.saasURL}${t}`,{credentials:"include",headers:{"Qlik-Web-Integration-ID":this.webIntegrationId}})).status&&(f(),c.closed||c.close(),yield this.setAuthUser(),o(this.user))}catch(e){}}),1e3),u=setInterval(()=>{c.closed&&(f(),this.checkAuthStatus().then(o).catch(r))},500),p=e=>{var t;e.origin===this.saasURL&&"qlik-auth-success"===(null===(t=e.data)||void 0===t?void 0:t.type)&&(f(),c.closed||c.close(),o(e.data.user))},f=()=>{clearInterval(h),clearInterval(u),clearTimeout(d),window.removeEventListener("message",p)};window.addEventListener("message",p)})})}checkAuthStatus(){return e(this,void 0,void 0,function*(){try{if(200===(yield fetch(`${this.saasURL}${t}`,{credentials:"include",headers:{"Qlik-Web-Integration-ID":this.webIntegrationId}})).status)return yield this.setAuthUser(),this.user;throw new Error("Authentication failed")}catch(e){throw console.error("Authentication status check failed:",e),e}})}isAuthenticated(){return e(this,void 0,void 0,function*(){if(this.isSaaS)try{return 200===(yield fetch(`${this.saasURL}${t}`,{credentials:"include",headers:{"Qlik-Web-Integration-ID":this.webIntegrationId}})).status}catch(e){return!1}else try{return!!(yield this.fetchEnterpriseAPI("api/hub/v1/user/info"))}catch(e){return!1}})}authenticateToQlik(){return e(this,void 0,void 0,function*(){var e;if(this.isSaaS)try{const i=yield fetch(`${this.saasURL}${t}`,{credentials:"include",headers:{"Qlik-Web-Integration-ID":this.webIntegrationId}});if(200===i.status)return void(yield this.setAuthUser());if(401===i.status){const t=new URL(`${this.saasURL}login`);if(t.searchParams.append("qlik-web-integration-id",this.webIntegrationId),"popup"===(null===(e=this.config.auth)||void 0===e?void 0:e.method)){const{popupWidth:e=600,popupHeight:i=600}=this.config.auth;yield this.openAuthPopup(t.toString(),e,i),this.config.auth.loginCallback&&this.config.auth.loginCallback(this.user)}else t.searchParams.append("returnto",window.location.origin),window.location.href=t.toString()}}catch(e){throw console.error("Authentication failed:",e),e}else try{yield this.fetchEnterpriseAPI("api/hub/v1/user/info")}catch(e){throw console.error("Enterprise authentication failed:",e),this.config.loginUri&&(window.location.href=this.config.loginUri),e}})}setAuthUser(){return e(this,void 0,void 0,function*(){if(this.isSaaS)try{const e=yield this.fetchAPI(`${this.saasURL}api/v1/users/me`),t=yield this.fetchAPI(`${this.saasURL}api/v1/tenants/me`);this.user=Object.assign(Object.assign({directory:t.name,userId:e.name},e),{tenant:t})}catch(e){throw console.error("Failed to set SaaS user info:",e),e}else try{const e=yield this.fetchEnterpriseAPI("api/hub/v1/user/info"),t=e.data?e.data[0]:e,{userDirectory:i,userId:s}=t.attributes||t;this.user={directory:i,userId:s,authUser:t}}catch(e){throw console.error("Failed to set Enterprise user info:",e),e}})}getMoreData(t){return e(this,void 0,void 0,function*(){var e,i;let s=Object.assign({},t),n=t.data;for(;null===(i=null===(e=s.links)||void 0===e?void 0:e.next)||void 0===i?void 0:i.href;){const e=yield this.fetchAPI(s.links.next.href);n=n.concat(e.data),s=e}return Object.assign(Object.assign({},s),{data:n})})}getSpace(t){return e(this,void 0,void 0,function*(){if(!this.isSaaS)throw new Error("Spaces are only available in Qlik Sense SaaS");return this.fetchAPI(`${this.saasURL}api/v1/spaces/${t}`)})}getSpaceList(){return e(this,void 0,void 0,function*(){if(!this.isSaaS)throw new Error("Spaces are only available in Qlik Sense SaaS");const e=yield this.fetchAPI(`${this.saasURL}api/v1/spaces?limit=100&type=managed,shared`);return(yield this.getMoreData(e)).data})}getUserList(){return e(this,void 0,void 0,function*(){if(!this.isSaaS){const e=yield this.fetchEnterpriseAPI("api/hub/v1/users");return e.data||e}const e=yield this.fetchAPI(`${this.saasURL}api/v1/users?limit=100`);return(yield this.getMoreData(e)).data})}getAppList(){return e(this,void 0,void 0,function*(){if(!this.isSaaS)return new Promise(e=>{this.qlik.getAppList(t=>{e(t)})});const e=yield this.fetchAPI(`${this.saasURL}api/v1/items?limit=100&resourceType=app`);return(yield this.getMoreData(e)).data})}getThemeList(){return e(this,void 0,void 0,function*(){if(!this.isSaaS){const e=yield this.fetchEnterpriseAPI("api/hub/v1/themes");return e.data||e}const e=yield this.fetchAPI(`${this.saasURL}api/v1/themes`);return(yield this.getMoreData(e)).data})}getDocs(){return e(this,void 0,void 0,function*(){if(!this.qlik)throw new Error("Qlik is not initialized. Call setQlik() first.");return new Promise((e,t)=>{try{this.qlik.getAppList(t=>{this.docList=t,e(t)},this.config)}catch(e){t(e)}})})}getList(t,i){return e(this,void 0,void 0,function*(){return new Promise(e=>{t.getList(i,i=>{e(i),t.destroySessionObject(i.qInfo.qId)})})})}getMeasure(t){return e(this,void 0,void 0,function*(){return(yield this.getList(t,"MeasureList")).qMeasureList.qItems})}getVariable(t){return e(this,void 0,void 0,function*(){return(yield this.getList(t,"VariableList")).qVariableList.qItems})}getFields(t){return e(this,void 0,void 0,function*(){return(yield this.getList(t,"FieldList")).qFieldList.qItems})}getBookmark(t){return e(this,void 0,void 0,function*(){return(yield this.getList(t,"BookmarkList")).qBookmarkList.qItems})}evaluateExpression(t,i){return e(this,void 0,void 0,function*(){return new Promise(e=>{var s;i&&" "!==i&&"object"==typeof i?t.createGenericObject({value:{qStringExpression:null===(s=i.qStringExpression)||void 0===s?void 0:s.qExpr}},i=>{e(i.value),t.destroySessionObject(i.qInfo.qId)}):e(i)})})}objectProper(t,i){return e(this,void 0,void 0,function*(){const e=i.properties,s={title:null,subtitle:null,footnote:null};return s.title=yield this.evaluateExpression(t,e.title),s.subtitle=yield this.evaluateExpression(t,e.subtitle),s.footnote=yield this.evaluateExpression(t,e.footnote),s})}getQlikObjectTitles(t,i){return e(this,void 0,void 0,function*(){const e=yield t.getObjectProperties(i);if(e.properties.qExtendsId){const i=yield t.getObjectProperties(e.properties.qExtendsId);return this.objectProper(t,i)}return this.objectProper(t,e)})}getSheet(t){return e(this,void 0,void 0,function*(){const i=yield this.getList(t,"sheet");return Promise.all(i.qAppObjectList.qItems.map(i=>e(this,void 0,void 0,function*(){const s=yield Promise.all(i.qData.cells.map(i=>e(this,void 0,void 0,function*(){const e=yield this.getQlikObjectTitles(t,i.name);return Object.assign(Object.assign({},i),{options:e,obj_id:i.name,id:i.name,title:e.title||e.subtitle||e.footnote||i.name})})));return Object.assign(Object.assign({},i),{name:i.qMeta.title,id:i.qInfo.qId,obj:s})})))})}callObject(t,i){return e(this,void 0,void 0,function*(){var e;if(null===(e=t.visualization)||void 0===e?void 0:e.get)return t.visualization.get(i).catch(e=>{throw console.error("Failed to call object:",e),e});throw new Error("Visualization API not available on this app")})}checkAppOpen(t){return e(this,void 0,void 0,function*(){return yield t.model.waitForOpen.promise,t})}setupEngineConnectionMonitoring(e){e.model.engineVersion().then(e=>{console.log("Connected to Qlik Engine version:",e)}),e.model.on("changed",()=>{console.debug("Engine connection: Model changed")}),e.model.on("closed",()=>{console.warn("Engine connection: Model closed");this.currApps.find(t=>t.app===e)&&this.isAppOpen(e.id).catch(console.error)}),e.model.on("suspended",()=>{console.warn("Engine connection: Model suspended")}),e.model.on("restored",()=>{console.log("Engine connection: Model restored")})}getSessionKey(e){return`qlik_session_${this.config.host}_${e}`}saveSessionState(e){var t;if(!e||!e.id)return;const i=this.getSessionKey(e.id),s={timestamp:Date.now(),selections:(null===(t=e.selectionState)||void 0===t?void 0:t.qSelections)||[],variables:{}},n=this.currApps.find(t=>t.app===e);(null==n?void 0:n.variable)&&n.variable.forEach(t=>{t.qName&&e.variable.getContent(t.qName,e=>{s.variables[t.qName]=e.qContent.qString})});try{sessionStorage.setItem(i,JSON.stringify(s))}catch(e){console.warn("Failed to save session state:",e)}}restoreSessionState(t){return e(this,void 0,void 0,function*(){var e,i;if(!t||!t.id)return;const s=this.getSessionKey(t.id);try{const n=sessionStorage.getItem(s);if(!n)return;const o=JSON.parse(n);if(Date.now()-o.timestamp>864e5)return void sessionStorage.removeItem(s);if(null===(e=o.selections)||void 0===e?void 0:e.length)for(const e of o.selections)if(e.field&&(null===(i=e.values)||void 0===i?void 0:i.length)){const i=t.field(e.field);yield i.selectValues(e.values,!1)}for(const[e,i]of Object.entries(o.variables))t.variable.setContent(e,String(i))}catch(e){console.warn("Failed to restore session state:",e)}})}isAppOpen(t){return e(this,void 0,void 0,function*(){const e=Object.assign(Object.assign({},this.config),{openWithoutData:!0,noData:!1,secure:this.config.isSecure}),i=this.qlik.openApp(t,e);this.setupEngineConnectionMonitoring(i),i.model.on("changed",()=>{this.saveSessionState(i)});const s=yield this.checkAppOpen(i);return yield this.restoreSessionState(s),s})}getApp(t){return e(this,void 0,void 0,function*(){this.user||(yield this.authenticateToQlik());if(!this.currApps.find(e=>e.app.id===t))try{const e=yield this.isAppOpen(t),[i,s,n,o,r]=yield Promise.all([this.getSheet(e),this.getMeasure(e),this.getFields(e),this.getVariable(e),this.getBookmark(e)]);this.currApps=[{id:t,app:e,sheet:i,measure:s,fields:n,variable:o,bookmark:r},...this.currApps],e.model.on("error",e=>{console.error("App model error:",e)})}catch(e){throw console.error("Failed to open app:",e),e}return this.currApps})}}export{i as default}; //# sourceMappingURL=index.mjs.map