codicent-app-sdk 0.3.83 → 0.3.85

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.
@@ -1 +1 @@
1
- {"version":3,"file":"FormAccept.d.ts","sourceRoot":"","sources":["../../../src/pages/FormAccept.tsx"],"names":[],"mappings":"AAkCA,QAAA,MAAM,UAAU,+CAkDf,CAAC;AAEF,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"FormAccept.d.ts","sourceRoot":"","sources":["../../../src/pages/FormAccept.tsx"],"names":[],"mappings":"AAiCA,QAAA,MAAM,UAAU,+CAkDf,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"FormInvite.d.ts","sourceRoot":"","sources":["../../../src/pages/FormInvite.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC;AAG3B,OAAO,EAAE,gBAAgB,EAA6C,MAAM,UAAU,CAAC;AAqCvF,QAAA,MAAM,UAAU,EAAE,EAAE,CAAC;IAAE,KAAK,EAAE,gBAAgB,CAAA;CAAE,CAyH/C,CAAC;AAEF,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"FormInvite.d.ts","sourceRoot":"","sources":["../../../src/pages/FormInvite.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC;AAG3B,OAAO,EAAE,gBAAgB,EAA6C,MAAM,UAAU,CAAC;AAsCvF,QAAA,MAAM,UAAU,EAAE,EAAE,CAAC;IAAE,KAAK,EAAE,gBAAgB,CAAA;CAAE,CA+I/C,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react");require("../components/Markdown.js"),require("../components/Textarea.js");var n=require("../components/Button.js"),o=require("../components/Title.js");require("../components/Spinner.js");var t=require("../components/Label.js"),i=require("../components/Input.js");require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js");var a=require("../hooks/useStateWithLocalStorage.js");require("../services/codicent.js"),require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var s=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");var l=require("../utils/helpers.js");require("./AppFrame.js"),require("./Snap.js"),require("./Search.js"),require("./Login.js"),require("./CrmPage.js"),require("./ImageView.js"),require("./FormAccept.js"),require("./Sales.js"),require("../stores/chatStore.js");var u=require("../hooks/useLocalization.js");require("../hooks/useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js");var c=require("../components/Content.js");require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js");var d=require("../components/Page.js"),p=require("../node_modules/@griffel/react/makeStyles.esm.js"),m=require("../node_modules/@fluentui/react-utilities/lib/hooks/useId.js"),j=require("../node_modules/@fluentui/react-combobox/lib/components/Dropdown/Dropdown.js"),h=require("../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js");const k=p.makeStyles({inputAndButton:{display:"flex",gap:"10px"},input:{minWidth:"90%"},container:{maxWidth:"640px",margin:"0 auto",backgroundPosition:"calc(50% + 100px) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",height:"100%"},generatedLinkTitle:{marginBottom:"0.5em",fontWeight:"bold"},orderedList:{marginLeft:"20px",marginBottom:"1em"},instructionParagraph:{marginBottom:"1em",fontWeight:"bold"}});exports.default=({state:p})=>{const q=k(),{service:g}=p,{t:x}=u.default(),[v,f]=a.default(p.context.selectedApp+"_forms",[]),[b,w]=r.useState(),[S,y]=r.useState(),[_,C]=r.useState(!1),[I,L]=r.useState(),B=m.useId("form-dropdown");r.useEffect((()=>{g.getForms().then((e=>{e.sort(((e,r)=>e.name.localeCompare(r.name))),f(e)}))}),[g,x,f]);const T=void 0!==navigator.share;return e.jsx(d.Page,{children:e.jsx("div",{className:q.container,style:{backgroundImage:`url(${s.getConfigValue("COMPOSE_BACKGROUND_IMAGE_URL")})`},children:e.jsxs(c.default,{children:[e.jsx(o.Title,{children:x("Skapa länk till formulär")}),e.jsx("p",{className:q.instructionParagraph,children:x("Instruktioner")}),e.jsxs("ol",{className:q.orderedList,children:[e.jsx("li",{children:x("Välj ett formulär från rullgardinsmenyn nedan. Detta formulär kommer att användas för den genererade länken.")}),e.jsx("li",{children:x("Klicka på 'Skapa länk' för att generera en unik länk. Länken visar var aktiv och kan användas för att svara på formuläret.")}),e.jsx("li",{children:x("När länken visas, kan du klicka på kopiera-ikonen för att kopiera länken till ditt urklipp.")}),e.jsx("li",{children:x("Om din enhet stödjer det, kan du även använda dela-knappen för att dela länken direkt.")}),e.jsx("li",{children:x("Kom ihåg att spara (skriva ner) koden")})]}),e.jsx("label",{id:B,className:q.instructionParagraph,children:x("Välj formulär")}),e.jsx(j.Dropdown,{"aria-labelledby":B,placeholder:"-",onOptionSelect:(e,r)=>L(r.optionValue),children:v.map((r=>e.jsxs(h.Option,{value:r.name,text:`${r.title} (${r.name})`,children:[`${r.title} (${r.name})`," "]},r.name)))}),e.jsx(n.Button,{appearance:"primary",disabled:!I,onClick:()=>{g.sendMessage(`#ss-link #${I}`).then((e=>{const r=`${window.location.protocol}//${window.location.hostname}${window.location.port?":"+window.location.port:""}${window.location.pathname}`;w(`${r}#/formaccept?id=${e}`);const n=l.formatGuidToShorterReadableCode(e);y(n)}))},children:x("Skapa länk")}),b&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:q.generatedLinkTitle,children:x("Här är din genererade länk (du kan kopiera eller dela den):")}),e.jsx("div",{className:q.inputAndButton,children:e.jsx(i.Input,{className:q.input,value:b,readOnly:!0,onFocus:e=>e.target.select()})}),e.jsx("br",{}),e.jsxs("div",{className:q.inputAndButton,children:[e.jsx(n.Button,{appearance:"primary",title:x("Kopiera länk"),icon:"CopyRegular",onClick:()=>{b&&(navigator.clipboard.writeText(b),C(!0),setTimeout((()=>{C(!1),w(void 0)}),2e3))},children:x("Kopiera")}),T&&e.jsx(n.Button,{appearance:"primary",title:x("Dela länk"),icon:"ShareRegular",onClick:()=>{b&&(navigator.share({url:b}),setTimeout((()=>{w(void 0)}),2e3))},children:x("Dela")})]}),_&&e.jsx(t.Label,{children:x("Länk kopierad!")})]})]})})})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react");require("../components/Markdown.js"),require("../components/Textarea.js");var n=require("../components/Button.js"),o=require("../components/Title.js");require("../components/Spinner.js");var t=require("../components/Label.js"),i=require("../components/Input.js");require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js");var a=require("../hooks/useStateWithLocalStorage.js");require("../services/codicent.js"),require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var s=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");var l=require("../utils/helpers.js");require("./AppFrame.js"),require("./Snap.js"),require("./Search.js"),require("./Login.js"),require("./CrmPage.js"),require("./ImageView.js"),require("./FormAccept.js"),require("./Sales.js"),require("../stores/chatStore.js");var u=require("../hooks/useLocalization.js");require("../hooks/useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js");var c=require("../components/Content.js");require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js");var d=require("../components/Page.js"),p=require("../node_modules/@griffel/react/makeStyles.esm.js"),m=require("../node_modules/@fluentui/react-utilities/lib/hooks/useId.js"),j=require("../node_modules/@fluentui/react-combobox/lib/components/Dropdown/Dropdown.js"),h=require("../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js");const k=p.makeStyles({inputAndButton:{display:"flex",gap:"10px"},input:{minWidth:"90%"},container:{maxWidth:"640px",margin:"0 auto",backgroundPosition:"calc(50% + 100px) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",height:"100%"},generatedLinkTitle:{marginBottom:"0.5em",fontWeight:"bold"},orderedList:{marginLeft:"20px",marginBottom:"1em"},instructionParagraph:{marginBottom:"1em",fontWeight:"bold"}});exports.default=({state:p})=>{const q=k(),{service:g}=p,{t:x}=u.default(),[v,f]=a.default(p.context.selectedApp+"_forms",[]),[b,w]=r.useState(),[S,y]=r.useState(),[_,C]=r.useState(!1),[$,T]=r.useState(),I=m.useId("form-dropdown");r.useEffect((()=>{g.getForms().then((e=>{e.sort(((e,r)=>e.name.localeCompare(r.name))),f(e)}))}),[g,x,f]);const L=void 0!==navigator.share;return e.jsx(d.Page,{children:e.jsx("div",{className:q.container,style:{backgroundImage:`url(${s.getConfigValue("COMPOSE_BACKGROUND_IMAGE_URL")})`},children:e.jsxs(c.default,{children:[e.jsx(o.Title,{children:x("Skapa länk till formulär")}),e.jsx("p",{className:q.instructionParagraph,children:x("Instruktioner")}),e.jsxs("ol",{className:q.orderedList,children:[e.jsx("li",{children:x("Välj ett formulär från rullgardinsmenyn nedan. Detta formulär kommer att användas för den genererade länken.")}),e.jsx("li",{children:x("Klicka på 'Skapa länk' för att generera en unik länk. Länken visar var aktiv och kan användas för att svara på formuläret.")}),e.jsx("li",{children:x("När länken visas, kan du klicka på kopiera-ikonen för att kopiera länken till ditt urklipp.")}),e.jsx("li",{children:x("Om din enhet stödjer det, kan du även använda dela-knappen för att dela länken direkt.")}),e.jsx("li",{children:x("Kom ihåg att spara (skriva ner) koden")})]}),e.jsx("label",{id:I,className:q.instructionParagraph,children:x("Välj formulär")}),e.jsx(j.Dropdown,{"aria-labelledby":I,placeholder:"-",onOptionSelect:(e,r)=>T(r.optionValue),children:v.map((r=>e.jsxs(h.Option,{value:r.name,text:`${r.title} (${r.name})`,children:[`${r.title} (${r.name})`," "]},r.name)))}),e.jsx(n.Button,{appearance:"primary",disabled:!$,onClick:()=>{const e=v.find((e=>e.name===$));e?.url?g.sendMessage(`#ss-link #${$}`).then((r=>{const n=new Date(Date.now()+2592e5);g.generateApiToken(n).then((n=>{const o=e.url.includes("?")?"&":"?",t=`${e.url}${o}token=${n}`;w(t);const i=l.formatGuidToShorterReadableCode(r);y(i)}))})):g.sendMessage(`#ss-link #${$}`).then((e=>{const r=`${window.location.protocol}//${window.location.hostname}${window.location.port?":"+window.location.port:""}${window.location.pathname}`;w(`${r}#/formaccept?id=${e}`);const n=l.formatGuidToShorterReadableCode(e);y(n)}))},children:x("Skapa länk")}),b&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:q.generatedLinkTitle,children:x("Här är din genererade länk (du kan kopiera eller dela den):")}),e.jsx("div",{className:q.inputAndButton,children:e.jsx(i.Input,{className:q.input,value:b,readOnly:!0,onFocus:e=>e.target.select()})}),e.jsx("br",{}),e.jsxs("div",{className:q.inputAndButton,children:[e.jsx(n.Button,{appearance:"primary",title:x("Kopiera länk"),icon:"CopyRegular",onClick:()=>{b&&(navigator.clipboard.writeText(b),C(!0),setTimeout((()=>{C(!1),w(void 0)}),2e3))},children:x("Kopiera")}),L&&e.jsx(n.Button,{appearance:"primary",title:x("Dela länk"),icon:"ShareRegular",onClick:()=>{b&&(navigator.share({url:b}),setTimeout((()=>{w(void 0)}),2e3))},children:x("Dela")})]}),_&&e.jsx(t.Label,{children:x("Länk kopierad!")})]})]})})})};
@@ -17,6 +17,12 @@ export interface AppInfo {
17
17
  title: string;
18
18
  logo: string;
19
19
  }
20
+ export interface Form {
21
+ name: string;
22
+ prompt: string;
23
+ title: string;
24
+ url?: string;
25
+ }
20
26
  export interface CodicentServiceOptions {
21
27
  API_BASE_URL: string;
22
28
  APP_LOG_CODICENT: string;
@@ -55,6 +61,7 @@ export declare class CodicentService {
55
61
  getFileInfo: (fileId: string) => Promise<FileInfo>;
56
62
  static getImageUrl: (fileId: string, width: number) => string;
57
63
  static getFileUrl: (fileId: string, extension?: string) => string;
64
+ generateApiToken: (expires?: Date, forUserNickname?: string) => Promise<string>;
58
65
  sendMessage: (message: string, parentId?: string) => Promise<string>;
59
66
  chat: (message: string, messageId?: string) => Promise<ChatMessageReply>;
60
67
  /**
@@ -105,11 +112,7 @@ export declare class CodicentService {
105
112
  findUsername: () => Promise<string | null>;
106
113
  static downloadFile: (file: FileInfo) => Promise<void>;
107
114
  static getMiniChatReply: (message: string, project?: string, messageId?: string) => Promise<string | undefined>;
108
- getForms: () => Promise<{
109
- name: string;
110
- prompt: string;
111
- title: string;
112
- }[]>;
115
+ getForms: () => Promise<Form[]>;
113
116
  getFormById: (id: string) => Promise<any>;
114
117
  private handleUnauthorized;
115
118
  getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAkCA,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,C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BAAgB,aAAoB,MAAM,uBAIxC;IAEF,QAAQ,aAAc,MAAM,UAK1B;IAEF,OAAO,CAAC,QAAQ,CAAe;IAE/B,mBAAmB,QAAa,OAAO,CAAC,OAAO,CAAC,CAe9C;IAEF,uBAAuB,QAAa,OAAO,CAAC,MAAM,CAAC,CAsBjD;IAEF,qBAAqB,YAAmB,MAAM,KAAG,OAAO,CAAC,MAAM,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,gBAAgB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCA0BrG;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,kBAO7B;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;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("../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.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},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 this.request(`${o}app/AppGetMessages`,"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})});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=[];const o=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(o)).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,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 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()}}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.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},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.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)=>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 this.request(`${o}app/AppGetMessages`,"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})});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=[];const o=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(o)).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,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 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()}}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":"FormAccept.d.ts","sourceRoot":"","sources":["../../../src/pages/FormAccept.tsx"],"names":[],"mappings":"AAkCA,QAAA,MAAM,UAAU,+CAkDf,CAAC;AAEF,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"FormAccept.d.ts","sourceRoot":"","sources":["../../../src/pages/FormAccept.tsx"],"names":[],"mappings":"AAiCA,QAAA,MAAM,UAAU,+CAkDf,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"FormInvite.d.ts","sourceRoot":"","sources":["../../../src/pages/FormInvite.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC;AAG3B,OAAO,EAAE,gBAAgB,EAA6C,MAAM,UAAU,CAAC;AAqCvF,QAAA,MAAM,UAAU,EAAE,EAAE,CAAC;IAAE,KAAK,EAAE,gBAAgB,CAAA;CAAE,CAyH/C,CAAC;AAEF,eAAe,UAAU,CAAC"}
1
+ {"version":3,"file":"FormInvite.d.ts","sourceRoot":"","sources":["../../../src/pages/FormInvite.tsx"],"names":[],"mappings":"AAYA,OAAO,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC;AAG3B,OAAO,EAAE,gBAAgB,EAA6C,MAAM,UAAU,CAAC;AAsCvF,QAAA,MAAM,UAAU,EAAE,EAAE,CAAC;IAAE,KAAK,EAAE,gBAAgB,CAAA;CAAE,CA+I/C,CAAC;AAEF,eAAe,UAAU,CAAC"}
@@ -1 +1 @@
1
- import{jsx as o,jsxs as e,Fragment as t}from"react/jsx-runtime";import{useState as n,useEffect as r}from"react";import"../components/Markdown.js";import"../components/Textarea.js";import{Button as i}from"../components/Button.js";import{Title as a}from"../components/Title.js";import"../components/Spinner.js";import{Label as s}from"../components/Label.js";import{Input as m}from"../components/Input.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import l from"../hooks/useStateWithLocalStorage.js";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as p}from"../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";import{formatGuidToShorterReadableCode as c}from"../utils/helpers.js";import"./AppFrame.js";import"./Snap.js";import"./Search.js";import"./Login.js";import"./CrmPage.js";import"./ImageView.js";import"./FormAccept.js";import"./Sales.js";import"../stores/chatStore.js";import d from"../hooks/useLocalization.js";import"../hooks/useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import u from"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import{Page as j}from"../components/Page.js";import{makeStyles as h}from"../node_modules/@griffel/react/makeStyles.esm.js";import{useId as k}from"../node_modules/@fluentui/react-utilities/lib/hooks/useId.js";import{Dropdown as g}from"../node_modules/@fluentui/react-combobox/lib/components/Dropdown/Dropdown.js";import{Option as f}from"../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js";const v=h({inputAndButton:{display:"flex",gap:"10px"},input:{minWidth:"90%"},container:{maxWidth:"640px",margin:"0 auto",backgroundPosition:"calc(50% + 100px) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",height:"100%"},generatedLinkTitle:{marginBottom:"0.5em",fontWeight:"bold"},orderedList:{marginLeft:"20px",marginBottom:"1em"},instructionParagraph:{marginBottom:"1em",fontWeight:"bold"}}),b=({state:h})=>{const b=v(),{service:w}=h,{t:x}=d(),[S,y]=l(h.context.selectedApp+"_forms",[]),[_,C]=n(),[L,$]=n(),[I,A]=n(!1),[N,T]=n(),B=k("form-dropdown");r((()=>{w.getForms().then((o=>{o.sort(((o,e)=>o.name.localeCompare(e.name))),y(o)}))}),[w,x,y]);const P=void 0!==navigator.share;return o(j,{children:o("div",{className:b.container,style:{backgroundImage:`url(${p("COMPOSE_BACKGROUND_IMAGE_URL")})`},children:e(u,{children:[o(a,{children:x("Skapa länk till formulär")}),o("p",{className:b.instructionParagraph,children:x("Instruktioner")}),e("ol",{className:b.orderedList,children:[o("li",{children:x("Välj ett formulär från rullgardinsmenyn nedan. Detta formulär kommer att användas för den genererade länken.")}),o("li",{children:x("Klicka på 'Skapa länk' för att generera en unik länk. Länken visar var aktiv och kan användas för att svara på formuläret.")}),o("li",{children:x("När länken visas, kan du klicka på kopiera-ikonen för att kopiera länken till ditt urklipp.")}),o("li",{children:x("Om din enhet stödjer det, kan du även använda dela-knappen för att dela länken direkt.")}),o("li",{children:x("Kom ihåg att spara (skriva ner) koden")})]}),o("label",{id:B,className:b.instructionParagraph,children:x("Välj formulär")}),o(g,{"aria-labelledby":B,placeholder:"-",onOptionSelect:(o,e)=>T(e.optionValue),children:S.map((o=>e(f,{value:o.name,text:`${o.title} (${o.name})`,children:[`${o.title} (${o.name})`," "]},o.name)))}),o(i,{appearance:"primary",disabled:!N,onClick:()=>{w.sendMessage(`#ss-link #${N}`).then((o=>{const e=`${window.location.protocol}//${window.location.hostname}${window.location.port?":"+window.location.port:""}${window.location.pathname}`;C(`${e}#/formaccept?id=${o}`);const t=c(o);$(t)}))},children:x("Skapa länk")}),_&&e(t,{children:[o("p",{className:b.generatedLinkTitle,children:x("Här är din genererade länk (du kan kopiera eller dela den):")}),o("div",{className:b.inputAndButton,children:o(m,{className:b.input,value:_,readOnly:!0,onFocus:o=>o.target.select()})}),o("br",{}),e("div",{className:b.inputAndButton,children:[o(i,{appearance:"primary",title:x("Kopiera länk"),icon:"CopyRegular",onClick:()=>{_&&(navigator.clipboard.writeText(_),A(!0),setTimeout((()=>{A(!1),C(void 0)}),2e3))},children:x("Kopiera")}),P&&o(i,{appearance:"primary",title:x("Dela länk"),icon:"ShareRegular",onClick:()=>{_&&(navigator.share({url:_}),setTimeout((()=>{C(void 0)}),2e3))},children:x("Dela")})]}),I&&o(s,{children:x("Länk kopierad!")})]})]})})})};export{b as default};
1
+ import{jsx as o,jsxs as e,Fragment as n}from"react/jsx-runtime";import{useState as t,useEffect as r}from"react";import"../components/Markdown.js";import"../components/Textarea.js";import{Button as i}from"../components/Button.js";import{Title as a}from"../components/Title.js";import"../components/Spinner.js";import{Label as s}from"../components/Label.js";import{Input as l}from"../components/Input.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import m from"../hooks/useStateWithLocalStorage.js";import"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as p}from"../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";import{formatGuidToShorterReadableCode as c}from"../utils/helpers.js";import"./AppFrame.js";import"./Snap.js";import"./Search.js";import"./Login.js";import"./CrmPage.js";import"./ImageView.js";import"./FormAccept.js";import"./Sales.js";import"../stores/chatStore.js";import d from"../hooks/useLocalization.js";import"../hooks/useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import u from"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import{Page as h}from"../components/Page.js";import{makeStyles as k}from"../node_modules/@griffel/react/makeStyles.esm.js";import{useId as j}from"../node_modules/@fluentui/react-utilities/lib/hooks/useId.js";import{Dropdown as g}from"../node_modules/@fluentui/react-combobox/lib/components/Dropdown/Dropdown.js";import{Option as f}from"../node_modules/@fluentui/react-combobox/lib/components/Option/Option.js";const v=k({inputAndButton:{display:"flex",gap:"10px"},input:{minWidth:"90%"},container:{maxWidth:"640px",margin:"0 auto",backgroundPosition:"calc(50% + 100px) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",height:"100%"},generatedLinkTitle:{marginBottom:"0.5em",fontWeight:"bold"},orderedList:{marginLeft:"20px",marginBottom:"1em"},instructionParagraph:{marginBottom:"1em",fontWeight:"bold"}}),b=({state:k})=>{const b=v(),{service:w}=k,{t:x}=d(),[S,y]=m(k.context.selectedApp+"_forms",[]),[$,_]=t(),[C,L]=t(),[A,I]=t(!1),[T,D]=t(),N=j("form-dropdown");r((()=>{w.getForms().then((o=>{o.sort(((o,e)=>o.name.localeCompare(e.name))),y(o)}))}),[w,x,y]);const B=void 0!==navigator.share;return o(h,{children:o("div",{className:b.container,style:{backgroundImage:`url(${p("COMPOSE_BACKGROUND_IMAGE_URL")})`},children:e(u,{children:[o(a,{children:x("Skapa länk till formulär")}),o("p",{className:b.instructionParagraph,children:x("Instruktioner")}),e("ol",{className:b.orderedList,children:[o("li",{children:x("Välj ett formulär från rullgardinsmenyn nedan. Detta formulär kommer att användas för den genererade länken.")}),o("li",{children:x("Klicka på 'Skapa länk' för att generera en unik länk. Länken visar var aktiv och kan användas för att svara på formuläret.")}),o("li",{children:x("När länken visas, kan du klicka på kopiera-ikonen för att kopiera länken till ditt urklipp.")}),o("li",{children:x("Om din enhet stödjer det, kan du även använda dela-knappen för att dela länken direkt.")}),o("li",{children:x("Kom ihåg att spara (skriva ner) koden")})]}),o("label",{id:N,className:b.instructionParagraph,children:x("Välj formulär")}),o(g,{"aria-labelledby":N,placeholder:"-",onOptionSelect:(o,e)=>D(e.optionValue),children:S.map((o=>e(f,{value:o.name,text:`${o.title} (${o.name})`,children:[`${o.title} (${o.name})`," "]},o.name)))}),o(i,{appearance:"primary",disabled:!T,onClick:()=>{const o=S.find((o=>o.name===T));o?.url?w.sendMessage(`#ss-link #${T}`).then((e=>{const n=new Date(Date.now()+2592e5);w.generateApiToken(n).then((n=>{const t=o.url.includes("?")?"&":"?",r=`${o.url}${t}token=${n}`;_(r);const i=c(e);L(i)}))})):w.sendMessage(`#ss-link #${T}`).then((o=>{const e=`${window.location.protocol}//${window.location.hostname}${window.location.port?":"+window.location.port:""}${window.location.pathname}`;_(`${e}#/formaccept?id=${o}`);const n=c(o);L(n)}))},children:x("Skapa länk")}),$&&e(n,{children:[o("p",{className:b.generatedLinkTitle,children:x("Här är din genererade länk (du kan kopiera eller dela den):")}),o("div",{className:b.inputAndButton,children:o(l,{className:b.input,value:$,readOnly:!0,onFocus:o=>o.target.select()})}),o("br",{}),e("div",{className:b.inputAndButton,children:[o(i,{appearance:"primary",title:x("Kopiera länk"),icon:"CopyRegular",onClick:()=>{$&&(navigator.clipboard.writeText($),I(!0),setTimeout((()=>{I(!1),_(void 0)}),2e3))},children:x("Kopiera")}),B&&o(i,{appearance:"primary",title:x("Dela länk"),icon:"ShareRegular",onClick:()=>{$&&(navigator.share({url:$}),setTimeout((()=>{_(void 0)}),2e3))},children:x("Dela")})]}),A&&o(s,{children:x("Länk kopierad!")})]})]})})})};export{b as default};
@@ -17,6 +17,12 @@ export interface AppInfo {
17
17
  title: string;
18
18
  logo: string;
19
19
  }
20
+ export interface Form {
21
+ name: string;
22
+ prompt: string;
23
+ title: string;
24
+ url?: string;
25
+ }
20
26
  export interface CodicentServiceOptions {
21
27
  API_BASE_URL: string;
22
28
  APP_LOG_CODICENT: string;
@@ -55,6 +61,7 @@ export declare class CodicentService {
55
61
  getFileInfo: (fileId: string) => Promise<FileInfo>;
56
62
  static getImageUrl: (fileId: string, width: number) => string;
57
63
  static getFileUrl: (fileId: string, extension?: string) => string;
64
+ generateApiToken: (expires?: Date, forUserNickname?: string) => Promise<string>;
58
65
  sendMessage: (message: string, parentId?: string) => Promise<string>;
59
66
  chat: (message: string, messageId?: string) => Promise<ChatMessageReply>;
60
67
  /**
@@ -105,11 +112,7 @@ export declare class CodicentService {
105
112
  findUsername: () => Promise<string | null>;
106
113
  static downloadFile: (file: FileInfo) => Promise<void>;
107
114
  static getMiniChatReply: (message: string, project?: string, messageId?: string) => Promise<string | undefined>;
108
- getForms: () => Promise<{
109
- name: string;
110
- prompt: string;
111
- title: string;
112
- }[]>;
115
+ getForms: () => Promise<Form[]>;
113
116
  getFormById: (id: string) => Promise<any>;
114
117
  private handleUnauthorized;
115
118
  getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAkCA,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,EA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+EH;IAElC,mBAAmB,aAAoB,MAAM,WAAW,MAAM,EAAE,sBAe9D;IAEF,gBAAgB,aAAoB,MAAM,uBAIxC;IAEF,QAAQ,aAAc,MAAM,UAK1B;IAEF,OAAO,CAAC,QAAQ,CAAe;IAE/B,mBAAmB,QAAa,OAAO,CAAC,OAAO,CAAC,CAe9C;IAEF,uBAAuB,QAAa,OAAO,CAAC,MAAM,CAAC,CAsBjD;IAEF,qBAAqB,YAAmB,MAAM,KAAG,OAAO,CAAC,MAAM,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,gBAAgB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCA0BrG;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,kBAO7B;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;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"../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 a;let o="https://codicent.com/",n="-";const i=()=>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 s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(a){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 a=new e(t.content).content.split("\n"),o=a[0],n=a.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 this.request(`${o}app/AppGetMessages`,"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})});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=[];const o=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(o)).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,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();return e.filter(((t,e,a)=>e===a.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 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 e=>{const a=await t(this.options.STRIPE_PUBLIC_KEY);if(!a)throw new Error("Stripe failed to load");const o=await this.createCheckoutSession(e),{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=a}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()}}a=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 t=>{fetch(a.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 a=window.URL.createObjectURL(e),o=document.createElement("a");o.style.display="none",o.href=a,o.download=t.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()};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 a;let o="https://codicent.com/",n="-";const i=()=>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 s=i();if(!s){const t=setInterval((()=>{s=i(),s&&clearInterval(t)}),100)}class r{constructor(a){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 a=new e(t.content).content.split("\n"),o=a[0],n=a.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)=>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 this.request(`${o}app/AppGetMessages`,"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})});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=[];const o=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:10});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(o)).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,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();return e.filter(((t,e,a)=>e===a.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 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 e=>{const a=await t(this.options.STRIPE_PUBLIC_KEY);if(!a)throw new Error("Stripe failed to load");const o=await this.createCheckoutSession(e),{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=a}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()}}a=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 t=>{fetch(a.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 a=window.URL.createObjectURL(e),o=document.createElement("a");o.style.display="none",o.href=a,o.download=t.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()};export{r as CodicentService};
package/dist/index.d.ts CHANGED
@@ -29,6 +29,12 @@ interface AppInfo {
29
29
  title: string;
30
30
  logo: string;
31
31
  }
32
+ interface Form {
33
+ name: string;
34
+ prompt: string;
35
+ title: string;
36
+ url?: string;
37
+ }
32
38
  interface CodicentServiceOptions {
33
39
  API_BASE_URL: string;
34
40
  APP_LOG_CODICENT: string;
@@ -67,6 +73,7 @@ declare class CodicentService {
67
73
  getFileInfo: (fileId: string) => Promise<FileInfo>;
68
74
  static getImageUrl: (fileId: string, width: number) => string;
69
75
  static getFileUrl: (fileId: string, extension?: string) => string;
76
+ generateApiToken: (expires?: Date, forUserNickname?: string) => Promise<string>;
70
77
  sendMessage: (message: string, parentId?: string) => Promise<string>;
71
78
  chat: (message: string, messageId?: string) => Promise<ChatMessageReply>;
72
79
  /**
@@ -117,11 +124,7 @@ declare class CodicentService {
117
124
  findUsername: () => Promise<string | null>;
118
125
  static downloadFile: (file: FileInfo) => Promise<void>;
119
126
  static getMiniChatReply: (message: string, project?: string, messageId?: string) => Promise<string | undefined>;
120
- getForms: () => Promise<{
121
- name: string;
122
- prompt: string;
123
- title: string;
124
- }[]>;
127
+ getForms: () => Promise<Form[]>;
125
128
  getFormById: (id: string) => Promise<any>;
126
129
  private handleUnauthorized;
127
130
  getTodoStatus: (messageId: string) => Promise<"done" | "undone" | "unknown">;
@@ -876,4 +879,4 @@ declare const Sales: React__default.FC<{
876
879
  state: CodicentAppState;
877
880
  }>;
878
881
 
879
- export { AiInput, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, Button, ChatInput, ChatMessage, CodicentAppState, CodicentService, CodicentServiceOptions, ColorPicker, CombinedPlaceholderDialog, Content, CrmPage, DatePicker, FilePlaceholder, FileThumbnail, Footer, FormAccept, FormInvite, Header, HtmlView, ImageViewer as ImageView, Input, Label, Login, Logout, Markdown, Message$1 as Message, Content$1 as MessageContent, MessageInput, MessageItem, Page, Profile, Prompt, RealtimeVoice, Sales, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UserInfo, VoiceIcon, WavRecorder, WavStreamPlayer, createAppStateMachine, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useLocalization, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
882
+ export { AiInput, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, Button, ChatInput, ChatMessage, CodicentAppState, CodicentService, CodicentServiceOptions, ColorPicker, CombinedPlaceholderDialog, Content, CrmPage, DatePicker, FilePlaceholder, FileThumbnail, Footer, Form, FormAccept, FormInvite, Header, HtmlView, ImageViewer as ImageView, Input, Label, Login, Logout, Markdown, Message$1 as Message, Content$1 as MessageContent, MessageInput, MessageItem, Page, Profile, Prompt, RealtimeVoice, Sales, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UserInfo, VoiceIcon, WavRecorder, WavStreamPlayer, createAppStateMachine, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useLocalization, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.3.83",
3
+ "version": "0.3.85",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",