codicent-app-sdk 0.3.108 → 0.3.109
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 +2 -2
- 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 +2 -2
- package/dist/esm/services/codicent.d.ts.map +1 -1
- package/dist/esm/services/codicent.js +1 -1
- package/dist/index.d.ts +2 -2
- package/package.json +1 -1
|
@@ -46,7 +46,7 @@ export interface CodicentServiceOptions {
|
|
|
46
46
|
}
|
|
47
47
|
export declare class CodicentService {
|
|
48
48
|
createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
|
|
49
|
-
readDataMessages: (tag: string, search?: string, codicent?: string) => Promise<DataMessage[]>;
|
|
49
|
+
readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number) => Promise<DataMessage[]>;
|
|
50
50
|
readOneDataMessage: (id: string) => Promise<Message | null>;
|
|
51
51
|
updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
|
|
52
52
|
deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
|
|
@@ -79,7 +79,7 @@ export declare class CodicentService {
|
|
|
79
79
|
* @param options Fetch options (headers, body, etc).
|
|
80
80
|
*/
|
|
81
81
|
private request;
|
|
82
|
-
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string) => Promise<Message[]>;
|
|
82
|
+
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string, start?: number) => Promise<Message[]>;
|
|
83
83
|
getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
|
|
84
84
|
registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
|
|
85
85
|
loginUser: (userId: string, accessToken: string) => Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","s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AAM,CAAC,CAoB9D;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,mBAAmB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCA+BxG;IAEF;;;;;;;;OAQG;IACH,MAAM,CAAC,gBAAgB,YACZ,MAAM,YACN,MAAM,cACH,MAAM,mBACF,MAAM,oBACL,MAAM,KACtB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+E5B;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,mBAO7B;IAGF,OAAO,CAAC,kBAAkB;IAM1B,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBjE,iBAAiB,IAAI,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoB5D;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CAsB7B;CACH"}
|
|
@@ -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("../utils/cacheManager.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 s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:o}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e,a)=>await window.Codicent.data.create({codicent:a||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,a)=>await window.Codicent.data.read({codicent:a||this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,a)=>await window.Codicent.data.update({id:t,data:e,codicent:a||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||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.generateApiToken=async(t,e)=>{const a=await fetch(`${o}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${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}`);return await a.text()},this.sendMessage=(t,e,a)=>window.Codicent.postMessage({message:`@${a||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,a)=>window.Codicent.getChatReply4({message:t,codicent:a||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,a=100,n=void 0,s)=>{const i=await this.request(`${o}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,length:a})});let r=await i.json();if(r.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);r=r.concat(t),r.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return r},this.getMessages=async(t,e,a=10)=>{let o=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:a});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{o=o.concat(t)})),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,a)=>e===a.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,a,n)=>{const s=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(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:o}),i},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),s=a.sub||a.userId,i=await fetch(`${o}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.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:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:a,picture:n})=>{const s=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(!s.ok)throw s.status,new Error(`${s.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 this.request(`${o}app/GetForms?codicent=${this.codicent}`,"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.getTodoStatus=async t=>{const e=await fetch(`${o}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const a=await fetch(`${o}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)return console.warn(`updateTodoStatus() => ${a.statusText}`),!1;return await a.json()},this.codicent="",this.options=t}async request(t,e,a={}){const o={};a.headers&&a.headers.forEach((([t,e])=>{o[t]=e}));const n=await fetch(t,{...a,method:e,headers:o});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${o}realtime/session?voice=${t}`,a=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const n=await a.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${o}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}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.getMiniChatReplyOld=async(t,e="codicent-mini",a)=>{let s={project:e,message:t};a&&(s.messageId=a);const i=await fetch(`${o}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",a,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;a&&(r.messageId=a);try{const t=await fetch(`${o}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${o}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const a=await t.json();return a.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},r.getTranslations=async(t,e,a="codicent-mini")=>{const s=await fetch(`${o}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:a,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},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("../utils/cacheManager.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 s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:o}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(t){this.createDataMessage=async(t,e,a)=>await window.Codicent.data.create({codicent:a||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,a,o,n)=>await window.Codicent.data.read({codicent:a||this.codicent,tag:t,search:e,start:o,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,a)=>await window.Codicent.data.update({id:t,data:e,codicent:a||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||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.generateApiToken=async(t,e)=>{const a=await fetch(`${o}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${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}`);return await a.text()},this.sendMessage=(t,e,a)=>window.Codicent.postMessage({message:`@${a||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,a)=>window.Codicent.getChatReply4({message:t,codicent:a||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,a=100,n=void 0,s,i=0)=>{const r=await this.request(`${o}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:a})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,a=10)=>{let o=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:a});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{o=o.concat(t)})),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,a)=>e===a.findIndex((e=>e.id===t.id)))),o.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),o},this.registerUser=async(t,e,a,n)=>{const s=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(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:o}),i},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),s=a.sub||a.userId,i=await fetch(`${o}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.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:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:a,picture:n})=>{const s=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(!s.ok)throw s.status,new Error(`${s.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 this.request(`${o}app/GetForms?codicent=${this.codicent}`,"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.getTodoStatus=async t=>{const e=await fetch(`${o}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const a=await fetch(`${o}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!a.ok)return console.warn(`updateTodoStatus() => ${a.statusText}`),!1;return await a.json()},this.codicent="",this.options=t}async request(t,e,a={}){const o={};a.headers&&a.headers.forEach((([t,e])=>{o[t]=e}));const n=await fetch(t,{...a,method:e,headers:o});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${o}realtime/session?voice=${t}`,a=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const n=await a.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${o}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}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.getMiniChatReplyOld=async(t,e="codicent-mini",a)=>{let s={project:e,message:t};a&&(s.messageId=a);const i=await fetch(`${o}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",a,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;a&&(r.messageId=a);try{const t=await fetch(`${o}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${o}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const a=await t.json();return a.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},r.getTranslations=async(t,e,a="codicent-mini")=>{const s=await fetch(`${o}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:a,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=r;
|
|
@@ -46,7 +46,7 @@ export interface CodicentServiceOptions {
|
|
|
46
46
|
}
|
|
47
47
|
export declare class CodicentService {
|
|
48
48
|
createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
|
|
49
|
-
readDataMessages: (tag: string, search?: string, codicent?: string) => Promise<DataMessage[]>;
|
|
49
|
+
readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number) => Promise<DataMessage[]>;
|
|
50
50
|
readOneDataMessage: (id: string) => Promise<Message | null>;
|
|
51
51
|
updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
|
|
52
52
|
deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
|
|
@@ -79,7 +79,7 @@ export declare class CodicentService {
|
|
|
79
79
|
* @param options Fetch options (headers, body, etc).
|
|
80
80
|
*/
|
|
81
81
|
private request;
|
|
82
|
-
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string) => Promise<Message[]>;
|
|
82
|
+
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string, start?: number) => Promise<Message[]>;
|
|
83
83
|
getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
|
|
84
84
|
registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
|
|
85
85
|
loginUser: (userId: string, accessToken: string) => Promise<string | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAmCA,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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D;IAEF,SAAS,+BAqCP;IAEF,YAAY,+BAeV;IAEF,MAAM,CAAC,YAAY,SAAgB,QAAQ,mBAyBzC;IAEF,MAAM,CAAC,mBAAmB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCA+BxG;IAEF;;;;;;;;OAQG;IACH,MAAM,CAAC,gBAAgB,YACZ,MAAM,YACN,MAAM,cACH,MAAM,mBACF,MAAM,oBACL,MAAM,KACtB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+E5B;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,mBAO7B;IAGF,OAAO,CAAC,kBAAkB;IAM1B,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsBjE,iBAAiB,IAAI,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoB5D;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CAsB7B;CACH"}
|
|
@@ -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"../utils/cacheManager.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 s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||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.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${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}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s)=>{const i=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,length:o})});let r=await i.json();if(r.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);r=r.concat(t),r.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return r},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),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,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=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(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},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),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.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:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=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(!s.ok)throw s.status,new Error(`${s.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 this.request(`${a}app/GetForms?codicent=${this.codicent}`,"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.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${a}realtime/session?voice=${t}`,o=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!o.ok)throw new Error(`Failed to fetch session token: ${o.statusText}`);const n=await o.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${a}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}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.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},r.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()};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"../utils/cacheManager.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 s=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let i=s();if(!i){const t=setInterval((()=>{i=s(),i&&clearInterval(t)}),100)}class r{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||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.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${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}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),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,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=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(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},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),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.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:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=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(!s.ok)throw s.status,new Error(`${s.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 this.request(`${a}app/GetForms?codicent=${this.codicent}`,"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.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy"){const e=`${a}realtime/session?voice=${t}`,o=await fetch(e,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!o.ok)throw new Error(`Failed to fetch session token: ${o.statusText}`);const n=await o.json(),s=n.client_secret?.value;if(!s)throw new Error("No ephemeral key returned from session endpoint");return s}async getRealtimeConfig(){try{const t=`${a}realtime/config`,e=await fetch(t,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return e.ok?await e.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}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.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},r.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},r.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()};export{r as CodicentService};
|
package/dist/index.d.ts
CHANGED
|
@@ -58,7 +58,7 @@ interface CodicentServiceOptions {
|
|
|
58
58
|
}
|
|
59
59
|
declare class CodicentService {
|
|
60
60
|
createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
|
|
61
|
-
readDataMessages: (tag: string, search?: string, codicent?: string) => Promise<DataMessage[]>;
|
|
61
|
+
readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number) => Promise<DataMessage[]>;
|
|
62
62
|
readOneDataMessage: (id: string) => Promise<Message | null>;
|
|
63
63
|
updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
|
|
64
64
|
deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
|
|
@@ -91,7 +91,7 @@ declare class CodicentService {
|
|
|
91
91
|
* @param options Fetch options (headers, body, etc).
|
|
92
92
|
*/
|
|
93
93
|
private request;
|
|
94
|
-
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string) => Promise<Message[]>;
|
|
94
|
+
getMessagesFast: (tags: string[], search?: string, length?: number, publicCodicent?: string | undefined, codicent?: string, start?: number) => Promise<Message[]>;
|
|
95
95
|
getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
|
|
96
96
|
registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
|
|
97
97
|
loginUser: (userId: string, accessToken: string) => Promise<string | null>;
|