codicent-app-sdk 0.3.56 → 0.3.57
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/dist/cjs/services/codicent.d.ts +1 -0
- package/dist/cjs/services/codicent.d.ts.map +1 -1
- package/dist/cjs/services/codicent.js +1 -1
- package/dist/esm/services/codicent.d.ts +1 -0
- package/dist/esm/services/codicent.d.ts.map +1 -1
- package/dist/esm/services/codicent.js +1 -1
- package/dist/index.d.ts +1 -0
- package/package.json +1 -1
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;
|
1
|
+
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EA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O,CAAC,MAAM,CAAC,CAgB9D;IAEF,kBAAkB,YAAmB,MAAM,mBAUzC;IAEF,cAAc,OAAc,MAAM,wBAehC;IAEF,aAAa,aAAoB,MAAM,wBAgBrC;IAEF,iBAAiB,OAAc,MAAM;;;OAcnC;IAEF,SAAS,YAAmB,MAAM,YAAY,MAAM,qBAqBlD;IAEF,SAAS,+BAqCP;IAEF,YAAY,+BAeV;IAEF,MAAM,CAAC,YAAY,SAAgB,QAAQ,mBAyBzC;IAEF,MAAM,CAAC,gBAAgB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCAyBrG;IAEF,QAAQ;cAMkB,MAAM;gBAAU,MAAM;eAAS,MAAM;SAC7D;IAEF,WAAW,OAAc,MAAM,kBAO7B;IAGF,OAAO,CAAC,kBAAkB;CAK3B"}
|
@@ -1 +1 @@
|
|
1
|
-
"use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),a=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let o="https://codicent.com/",n="-";const i=()=>void 0!==window.Codicent&&(window.Codicent.init({token:n,baseUrl:o}),!0);let s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new a.default(t.content).content.split("\n"),o=e[0],n=e.slice(1).join("\n");return{id:t.id,title:o,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,a=100,n=void 0)=>{const i=await fetch(`${o}app/AppGetMessages`,{method:"POST",headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:a})});if(!i.ok)throw 401===i.status&&this.handleUnauthorized(),new Error(`${i.statusText}`);let s=await i.json();if(s.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);s=s.concat(t),s.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return s},this.getMessages=async(t,e)=>{let a=[];for(const e of t){const t=await window.Codicent.getMessages({search:`@${this.codicent} #${e}`,length:10});"chat"===e&&t.forEach((t=>t.content=`#chat\n${t.content}`)),a=a.concat(t)}if(e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,a)=>e===a.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,a,n)=>{const i=await fetch(`${o}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:a})});if(!i.ok)return"";const s=await i.text();return window.Codicent.init({token:n,baseUrl:o}),s},this.loginUser=async(t,e)=>{try{const a=await fetch(`${o}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!a.ok)return 404===a.status||400===a.status?null:401===a.status?(this.handleUnauthorized(),null):"";const n=await a.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${o}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${o}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,a)=>e===a.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const a=await fetch(`${o}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw a.status,new Error(`${a.statusText||"Failed to add follower!"}`);return await a.json()},this.cloneProject=async(t,e)=>{const a=await fetch(`${o}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw a.status,new Error(`${a.statusText}`);let n=await a.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),a=JSON.parse(e),i=a.sub||a.userId,s=await fetch(`${o}app/GetNickname?userId=${i}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!s.ok)throw 401===s.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${s.statusText}`);return await s.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),a=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==a&&(console.log("updating instructions",a),await window.Codicent.postMessage({message:a,type:"text",parentId:e[0].id})):(console.log("new instructions",a),await window.Codicent.postMessage({message:a,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const a=await fetch(`${o}/app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw 401===a.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${a.statusText}`);const n=await a.json(),{email:i,picture:s,description:r,followers:c,properties:h}=n;return{nickname:t,email:i,name:r,picture:s,followers:c,properties:h}},this.updateUserInfo=async({nickname:t,email:e,name:a,picture:n})=>{const i=await fetch(`${o}/app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:a,picture:n,description:""})});if(!i.ok)throw i.status,new Error(`${i.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const a=await fetch(`${o}/app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!a.ok||(console.warn(`requestInvite() => ${a.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const a=await fetch(`${o}/app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!a.ok||(console.warn(`updateMembersAccess() => ${a.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:o})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${o}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${o}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${o}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:a}=await e.json();return a},this.redirectToCheckout=async t=>{const a=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!a)throw new Error("Stripe failed to load");const o=await this.createCheckoutSession(t),{error:n}=await a.redirectToCheckout({sessionId:o});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${o}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let a=await e.json();return a=a.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),a},this.getPublicFlow=async t=>{const e=await fetch(`${o}/app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const a=await e.json();return a.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a},this.getMessageContent=async t=>{const e=await fetch(`${o}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const a={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${o}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(a)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],a=atob(t),o=JSON.parse(a).nickname;if(!await this.addFollower(e,o))throw new Error("Failed to add follower: "+o)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await fetch(`${o}app/GetForms?codicent=${this.codicent}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${o}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.codicent="",this.options=t}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}t=r,r.getImageUrl=(t,e)=>`${o}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${o}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const a=window.URL.createObjectURL(t),o=document.createElement("a");o.style.display="none",o.href=a,o.download=e.filename,document.body.appendChild(o),o.click(),window.URL.revokeObjectURL(a)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReply=async(t,e="codicent-mini",a)=>{const n=await fetch(`${o}app/GetAi2ChatReply?message=${t}&project=${e}${a?"&messageId="+a:""}`,{method:"GET",headers:[["Authorization","Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjJlMTliNjNmLWQxNDgtNGRmMi04MzMxLTZlZGE3ZTQzNjQ1ZCIsIm5pY2tuYW1lIjoiam9oYW4iLCJuYW1lIjoiSm9oYW4gSXNha3Nzb24iLCJ1c2VySWQiOiIyZTE5YjYzZi1kMTQ4LTRkZjItODMzMS02ZWRhN2U0MzY0NWQiLCJwcm9qZWN0IjoiY29kaWNlbnQtbWluaSIsIm5iZiI6MTczNjkzMjcyOCwiZXhwIjoxNzY4NDY4NzI4LCJpYXQiOjE3MzY5MzI3Mjh9.l2J7GgfU01iihdud7QP1aYBCM3NgxxqiM4VrplLO1s0"]]});if(!n.ok)return void n.status;return(await n.json()).content.replace("@codicent-mini","").trim()},exports.CodicentService=r;
|
1
|
+
"use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),a=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let o="https://codicent.com/",n="-";const i=()=>void 0!==window.Codicent&&(window.Codicent.init({token:n,baseUrl:o}),!0);let s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new a.default(t.content).content.split("\n"),o=e[0],n=e.slice(1).join("\n");return{id:t.id,title:o,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,a=100,n=void 0)=>{const i=await fetch(`${o}app/AppGetMessages`,{method:"POST",headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:a})});if(!i.ok)throw 401===i.status&&this.handleUnauthorized(),new Error(`${i.statusText}`);let s=await i.json();if(s.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);s=s.concat(t),s.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return s},this.getMessages=async(t,e)=>{let a=[];for(const e of t){const t=await window.Codicent.getMessages({search:`@${this.codicent} #${e}`,length:10});"chat"===e&&t.forEach((t=>t.content=`#chat\n${t.content}`)),a=a.concat(t)}if(e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,a)=>e===a.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,a,n)=>{const i=await fetch(`${o}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:a})});if(!i.ok)return"";const s=await i.text();return window.Codicent.init({token:n,baseUrl:o}),s},this.loginUser=async(t,e)=>{try{const a=await fetch(`${o}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!a.ok)return 404===a.status||400===a.status?null:401===a.status?(this.handleUnauthorized(),null):"";const n=await a.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${o}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${o}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,a)=>e===a.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const a=await fetch(`${o}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw a.status,new Error(`${a.statusText||"Failed to add follower!"}`);return await a.json()},this.cloneProject=async(t,e)=>{const a=await fetch(`${o}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw a.status,new Error(`${a.statusText}`);let n=await a.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),a=JSON.parse(e),i=a.sub||a.userId,s=await fetch(`${o}app/GetNickname?userId=${i}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!s.ok)throw 401===s.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${s.statusText}`);return await s.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),a=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==a&&(console.log("updating instructions",a),await window.Codicent.postMessage({message:a,type:"text",parentId:e[0].id})):(console.log("new instructions",a),await window.Codicent.postMessage({message:a,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const a=await fetch(`${o}/app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)throw 401===a.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${a.statusText}`);const n=await a.json(),{email:i,picture:s,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:i,name:r,picture:s,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:a,picture:n})=>{const i=await fetch(`${o}/app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:a,picture:n,description:""})});if(!i.ok)throw i.status,new Error(`${i.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const a=await fetch(`${o}/app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!a.ok||(console.warn(`requestInvite() => ${a.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const a=await fetch(`${o}/app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!a.ok||(console.warn(`updateMembersAccess() => ${a.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:o})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${o}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${o}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${o}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:a}=await e.json();return a},this.redirectToCheckout=async t=>{const a=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!a)throw new Error("Stripe failed to load");const o=await this.createCheckoutSession(t),{error:n}=await a.redirectToCheckout({sessionId:o});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${o}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let a=await e.json();return a=a.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),a},this.getPublicFlow=async t=>{const e=await fetch(`${o}/app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const a=await e.json();return a.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),a},this.getMessageContent=async t=>{const e=await fetch(`${o}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const a={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${o}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(a)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],a=atob(t),o=JSON.parse(a).nickname;if(!await this.addFollower(e,o))throw new Error("Failed to add follower: "+o)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await fetch(`${o}app/GetForms?codicent=${this.codicent}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${o}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.codicent="",this.options=t}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}t=r,r.getImageUrl=(t,e)=>`${o}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${o}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const a=window.URL.createObjectURL(t),o=document.createElement("a");o.style.display="none",o.href=a,o.download=e.filename,document.body.appendChild(o),o.click(),window.URL.revokeObjectURL(a)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReply=async(t,e="codicent-mini",a)=>{const n=await fetch(`${o}app/GetAi2ChatReply?message=${t}&project=${e}${a?"&messageId="+a:""}`,{method:"GET",headers:[["Authorization","Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjJlMTliNjNmLWQxNDgtNGRmMi04MzMxLTZlZGE3ZTQzNjQ1ZCIsIm5pY2tuYW1lIjoiam9oYW4iLCJuYW1lIjoiSm9oYW4gSXNha3Nzb24iLCJ1c2VySWQiOiIyZTE5YjYzZi1kMTQ4LTRkZjItODMzMS02ZWRhN2U0MzY0NWQiLCJwcm9qZWN0IjoiY29kaWNlbnQtbWluaSIsIm5iZiI6MTczNjkzMjcyOCwiZXhwIjoxNzY4NDY4NzI4LCJpYXQiOjE3MzY5MzI3Mjh9.l2J7GgfU01iihdud7QP1aYBCM3NgxxqiM4VrplLO1s0"]]});if(!n.ok)return void n.status;return(await n.json()).content.replace("@codicent-mini","").trim()},exports.CodicentService=r;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;
|
1
|
+
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACzB,aAAa,E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,MAAM;;;OAcnC;IAEF,SAAS,YAAmB,MAAM,YAAY,MAAM,qBAqBlD;IAEF,SAAS,+BAqCP;IAEF,YAAY,+BAeV;IAEF,MAAM,CAAC,YAAY,SAAgB,QAAQ,mBAyBzC;IAEF,MAAM,CAAC,gBAAgB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCAyBrG;IAEF,QAAQ;cAMkB,MAAM;gBAAU,MAAM;eAAS,MAAM;SAC7D;IAEF,WAAW,OAAc,MAAM,kBAO7B;IAGF,OAAO,CAAC,kBAAkB;CAK3B"}
|
@@ -1 +1 @@
|
|
1
|
-
import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const i=()=>void 0!==window.Codicent&&(window.Codicent.init({token:n,baseUrl:a}),!0);let s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const i=await fetch(`${a}app/AppGetMessages`,{method:"POST",headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});if(!i.ok)throw 401===i.status&&this.handleUnauthorized(),new Error(`${i.statusText}`);let s=await i.json();if(s.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);s=s.concat(t),s.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return s},this.getMessages=async(t,e)=>{let o=[];for(const e of t){const t=await window.Codicent.getMessages({search:`@${this.codicent} #${e}`,length:10});"chat"===e&&t.forEach((t=>t.content=`#chat\n${t.content}`)),o=o.concat(t)}if(e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const i=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const s=await i.text();return window.Codicent.init({token:n,baseUrl:a}),s},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),i=o.sub||o.userId,s=await fetch(`${a}app/GetNickname?userId=${i}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!s.ok)throw 401===s.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${s.statusText}`);return await s.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}/app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:i,picture:s,description:r,followers:c,properties:h}=n;return{nickname:t,email:i,name:r,picture:s,followers:c,properties:h}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const i=await fetch(`${a}/app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!i.ok)throw i.status,new Error(`${i.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}/app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}/app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}/app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await fetch(`${a}app/GetForms?codicent=${this.codicent}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.codicent="",this.options=o}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}o=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReply=async(t,e="codicent-mini",o)=>{const n=await fetch(`${a}app/GetAi2ChatReply?message=${t}&project=${e}${o?"&messageId="+o:""}`,{method:"GET",headers:[["Authorization","Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjJlMTliNjNmLWQxNDgtNGRmMi04MzMxLTZlZGE3ZTQzNjQ1ZCIsIm5pY2tuYW1lIjoiam9oYW4iLCJuYW1lIjoiSm9oYW4gSXNha3Nzb24iLCJ1c2VySWQiOiIyZTE5YjYzZi1kMTQ4LTRkZjItODMzMS02ZWRhN2U0MzY0NWQiLCJwcm9qZWN0IjoiY29kaWNlbnQtbWluaSIsIm5iZiI6MTczNjkzMjcyOCwiZXhwIjoxNzY4NDY4NzI4LCJpYXQiOjE3MzY5MzI3Mjh9.l2J7GgfU01iihdud7QP1aYBCM3NgxxqiM4VrplLO1s0"]]});if(!n.ok)return void n.status;return(await n.json()).content.replace("@codicent-mini","").trim()};export{r as CodicentService};
|
1
|
+
import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const i=()=>void 0!==window.Codicent&&(window.Codicent.init({token:n,baseUrl:a}),!0);let s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e)=>await window.Codicent.data.create({codicent:this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e)=>await window.Codicent.data.read({codicent:this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e)=>await window.Codicent.data.update({id:t,data:e,codicent:this.codicent}),this.deleteDataMessage=async t=>await window.Codicent.data.delete({id:t,codicent:this.codicent}),this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.sendMessage=(t,e)=>window.Codicent.postMessage({message:`@${this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e)=>window.Codicent.getChatReply3({message:t,codicent:this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0)=>{const i=await fetch(`${a}app/AppGetMessages`,{method:"POST",headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:this.codicent,search:e,length:o})});if(!i.ok)throw 401===i.status&&this.handleUnauthorized(),new Error(`${i.statusText}`);let s=await i.json();if(s.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);s=s.concat(t),s.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return s},this.getMessages=async(t,e)=>{let o=[];for(const e of t){const t=await window.Codicent.getMessages({search:`@${this.codicent} #${e}`,length:10});"chat"===e&&t.forEach((t=>t.content=`#chat\n${t.content}`)),o=o.concat(t)}if(e)try{const t=await this.getPublicFlow(e);o=o.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return o=o.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,o,n)=>{const i=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!i.ok)return"";const s=await i.text();return window.Codicent.init({token:n,baseUrl:a}),s},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),i=o.sub||o.userId,s=await fetch(`${a}app/GetNickname?userId=${i}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!s.ok)throw 401===s.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${s.statusText}`);return await s.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}/app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:i,picture:s,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:i,name:r,picture:s,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const i=await fetch(`${a}/app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!i.ok)throw i.status,new Error(`${i.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}/app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}/app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({priceId:t,successUrl:window.location.href,cancelUrl:window.location.href})});if(!e.ok)throw new Error("Failed to create checkout session");const{id:o}=await e.json();return o},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}/app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await fetch(`${a}app/GetForms?codicent=${this.codicent}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.codicent="",this.options=o}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}}o=r,r.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,r.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,r.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},r.getMiniChatReply=async(t,e="codicent-mini",o)=>{const n=await fetch(`${a}app/GetAi2ChatReply?message=${t}&project=${e}${o?"&messageId="+o:""}`,{method:"GET",headers:[["Authorization","Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjJlMTliNjNmLWQxNDgtNGRmMi04MzMxLTZlZGE3ZTQzNjQ1ZCIsIm5pY2tuYW1lIjoiam9oYW4iLCJuYW1lIjoiSm9oYW4gSXNha3Nzb24iLCJ1c2VySWQiOiIyZTE5YjYzZi1kMTQ4LTRkZjItODMzMS02ZWRhN2U0MzY0NWQiLCJwcm9qZWN0IjoiY29kaWNlbnQtbWluaSIsIm5iZiI6MTczNjkzMjcyOCwiZXhwIjoxNzY4NDY4NzI4LCJpYXQiOjE3MzY5MzI3Mjh9.l2J7GgfU01iihdud7QP1aYBCM3NgxxqiM4VrplLO1s0"]]});if(!n.ok)return void n.status;return(await n.json()).content.replace("@codicent-mini","").trim()};export{r as CodicentService};
|
package/dist/index.d.ts
CHANGED