codicent-app-sdk 0.4.7 → 0.4.9

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":"Footer.d.ts","sourceRoot":"","sources":["../../../src/components/Footer.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AA8EnD,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,EAgH1B,CAAC;AAEF,eAAe,MAAM,CAAC"}
1
+ {"version":3,"file":"Footer.d.ts","sourceRoot":"","sources":["../../../src/components/Footer.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAyFnD,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,EAwI1B,CAAC;AAEF,eAAe,MAAM,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react"),s=require("@fluentui/react-components"),a=require("@fluentui/react-icons"),i=require("react-router-dom");require("../services/codicent.js"),require("./Markdown.js"),require("./Textarea.js"),require("./Button.js"),require("./CompoundButton.js"),require("./Spinner.js"),require("./TextHeader.js"),require("./TypingIndicator.js"),require("./Dialog.js"),require("./ChatInput.js"),require("./CombinedPlaceholderDialog.js"),require("./ChatMessage.js"),require("./Header.js"),require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var o=require("../config/index.js");require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./FileThumbnail.js"),require("./MessageInput.js"),require("./UploadFile.js"),require("./SnapFooter.js"),require("./Profile.js"),require("./MessageItem.js"),require("./Content.js"),require("./AiInput.js"),require("./SearchBox.js"),require("./HtmlView.js"),require("./Page.js"),require("./QrCodeDialog.js"),require("./QrScanner.js");var t=require("../hooks/useLocalization.js");require("./OfflineMessage.js"),require("./LanguageSelector.js"),require("./ListView.js"),require("./RecordModal.js"),require("./BulkUploadDialog.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js"),require("../hooks/useAppStyles.js");const l=s.makeStyles({footer:{...s.shorthands.padding("14px"),textAlign:"center",display:"flex",justifyContent:"space-around",alignItems:"center",position:"sticky",bottom:0,zIndex:1e3,paddingBottom:"22px",width:"100%"},container:{display:"flex",justifyContent:"space-around",alignItems:"center",maxWidth:"480px",width:"100%"},button:{color:s.tokens.colorNeutralForegroundOnBrand,height:"24px",width:"24px",...s.shorthands.borderWidth("0")},link:{textDecoration:"none",color:"inherit",display:"flex",flexDirection:"column",alignItems:"center","&.selected":{border:"none"},"&:hover":{textDecoration:"none"}},buttonText:{fontSize:"12px"}}),n=()=>{const n=l(),u=i.useLocation(),[c,d]=r.useState(null),{t:j}=t.default(),g={backgroundColor:o.getConfigValue("APP_FOOTER_COLOR")||s.tokens.colorBrandBackground,color:o.getConfigValue("APP_FOOTER_TEXT_COLOR")||s.tokens.colorNeutralForegroundOnBrand},p=o.getConfigValue("APP_FOOTER_SELECTED_COLOR")||void 0;return r.useEffect((()=>{const e=u.pathname;"/"===e?d("home"):"/chat"===e?d("chat"):"/new"===e?d("save"):"/menu"===e?d("menu"):"/log"===e?d("log"):"/canvas"===e?d("canvas"):"/snap"===e&&d("snap")}),[u]),r.useEffect((()=>{c&&console.log(`footer-button: ${c}`)}),[c]),e.jsx("footer",{className:n.footer,style:g,children:e.jsxs("div",{className:n.container,children:[e.jsxs(i.Link,{to:"/",className:`${n.link} ${"home"===c?"selected":""}`,onClick:()=>d("home"),style:"home"===c?{color:p}:void 0,children:["home"===c?e.jsx(a.Home24Filled,{}):e.jsx(a.Home24Regular,{}),e.jsx("p",{className:n.buttonText,children:j("Hem")})]}),!o.getConfigValue("HIDE_CHAT_BUTTON")&&e.jsxs(i.Link,{to:"/chat",className:`${n.link} ${"chat"===c?"selected":""}`,onClick:()=>d("chat"),style:"chat"===c?{color:p}:void 0,children:["chat"===c?e.jsx(a.Chat24Filled,{}):e.jsx(a.Chat24Regular,{}),e.jsx("p",{className:n.buttonText,children:j(o.getConfigValue("APP_CHAT_TITLE")||"Chatt")})]}),!o.getConfigValue("HIDE_SAVE_BUTTON")&&e.jsxs(i.Link,{to:"/new",className:`${n.link} ${"save"===c?"selected":""}`,onClick:()=>d("save"),style:"save"===c?{color:p}:void 0,children:["save"===c?e.jsx(a.AddSquare24Filled,{}):e.jsx(a.AddSquare24Regular,{}),e.jsx("p",{className:n.buttonText,children:j(o.getConfigValue("APP_SAVE_TITLE")||"Spara")})]}),o.getConfigValue("SHOW_SNAP_BUTTON")&&e.jsxs(i.Link,{to:"/snap",className:`${n.link} ${"snap"===c?"selected":""}`,onClick:()=>d("snap"),style:"snap"===c?{color:p}:void 0,children:["snap"===c?e.jsx(a.ClipboardDay24Filled,{}):e.jsx(a.ClipboardDay24Regular,{}),e.jsx("p",{className:n.buttonText,children:j("Snap")})]}),o.getConfigValue("SHOW_LOGBOOK_BUTTON")&&e.jsxs(i.Link,{to:"/log",className:`${n.link} ${"log"===c?"selected":""}`,onClick:()=>d("log"),style:"log"===c?{color:p}:void 0,children:["log"===c?e.jsx(a.SlideText24Filled,{}):e.jsx(a.SlideText24Regular,{}),e.jsx("p",{className:n.buttonText,children:j(o.getConfigValue("APP_LOGBOOK_TITLE")||"Loggbok")})]}),o.getConfigValue("SHOW_CANVAS_BUTTON")&&e.jsxs(i.Link,{to:"/canvas",className:`${n.link} ${"canvas"===c?"selected":""}`,onClick:()=>d("canvas"),style:"canvas"===c?{color:p}:void 0,children:["canvas"===c?e.jsx(a.Whiteboard24Filled,{}):e.jsx(a.Whiteboard24Regular,{}),e.jsx("p",{className:n.buttonText,children:j("Kanvas")})]}),!o.getConfigValue("HIDE_MENU_BUTTON")&&e.jsxs(i.Link,{to:"/menu",className:`${n.link} ${"menu"===c?"selected":""}`,onClick:()=>d("menu"),style:"menu"===c?{color:p}:void 0,children:["menu"===c?e.jsx(a.Apps24Filled,{}):e.jsx(a.Apps24Regular,{}),e.jsx("p",{className:n.buttonText,children:j("Meny")})]})]})})};exports.Footer=n,exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react"),s=require("@fluentui/react-components"),o=require("@fluentui/react-icons"),a=require("react-router-dom");require("../services/codicent.js"),require("./Markdown.js"),require("./Textarea.js"),require("./Button.js"),require("./CompoundButton.js"),require("./Spinner.js"),require("./TextHeader.js"),require("./TypingIndicator.js"),require("./Dialog.js"),require("./ChatInput.js"),require("./CombinedPlaceholderDialog.js"),require("./ChatMessage.js"),require("./Header.js"),require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var i=require("../config/index.js");require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./FileThumbnail.js"),require("./MessageInput.js"),require("./UploadFile.js"),require("./SnapFooter.js"),require("./Profile.js"),require("./MessageItem.js"),require("./Content.js"),require("./AiInput.js"),require("./SearchBox.js"),require("./HtmlView.js"),require("./Page.js"),require("./QrCodeDialog.js"),require("./QrScanner.js");var t=require("../hooks/useLocalization.js");require("./OfflineMessage.js"),require("./LanguageSelector.js"),require("./ListView.js"),require("./RecordModal.js"),require("./BulkUploadDialog.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js"),require("../hooks/useAppStyles.js");const n=s.makeStyles({footer:{...s.shorthands.padding("14px"),textAlign:"center",display:"flex",justifyContent:"space-around",alignItems:"center",position:"sticky",bottom:0,zIndex:1e3,paddingBottom:"22px",width:"100%"},container:{display:"flex",justifyContent:"space-around",alignItems:"center",maxWidth:"480px",width:"100%"},button:{color:s.tokens.colorNeutralForegroundOnBrand,height:"24px",width:"24px",...s.shorthands.borderWidth("0")},link:{textDecoration:"none",color:"inherit",display:"flex",flexDirection:"column",alignItems:"center","&.selected":{border:"none"},"&:hover":{textDecoration:"none"}},buttonText:{fontSize:"12px"},logbookIconWrapper:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center"},notificationBadge:{position:"absolute",top:"-4px",right:"-4px"}}),l=()=>{const l=n(),u=a.useLocation(),[c,d]=r.useState(null),{t:g}=t.default(),[j,p]=r.useState((()=>"true"===localStorage.getItem("logbook-has-notification"))),m={backgroundColor:i.getConfigValue("APP_FOOTER_COLOR")||s.tokens.colorBrandBackground,color:i.getConfigValue("APP_FOOTER_TEXT_COLOR")||s.tokens.colorNeutralForegroundOnBrand},x=i.getConfigValue("APP_FOOTER_SELECTED_COLOR")||void 0;return r.useEffect((()=>{const e=u.pathname;"/"===e?d("home"):"/chat"===e?d("chat"):"/new"===e?d("save"):"/menu"===e?d("menu"):"/log"===e?d("log"):"/canvas"===e?d("canvas"):"/snap"===e&&d("snap")}),[u]),r.useEffect((()=>{c&&console.log(`footer-button: ${c}`)}),[c]),r.useEffect((()=>{const e=()=>{p("true"===localStorage.getItem("logbook-has-notification"))};return window.addEventListener("storage",e),window.addEventListener("logbook-notification-changed",e),()=>{window.removeEventListener("storage",e),window.removeEventListener("logbook-notification-changed",e)}}),[]),e.jsx("footer",{className:l.footer,style:m,children:e.jsxs("div",{className:l.container,children:[e.jsxs(a.Link,{to:"/",className:`${l.link} ${"home"===c?"selected":""}`,onClick:()=>d("home"),style:"home"===c?{color:x}:void 0,children:["home"===c?e.jsx(o.Home24Filled,{}):e.jsx(o.Home24Regular,{}),e.jsx("p",{className:l.buttonText,children:g("Hem")})]}),!i.getConfigValue("HIDE_CHAT_BUTTON")&&e.jsxs(a.Link,{to:"/chat",className:`${l.link} ${"chat"===c?"selected":""}`,onClick:()=>d("chat"),style:"chat"===c?{color:x}:void 0,children:["chat"===c?e.jsx(o.Chat24Filled,{}):e.jsx(o.Chat24Regular,{}),e.jsx("p",{className:l.buttonText,children:g(i.getConfigValue("APP_CHAT_TITLE")||"Chatt")})]}),!i.getConfigValue("HIDE_SAVE_BUTTON")&&e.jsxs(a.Link,{to:"/new",className:`${l.link} ${"save"===c?"selected":""}`,onClick:()=>d("save"),style:"save"===c?{color:x}:void 0,children:["save"===c?e.jsx(o.AddSquare24Filled,{}):e.jsx(o.AddSquare24Regular,{}),e.jsx("p",{className:l.buttonText,children:g(i.getConfigValue("APP_SAVE_TITLE")||"Spara")})]}),i.getConfigValue("SHOW_SNAP_BUTTON")&&e.jsxs(a.Link,{to:"/snap",className:`${l.link} ${"snap"===c?"selected":""}`,onClick:()=>d("snap"),style:"snap"===c?{color:x}:void 0,children:["snap"===c?e.jsx(o.ClipboardDay24Filled,{}):e.jsx(o.ClipboardDay24Regular,{}),e.jsx("p",{className:l.buttonText,children:g("Snap")})]}),i.getConfigValue("SHOW_LOGBOOK_BUTTON")&&e.jsxs(a.Link,{to:"/log",className:`${l.link} ${"log"===c?"selected":""}`,onClick:()=>{d("log"),localStorage.removeItem("logbook-has-notification"),p(!1)},style:"log"===c?{color:x}:void 0,children:[e.jsxs("div",{className:l.logbookIconWrapper,children:["log"===c?e.jsx(o.SlideText24Filled,{}):e.jsx(o.SlideText24Regular,{}),j&&"log"!==c&&e.jsx(s.Badge,{appearance:"filled",color:"danger",size:"extra-small",className:l.notificationBadge})]}),e.jsx("p",{className:l.buttonText,children:g(i.getConfigValue("APP_LOGBOOK_TITLE")||"Loggbok")})]}),i.getConfigValue("SHOW_CANVAS_BUTTON")&&e.jsxs(a.Link,{to:"/canvas",className:`${l.link} ${"canvas"===c?"selected":""}`,onClick:()=>d("canvas"),style:"canvas"===c?{color:x}:void 0,children:["canvas"===c?e.jsx(o.Whiteboard24Filled,{}):e.jsx(o.Whiteboard24Regular,{}),e.jsx("p",{className:l.buttonText,children:g("Kanvas")})]}),!i.getConfigValue("HIDE_MENU_BUTTON")&&e.jsxs(a.Link,{to:"/menu",className:`${l.link} ${"menu"===c?"selected":""}`,onClick:()=>d("menu"),style:"menu"===c?{color:x}:void 0,children:["menu"===c?e.jsx(o.Apps24Filled,{}):e.jsx(o.Apps24Regular,{}),e.jsx("p",{className:l.buttonText,children:g("Meny")})]})]})})};exports.Footer=l,exports.default=l;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),r=require("@fluentui/react-components"),n=require("react-router-dom"),s=require("@fluentui/react-icons");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("../components/Spinner.js");var o=require("../components/TextHeader.js"),a=require("../components/TypingIndicator.js"),i=require("../components/Prompt.js"),l=require("../components/ChatInput.js"),c=require("../components/CombinedPlaceholderDialog.js"),u=require("../components/ChatMessage.js");require("../components/Header.js");var d=require("../hooks/useStateWithLocalStorage.js"),p=require("../services/codicent.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var m=require("../config/index.js");require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./AppFrame.js"),require("./Compose.js"),require("./Snap.js"),require("./Search.js"),require("./Login.js"),require("./CrmPage.js"),require("./CrmPagePersistent.js"),require("./ImageView.js"),require("./FormInvite.js"),require("./FormAccept.js"),require("./Sales.js"),require("./Purchase.js"),require("../components/Content.js");var g=require("../components/Page.js");require("./QrScan.js");var h=require("../hooks/useLocalization.js");require("../components/FileThumbnail.js"),require("react-dom/client"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");var j=require("../hooks/useChat.js"),f=require("../hooks/useTemplateVariables.js");require("../hooks/useAppStyles.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js");const q=r.makeStyles({chatContainer:{width:"100%",flex:1,maxWidth:"800px",height:"100%",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"}});exports.default=({state:r,hideFooter:x,codicent:C,title:S,welcomeMessage:b})=>{const v=q(),{t:w,tAsync:y,getLanguageInfo:P}=h.default(),k=n.useNavigate(),F=t.useRef(null),[T,_]=n.useSearchParams(),I=T.get("codicent"),A=I||C,{messages:M,isBotTyping:V,handleSend:R,newChat:L,openChat:E}=j.useChat(r.stateMachine,A||void 0),[H,N]=t.useState(null),[B,U]=t.useState(!1),[O,D]=t.useState(!1),{service:W,currentStateName:z}=r,[Q,G]=t.useState([]),[Y,$]=t.useState([]),[K,J]=t.useState(!1),[X,Z]=t.useState(),[ee,te]=d.default(r.context.selectedApp+"_prompts",[]),[re,ne]=t.useState(!1),{extractTemplateVariables:se,replaceTemplateVariables:oe,extractFilePlaceholders:ae,replaceFilePlaceholders:ie,handleSelectFiles:le}=f.useTemplateVariables(W.uploadFile),ce=t.useRef(!1),ue=t.useRef(null);t.useEffect((()=>{const e=window.history.length>1,t=Boolean(document.referrer&&document.referrer!==window.location.href);D(e||t)}),[]);t.useEffect((()=>{m.getConfigValue("SHOW_CHAT_PROMPTS")&&0===M.length&&r.service.getAppPrompts().then(te).catch((e=>{console.error("Failed to get prompts",e)}))}),[r.service,te,M.length]),t.useEffect((()=>{setTimeout((()=>{F.current?.scrollIntoView({behavior:"smooth"})}),10)}),[M]),t.useEffect((()=>{if(ce.current)return;ce.current=!0;const e=T.get("text"),t=T.get("id"),r=T.get("fid");if(I){console.log("Using temporary codicent from URL param:",I);const e=new URLSearchParams(T);e.delete("codicent"),_(e,{replace:!0})}if(e){(async()=>{const t=ae(e),r=se(e);L(),t.length>0||r.length>0?($(t),G(r),J(!0),N(w(e))):N(w(e))})()}else t?E(t):r&&Z(r)}),[]),t.useEffect((()=>{X&&"anonymous"===z&&ue.current!==X&&(ue.current=X,W.getFormById(X).then((async e=>{L();const t=P().language,r=e.prompt.replace("{{fid}}",X).replace("{{fname}}",e.name).replace("{{language}}",t);ne(!0);const n=await y(r);ne(!1),N(n),D(!1)})))}),[X,L,W,N,z,y,P,ne]),t.useEffect((()=>{if(H&&!K){let e=H;Y.length>0&&(e=ie(e,Y)),Q.length>0&&(e=oe(e,Q)),R(e),_({},{replace:!0}),N(null),G([]),$([])}}),[H,K,R,_,ie,oe,Y,Q]);const de=e=>{const t=T.get("append");t&&(e+="\n---\n"+t),R(e)};return e.jsxs(g.Page,{hideHeader:!0,hideFooter:!!X||x,children:[e.jsxs("div",{id:"chat-container",className:v.chatContainer,style:{backgroundImage:`url(${m.getConfigValue("CHAT_BACKGROUND_IMAGE_URL")})`},children:[O&&e.jsx("button",{onClick:()=>{O&&k(-1)},"aria-label":w("Tillbaka"),style:{position:"absolute",top:12,left:12,zIndex:100,background:"var(--colorNeutralBackground1)",border:"none",cursor:"pointer",padding:8,borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.08)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(s.CalendarWeekStart24Regular,{style:{transform:"rotate(180deg)"}})}),e.jsx("div",{style:{marginLeft:O?40:0},children:e.jsx(o.default,{title:S||w(m.getConfigValue("APP_CHAT_TITLE")||"Chatt"),onNewChat:X?void 0:()=>U(!0)})}),e.jsxs("div",{className:v.chatMessages,children:[b&&e.jsx(u.default,{sender:"bot",content:b}),m.getConfigValue("SHOW_CHAT_PROMPTS")&&ee.length>0&&0===M.length&&e.jsx(u.default,{sender:"bot",content:w(m.getConfigValue("CHAT_WELCOME")||w("Välkommen!")),children:ee.map(((t,r)=>e.jsxs("div",{children:["> ",e.jsx("a",{href:"./#/chat",onClick:()=>{de(t.title+"\n---\n"+t.prompt)},children:w(t.title)}),e.jsx("br",{})]},`prompt-${r}`)))}),M.map(((t,r)=>e.jsxs("div",{children:[(V&&r===M.length-1||!V&&r===M.length-2)&&e.jsx("div",{ref:F}),e.jsx(u.default,{sender:t.sender,content:t.content,isNew:t.isNew,showSuggestions:r===M.length-1,onSuggestionClicked:R},t.id)]},t.id))),re&&e.jsx(u.default,{sender:"user",content:w("Översätter...")}),V&&e.jsx(a.default,{})]}),e.jsx(l.default,{codicent:A||r.context.selectedApp,disableSend:V,onSend:de,onSelectFiles:le,getImageUrl:p.CodicentService.getImageUrl,getFileInfo:e=>W.getFileInfo(e)})]}),e.jsx(i.default,{open:B,title:w("Vill du rensa chatten?"),content:w("En ny startas, men chatten kommer först sparas."),onYes:()=>{U(!1),L()},onNo:()=>U(!1)}),e.jsx(c.CombinedPlaceholderDialog,{open:K,templateVariables:Q,filePlaceholders:Y,onTemplateVariablesChange:G,onFilePlaceholdersChange:$,onConfirm:()=>J(!1),onCancel:()=>{J(!1),N(null),G([]),$([])},uploadFile:W.uploadFile})]})};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),r=require("@fluentui/react-components"),n=require("react-router-dom"),s=require("@fluentui/react-icons");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("../components/Spinner.js");var o=require("../components/TextHeader.js"),a=require("../components/TypingIndicator.js"),i=require("../components/Prompt.js"),l=require("../components/ChatInput.js"),c=require("../components/CombinedPlaceholderDialog.js"),u=require("../components/ChatMessage.js");require("../components/Header.js");var d=require("../hooks/useStateWithLocalStorage.js"),p=require("../services/codicent.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js");var m=require("../config/index.js");require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./AppFrame.js"),require("./Compose.js"),require("./Snap.js"),require("./Search.js"),require("./Login.js"),require("./CrmPage.js"),require("./CrmPagePersistent.js"),require("./ImageView.js"),require("./FormInvite.js"),require("./FormAccept.js"),require("./Sales.js"),require("./Purchase.js"),require("../components/Content.js");var g=require("../components/Page.js");require("./QrScan.js");var h=require("../hooks/useLocalization.js");require("../components/FileThumbnail.js"),require("react-dom/client"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");var j=require("../hooks/useChat.js"),f=require("../hooks/useTemplateVariables.js");require("../hooks/useAppStyles.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js");const q=r.makeStyles({chatContainer:{width:"100%",flex:1,maxWidth:"1600px",height:"100%",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"}});exports.default=({state:r,hideFooter:x,codicent:C,title:S,welcomeMessage:b})=>{const v=q(),{t:w,tAsync:y,getLanguageInfo:P}=h.default(),k=n.useNavigate(),F=t.useRef(null),[T,_]=n.useSearchParams(),I=T.get("codicent"),A=I||C,{messages:M,isBotTyping:V,handleSend:R,newChat:L,openChat:E}=j.useChat(r.stateMachine,A||void 0),[H,N]=t.useState(null),[B,U]=t.useState(!1),[O,D]=t.useState(!1),{service:W,currentStateName:z}=r,[Q,G]=t.useState([]),[Y,$]=t.useState([]),[K,J]=t.useState(!1),[X,Z]=t.useState(),[ee,te]=d.default(r.context.selectedApp+"_prompts",[]),[re,ne]=t.useState(!1),{extractTemplateVariables:se,replaceTemplateVariables:oe,extractFilePlaceholders:ae,replaceFilePlaceholders:ie,handleSelectFiles:le}=f.useTemplateVariables(W.uploadFile),ce=t.useRef(!1),ue=t.useRef(null);t.useEffect((()=>{const e=window.history.length>1,t=Boolean(document.referrer&&document.referrer!==window.location.href);D(e||t)}),[]);t.useEffect((()=>{m.getConfigValue("SHOW_CHAT_PROMPTS")&&0===M.length&&r.service.getAppPrompts().then(te).catch((e=>{console.error("Failed to get prompts",e)}))}),[r.service,te,M.length]),t.useEffect((()=>{setTimeout((()=>{F.current?.scrollIntoView({behavior:"smooth"})}),10)}),[M]),t.useEffect((()=>{if(ce.current)return;ce.current=!0;const e=T.get("text"),t=T.get("id"),r=T.get("fid");if(I){console.log("Using temporary codicent from URL param:",I);const e=new URLSearchParams(T);e.delete("codicent"),_(e,{replace:!0})}if(e){(async()=>{const t=ae(e),r=se(e);L(),t.length>0||r.length>0?($(t),G(r),J(!0),N(w(e))):N(w(e))})()}else t?E(t):r&&Z(r)}),[]),t.useEffect((()=>{X&&"anonymous"===z&&ue.current!==X&&(ue.current=X,W.getFormById(X).then((async e=>{L();const t=P().language,r=e.prompt.replace("{{fid}}",X).replace("{{fname}}",e.name).replace("{{language}}",t);ne(!0);const n=await y(r);ne(!1),N(n),D(!1)})))}),[X,L,W,N,z,y,P,ne]),t.useEffect((()=>{if(H&&!K){let e=H;Y.length>0&&(e=ie(e,Y)),Q.length>0&&(e=oe(e,Q)),R(e),_({},{replace:!0}),N(null),G([]),$([])}}),[H,K,R,_,ie,oe,Y,Q]);const de=e=>{const t=T.get("append");t&&(e+="\n---\n"+t),R(e)};return e.jsxs(g.Page,{hideHeader:!0,hideFooter:!!X||x,children:[e.jsxs("div",{id:"chat-container",className:v.chatContainer,style:{backgroundImage:`url(${m.getConfigValue("CHAT_BACKGROUND_IMAGE_URL")})`},children:[O&&e.jsx("button",{onClick:()=>{O&&k(-1)},"aria-label":w("Tillbaka"),style:{position:"absolute",top:12,left:12,zIndex:100,background:"var(--colorNeutralBackground1)",border:"none",cursor:"pointer",padding:8,borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.08)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(s.CalendarWeekStart24Regular,{style:{transform:"rotate(180deg)"}})}),e.jsx("div",{style:{marginLeft:O?40:0},children:e.jsx(o.default,{title:S||w(m.getConfigValue("APP_CHAT_TITLE")||"Chatt"),onNewChat:X?void 0:()=>U(!0)})}),e.jsxs("div",{className:v.chatMessages,children:[b&&e.jsx(u.default,{sender:"bot",content:b}),m.getConfigValue("SHOW_CHAT_PROMPTS")&&ee.length>0&&0===M.length&&e.jsx(u.default,{sender:"bot",content:w(m.getConfigValue("CHAT_WELCOME")||w("Välkommen!")),children:ee.map(((t,r)=>e.jsxs("div",{children:["> ",e.jsx("a",{href:"./#/chat",onClick:()=>{de(t.title+"\n---\n"+t.prompt)},children:w(t.title)}),e.jsx("br",{})]},`prompt-${r}`)))}),M.map(((t,r)=>e.jsxs("div",{children:[(V&&r===M.length-1||!V&&r===M.length-2)&&e.jsx("div",{ref:F}),e.jsx(u.default,{sender:t.sender,content:t.content,isNew:t.isNew,showSuggestions:r===M.length-1,onSuggestionClicked:R},t.id)]},t.id))),re&&e.jsx(u.default,{sender:"user",content:w("Översätter...")}),V&&e.jsx(a.default,{})]}),e.jsx(l.default,{codicent:A||r.context.selectedApp,disableSend:V,onSend:de,onSelectFiles:le,getImageUrl:p.CodicentService.getImageUrl,getFileInfo:e=>W.getFileInfo(e)})]}),e.jsx(i.default,{open:B,title:w("Vill du rensa chatten?"),content:w("En ny startas, men chatten kommer först sparas."),onYes:()=>{U(!1),L()},onNo:()=>U(!1)}),e.jsx(c.CombinedPlaceholderDialog,{open:K,templateVariables:Q,filePlaceholders:Y,onTemplateVariablesChange:G,onFilePlaceholdersChange:$,onConfirm:()=>J(!1),onCancel:()=>{J(!1),N(null),G([]),$([])},uploadFile:W.uploadFile})]})};
@@ -54,7 +54,9 @@ export interface CodicentServiceOptions {
54
54
  }
55
55
  export declare class CodicentService {
56
56
  createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
57
- readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
57
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string, dataFilters?: {
58
+ [key: string]: string;
59
+ }) => Promise<DataMessage[]>;
58
60
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
59
61
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
60
62
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,UAAU,QAAS,MAAM,SAerC,CAAC;AA8BF,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE;QAAE,aAAa,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IACvC,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;IAC9C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED,MAAM,WAAW,OAAO;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,IAAI;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,MAAM,CAAC;IACrB,gBAAgB,EAAE,MAAM,CAAC;IACz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a,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,EAAE,QAAQ,GAAE,MAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsB9F,iBAAiB,CAAC,QAAQ,GAAE,MAAiB,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoBzG;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CAsB7B;CACH"}
@@ -1 +1 @@
1
- "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},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:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},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 o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.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 o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,s(t.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.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 o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=c,exports.setBaseUrl=s;
1
+ "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},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:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},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 o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.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 o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,s(t.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.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 o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=c,exports.setBaseUrl=s;
@@ -1 +1 @@
1
- {"version":3,"file":"Footer.d.ts","sourceRoot":"","sources":["../../../src/components/Footer.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AA8EnD,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,EAgH1B,CAAC;AAEF,eAAe,MAAM,CAAC"}
1
+ {"version":3,"file":"Footer.d.ts","sourceRoot":"","sources":["../../../src/components/Footer.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAyFnD,eAAO,MAAM,MAAM,EAAE,KAAK,CAAC,EAwI1B,CAAC;AAEF,eAAe,MAAM,CAAC"}
@@ -1 +1 @@
1
- import{jsx as o,jsxs as e}from"react/jsx-runtime";import{useState as t,useEffect as s}from"react";import{makeStyles as a,shorthands as i,tokens as r}from"@fluentui/react-components";import{Home24Filled as n,Home24Regular as l,Chat24Filled as m,Chat24Regular as p,AddSquare24Filled as c,AddSquare24Regular as d,ClipboardDay24Filled as j,ClipboardDay24Regular as u,SlideText24Filled as g,SlideText24Regular as h,Whiteboard24Filled as T,Whiteboard24Regular as _,Apps24Filled as v,Apps24Regular as x}from"@fluentui/react-icons";import{useLocation as O,Link as C}from"react-router-dom";import"../services/codicent.js";import"./Markdown.js";import"./Textarea.js";import"./Button.js";import"./CompoundButton.js";import"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as N}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./FileThumbnail.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./Content.js";import"./AiInput.js";import"./SearchBox.js";import"./HtmlView.js";import"./Page.js";import"./QrCodeDialog.js";import"./QrScanner.js";import b from"../hooks/useLocalization.js";import"./OfflineMessage.js";import"./LanguageSelector.js";import"./ListView.js";import"./RecordModal.js";import"./BulkUploadDialog.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import"../hooks/useAppStyles.js";const f=a({footer:{...i.padding("14px"),textAlign:"center",display:"flex",justifyContent:"space-around",alignItems:"center",position:"sticky",bottom:0,zIndex:1e3,paddingBottom:"22px",width:"100%"},container:{display:"flex",justifyContent:"space-around",alignItems:"center",maxWidth:"480px",width:"100%"},button:{color:r.colorNeutralForegroundOnBrand,height:"24px",width:"24px",...i.borderWidth("0")},link:{textDecoration:"none",color:"inherit",display:"flex",flexDirection:"column",alignItems:"center","&.selected":{border:"none"},"&:hover":{textDecoration:"none"}},buttonText:{fontSize:"12px"}}),k=()=>{const a=f(),i=O(),[k,y]=t(null),{t:S}=b(),P={backgroundColor:N("APP_FOOTER_COLOR")||r.colorBrandBackground,color:N("APP_FOOTER_TEXT_COLOR")||r.colorNeutralForegroundOnBrand},A=N("APP_FOOTER_SELECTED_COLOR")||void 0;return s((()=>{const o=i.pathname;"/"===o?y("home"):"/chat"===o?y("chat"):"/new"===o?y("save"):"/menu"===o?y("menu"):"/log"===o?y("log"):"/canvas"===o?y("canvas"):"/snap"===o&&y("snap")}),[i]),s((()=>{k&&console.log(`footer-button: ${k}`)}),[k]),o("footer",{className:a.footer,style:P,children:e("div",{className:a.container,children:[e(C,{to:"/",className:`${a.link} ${"home"===k?"selected":""}`,onClick:()=>y("home"),style:"home"===k?{color:A}:void 0,children:[o("home"===k?n:l,{}),o("p",{className:a.buttonText,children:S("Hem")})]}),!N("HIDE_CHAT_BUTTON")&&e(C,{to:"/chat",className:`${a.link} ${"chat"===k?"selected":""}`,onClick:()=>y("chat"),style:"chat"===k?{color:A}:void 0,children:[o("chat"===k?m:p,{}),o("p",{className:a.buttonText,children:S(N("APP_CHAT_TITLE")||"Chatt")})]}),!N("HIDE_SAVE_BUTTON")&&e(C,{to:"/new",className:`${a.link} ${"save"===k?"selected":""}`,onClick:()=>y("save"),style:"save"===k?{color:A}:void 0,children:[o("save"===k?c:d,{}),o("p",{className:a.buttonText,children:S(N("APP_SAVE_TITLE")||"Spara")})]}),N("SHOW_SNAP_BUTTON")&&e(C,{to:"/snap",className:`${a.link} ${"snap"===k?"selected":""}`,onClick:()=>y("snap"),style:"snap"===k?{color:A}:void 0,children:[o("snap"===k?j:u,{}),o("p",{className:a.buttonText,children:S("Snap")})]}),N("SHOW_LOGBOOK_BUTTON")&&e(C,{to:"/log",className:`${a.link} ${"log"===k?"selected":""}`,onClick:()=>y("log"),style:"log"===k?{color:A}:void 0,children:[o("log"===k?g:h,{}),o("p",{className:a.buttonText,children:S(N("APP_LOGBOOK_TITLE")||"Loggbok")})]}),N("SHOW_CANVAS_BUTTON")&&e(C,{to:"/canvas",className:`${a.link} ${"canvas"===k?"selected":""}`,onClick:()=>y("canvas"),style:"canvas"===k?{color:A}:void 0,children:[o("canvas"===k?T:_,{}),o("p",{className:a.buttonText,children:S("Kanvas")})]}),!N("HIDE_MENU_BUTTON")&&e(C,{to:"/menu",className:`${a.link} ${"menu"===k?"selected":""}`,onClick:()=>y("menu"),style:"menu"===k?{color:A}:void 0,children:[o("menu"===k?v:x,{}),o("p",{className:a.buttonText,children:S("Meny")})]})]})})};export{k as Footer,k as default};
1
+ import{jsx as o,jsxs as e}from"react/jsx-runtime";import{useState as t,useEffect as i}from"react";import{makeStyles as a,shorthands as s,tokens as r,Badge as n}from"@fluentui/react-components";import{Home24Filled as l,Home24Regular as c,Chat24Filled as p,Chat24Regular as m,AddSquare24Filled as d,AddSquare24Regular as g,ClipboardDay24Filled as u,ClipboardDay24Regular as j,SlideText24Filled as h,SlideText24Regular as v,Whiteboard24Filled as T,Whiteboard24Regular as f,Apps24Filled as x,Apps24Regular as _}from"@fluentui/react-icons";import{useLocation as b,Link as k}from"react-router-dom";import"../services/codicent.js";import"./Markdown.js";import"./Textarea.js";import"./Button.js";import"./CompoundButton.js";import"./Spinner.js";import"./TextHeader.js";import"./TypingIndicator.js";import"./Dialog.js";import"./ChatInput.js";import"./CombinedPlaceholderDialog.js";import"./ChatMessage.js";import"./Header.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as C}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./FileThumbnail.js";import"./MessageInput.js";import"./UploadFile.js";import"./SnapFooter.js";import"./Profile.js";import"./MessageItem.js";import"./Content.js";import"./AiInput.js";import"./SearchBox.js";import"./HtmlView.js";import"./Page.js";import"./QrCodeDialog.js";import"./QrScanner.js";import O from"../hooks/useLocalization.js";import"./OfflineMessage.js";import"./LanguageSelector.js";import"./ListView.js";import"./RecordModal.js";import"./BulkUploadDialog.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import"../hooks/useAppStyles.js";const N=a({footer:{...s.padding("14px"),textAlign:"center",display:"flex",justifyContent:"space-around",alignItems:"center",position:"sticky",bottom:0,zIndex:1e3,paddingBottom:"22px",width:"100%"},container:{display:"flex",justifyContent:"space-around",alignItems:"center",maxWidth:"480px",width:"100%"},button:{color:r.colorNeutralForegroundOnBrand,height:"24px",width:"24px",...s.borderWidth("0")},link:{textDecoration:"none",color:"inherit",display:"flex",flexDirection:"column",alignItems:"center","&.selected":{border:"none"},"&:hover":{textDecoration:"none"}},buttonText:{fontSize:"12px"},logbookIconWrapper:{position:"relative",display:"inline-flex",alignItems:"center",justifyContent:"center"},notificationBadge:{position:"absolute",top:"-4px",right:"-4px"}}),w=()=>{const a=N(),s=b(),[w,y]=t(null),{t:S}=O(),[I,E]=t((()=>"true"===localStorage.getItem("logbook-has-notification"))),P={backgroundColor:C("APP_FOOTER_COLOR")||r.colorBrandBackground,color:C("APP_FOOTER_TEXT_COLOR")||r.colorNeutralForegroundOnBrand},B=C("APP_FOOTER_SELECTED_COLOR")||void 0;return i((()=>{const o=s.pathname;"/"===o?y("home"):"/chat"===o?y("chat"):"/new"===o?y("save"):"/menu"===o?y("menu"):"/log"===o?y("log"):"/canvas"===o?y("canvas"):"/snap"===o&&y("snap")}),[s]),i((()=>{w&&console.log(`footer-button: ${w}`)}),[w]),i((()=>{const o=()=>{E("true"===localStorage.getItem("logbook-has-notification"))};return window.addEventListener("storage",o),window.addEventListener("logbook-notification-changed",o),()=>{window.removeEventListener("storage",o),window.removeEventListener("logbook-notification-changed",o)}}),[]),o("footer",{className:a.footer,style:P,children:e("div",{className:a.container,children:[e(k,{to:"/",className:`${a.link} ${"home"===w?"selected":""}`,onClick:()=>y("home"),style:"home"===w?{color:B}:void 0,children:[o("home"===w?l:c,{}),o("p",{className:a.buttonText,children:S("Hem")})]}),!C("HIDE_CHAT_BUTTON")&&e(k,{to:"/chat",className:`${a.link} ${"chat"===w?"selected":""}`,onClick:()=>y("chat"),style:"chat"===w?{color:B}:void 0,children:[o("chat"===w?p:m,{}),o("p",{className:a.buttonText,children:S(C("APP_CHAT_TITLE")||"Chatt")})]}),!C("HIDE_SAVE_BUTTON")&&e(k,{to:"/new",className:`${a.link} ${"save"===w?"selected":""}`,onClick:()=>y("save"),style:"save"===w?{color:B}:void 0,children:[o("save"===w?d:g,{}),o("p",{className:a.buttonText,children:S(C("APP_SAVE_TITLE")||"Spara")})]}),C("SHOW_SNAP_BUTTON")&&e(k,{to:"/snap",className:`${a.link} ${"snap"===w?"selected":""}`,onClick:()=>y("snap"),style:"snap"===w?{color:B}:void 0,children:[o("snap"===w?u:j,{}),o("p",{className:a.buttonText,children:S("Snap")})]}),C("SHOW_LOGBOOK_BUTTON")&&e(k,{to:"/log",className:`${a.link} ${"log"===w?"selected":""}`,onClick:()=>{y("log"),localStorage.removeItem("logbook-has-notification"),E(!1)},style:"log"===w?{color:B}:void 0,children:[e("div",{className:a.logbookIconWrapper,children:[o("log"===w?h:v,{}),I&&"log"!==w&&o(n,{appearance:"filled",color:"danger",size:"extra-small",className:a.notificationBadge})]}),o("p",{className:a.buttonText,children:S(C("APP_LOGBOOK_TITLE")||"Loggbok")})]}),C("SHOW_CANVAS_BUTTON")&&e(k,{to:"/canvas",className:`${a.link} ${"canvas"===w?"selected":""}`,onClick:()=>y("canvas"),style:"canvas"===w?{color:B}:void 0,children:[o("canvas"===w?T:f,{}),o("p",{className:a.buttonText,children:S("Kanvas")})]}),!C("HIDE_MENU_BUTTON")&&e(k,{to:"/menu",className:`${a.link} ${"menu"===w?"selected":""}`,onClick:()=>y("menu"),style:"menu"===w?{color:B}:void 0,children:[o("menu"===w?x:_,{}),o("p",{className:a.buttonText,children:S("Meny")})]})]})})};export{w as Footer,w as default};
@@ -1 +1 @@
1
- import{jsxs as e,jsx as o}from"react/jsx-runtime";import{useRef as t,useState as n,useEffect as r}from"react";import{makeStyles as s}from"@fluentui/react-components";import{useNavigate as i,useSearchParams as a}from"react-router-dom";import{CalendarWeekStart24Regular as m}from"@fluentui/react-icons";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"../components/Spinner.js";import l from"../components/TextHeader.js";import c from"../components/TypingIndicator.js";import p from"../components/Prompt.js";import d from"../components/ChatInput.js";import{CombinedPlaceholderDialog as h}from"../components/CombinedPlaceholderDialog.js";import g from"../components/ChatMessage.js";import"../components/Header.js";import u from"../hooks/useStateWithLocalStorage.js";import{CodicentService as j}from"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as f}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./AppFrame.js";import"./Compose.js";import"./Snap.js";import"./Search.js";import"./Login.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"./Purchase.js";import"../components/Content.js";import{Page as b}from"../components/Page.js";import"./QrScan.js";import C from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useChat as x}from"../hooks/useChat.js";import{useTemplateVariables as w}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";const S=s({chatContainer:{width:"100%",flex:1,maxWidth:"800px",height:"100%",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"}}),v=({state:s,hideFooter:v,codicent:y,title:F,welcomeMessage:P})=>{const k=S(),{t:T,tAsync:I,getLanguageInfo:_}=C(),A=i(),M=t(null),[L,H]=a(),V=L.get("codicent"),R=V||y,{messages:B,isBotTyping:N,handleSend:U,newChat:O,openChat:D}=x(s.stateMachine,R||void 0),[W,E]=n(null),[z,Q]=n(!1),[G,Y]=n(!1),{service:$,currentStateName:K}=s,[q,J]=n([]),[X,Z]=n([]),[ee,oe]=n(!1),[te,ne]=n(),[re,se]=u(s.context.selectedApp+"_prompts",[]),[ie,ae]=n(!1),{extractTemplateVariables:me,replaceTemplateVariables:le,extractFilePlaceholders:ce,replaceFilePlaceholders:pe,handleSelectFiles:de}=w($.uploadFile),he=t(!1),ge=t(null);r((()=>{const e=window.history.length>1,o=Boolean(document.referrer&&document.referrer!==window.location.href);Y(e||o)}),[]);r((()=>{f("SHOW_CHAT_PROMPTS")&&0===B.length&&s.service.getAppPrompts().then(se).catch((e=>{console.error("Failed to get prompts",e)}))}),[s.service,se,B.length]),r((()=>{setTimeout((()=>{M.current?.scrollIntoView({behavior:"smooth"})}),10)}),[B]),r((()=>{if(he.current)return;he.current=!0;const e=L.get("text"),o=L.get("id"),t=L.get("fid");if(V){console.log("Using temporary codicent from URL param:",V);const e=new URLSearchParams(L);e.delete("codicent"),H(e,{replace:!0})}if(e){(async()=>{const o=ce(e),t=me(e);O(),o.length>0||t.length>0?(Z(o),J(t),oe(!0),E(T(e))):E(T(e))})()}else o?D(o):t&&ne(t)}),[]),r((()=>{te&&"anonymous"===K&&ge.current!==te&&(ge.current=te,$.getFormById(te).then((async e=>{O();const o=_().language,t=e.prompt.replace("{{fid}}",te).replace("{{fname}}",e.name).replace("{{language}}",o);ae(!0);const n=await I(t);ae(!1),E(n),Y(!1)})))}),[te,O,$,E,K,I,_,ae]),r((()=>{if(W&&!ee){let e=W;X.length>0&&(e=pe(e,X)),q.length>0&&(e=le(e,q)),U(e),H({},{replace:!0}),E(null),J([]),Z([])}}),[W,ee,U,H,pe,le,X,q]);const ue=e=>{const o=L.get("append");o&&(e+="\n---\n"+o),U(e)};return e(b,{hideHeader:!0,hideFooter:!!te||v,children:[e("div",{id:"chat-container",className:k.chatContainer,style:{backgroundImage:`url(${f("CHAT_BACKGROUND_IMAGE_URL")})`},children:[G&&o("button",{onClick:()=>{G&&A(-1)},"aria-label":T("Tillbaka"),style:{position:"absolute",top:12,left:12,zIndex:100,background:"var(--colorNeutralBackground1)",border:"none",cursor:"pointer",padding:8,borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.08)",display:"flex",alignItems:"center",justifyContent:"center"},children:o(m,{style:{transform:"rotate(180deg)"}})}),o("div",{style:{marginLeft:G?40:0},children:o(l,{title:F||T(f("APP_CHAT_TITLE")||"Chatt"),onNewChat:te?void 0:()=>Q(!0)})}),e("div",{className:k.chatMessages,children:[P&&o(g,{sender:"bot",content:P}),f("SHOW_CHAT_PROMPTS")&&re.length>0&&0===B.length&&o(g,{sender:"bot",content:T(f("CHAT_WELCOME")||T("Välkommen!")),children:re.map(((t,n)=>e("div",{children:["> ",o("a",{href:"./#/chat",onClick:()=>{ue(t.title+"\n---\n"+t.prompt)},children:T(t.title)}),o("br",{})]},`prompt-${n}`)))}),B.map(((t,n)=>e("div",{children:[(N&&n===B.length-1||!N&&n===B.length-2)&&o("div",{ref:M}),o(g,{sender:t.sender,content:t.content,isNew:t.isNew,showSuggestions:n===B.length-1,onSuggestionClicked:U},t.id)]},t.id))),ie&&o(g,{sender:"user",content:T("Översätter...")}),N&&o(c,{})]}),o(d,{codicent:R||s.context.selectedApp,disableSend:N,onSend:ue,onSelectFiles:de,getImageUrl:j.getImageUrl,getFileInfo:e=>$.getFileInfo(e)})]}),o(p,{open:z,title:T("Vill du rensa chatten?"),content:T("En ny startas, men chatten kommer först sparas."),onYes:()=>{Q(!1),O()},onNo:()=>Q(!1)}),o(h,{open:ee,templateVariables:q,filePlaceholders:X,onTemplateVariablesChange:J,onFilePlaceholdersChange:Z,onConfirm:()=>oe(!1),onCancel:()=>{oe(!1),E(null),J([]),Z([])},uploadFile:$.uploadFile})]})};export{v as default};
1
+ import{jsxs as e,jsx as o}from"react/jsx-runtime";import{useRef as t,useState as n,useEffect as r}from"react";import{makeStyles as s}from"@fluentui/react-components";import{useNavigate as i,useSearchParams as a}from"react-router-dom";import{CalendarWeekStart24Regular as m}from"@fluentui/react-icons";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"../components/Spinner.js";import l from"../components/TextHeader.js";import c from"../components/TypingIndicator.js";import p from"../components/Prompt.js";import d from"../components/ChatInput.js";import{CombinedPlaceholderDialog as h}from"../components/CombinedPlaceholderDialog.js";import g from"../components/ChatMessage.js";import"../components/Header.js";import u from"../hooks/useStateWithLocalStorage.js";import{CodicentService as j}from"../services/codicent.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import{getConfigValue as f}from"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./AppFrame.js";import"./Compose.js";import"./Snap.js";import"./Search.js";import"./Login.js";import"./CrmPage.js";import"./CrmPagePersistent.js";import"./ImageView.js";import"./FormInvite.js";import"./FormAccept.js";import"./Sales.js";import"./Purchase.js";import"../components/Content.js";import{Page as b}from"../components/Page.js";import"./QrScan.js";import C from"../hooks/useLocalization.js";import"../components/FileThumbnail.js";import"react-dom/client";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";import{useChat as x}from"../hooks/useChat.js";import{useTemplateVariables as w}from"../hooks/useTemplateVariables.js";import"../hooks/useAppStyles.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";const S=s({chatContainer:{width:"100%",flex:1,maxWidth:"1600px",height:"100%",display:"flex",flexDirection:"column",margin:"0 auto",overflow:"hidden","@media (max-width: 768px)":{maxWidth:"100%",borderRadius:"0"},"@media (max-width: 480px)":{},backgroundPosition:"calc(50%) center",backgroundRepeat:"no-repeat",backgroundSize:"contain",touchAction:"pan-y"},chatMessages:{display:"flex",flexDirection:"column",flex:1,padding:"16px",overflowY:"auto",touchAction:"pan-y"}}),v=({state:s,hideFooter:v,codicent:y,title:F,welcomeMessage:P})=>{const k=S(),{t:T,tAsync:I,getLanguageInfo:_}=C(),A=i(),M=t(null),[L,H]=a(),V=L.get("codicent"),R=V||y,{messages:B,isBotTyping:N,handleSend:U,newChat:O,openChat:D}=x(s.stateMachine,R||void 0),[W,E]=n(null),[z,Q]=n(!1),[G,Y]=n(!1),{service:$,currentStateName:K}=s,[q,J]=n([]),[X,Z]=n([]),[ee,oe]=n(!1),[te,ne]=n(),[re,se]=u(s.context.selectedApp+"_prompts",[]),[ie,ae]=n(!1),{extractTemplateVariables:me,replaceTemplateVariables:le,extractFilePlaceholders:ce,replaceFilePlaceholders:pe,handleSelectFiles:de}=w($.uploadFile),he=t(!1),ge=t(null);r((()=>{const e=window.history.length>1,o=Boolean(document.referrer&&document.referrer!==window.location.href);Y(e||o)}),[]);r((()=>{f("SHOW_CHAT_PROMPTS")&&0===B.length&&s.service.getAppPrompts().then(se).catch((e=>{console.error("Failed to get prompts",e)}))}),[s.service,se,B.length]),r((()=>{setTimeout((()=>{M.current?.scrollIntoView({behavior:"smooth"})}),10)}),[B]),r((()=>{if(he.current)return;he.current=!0;const e=L.get("text"),o=L.get("id"),t=L.get("fid");if(V){console.log("Using temporary codicent from URL param:",V);const e=new URLSearchParams(L);e.delete("codicent"),H(e,{replace:!0})}if(e){(async()=>{const o=ce(e),t=me(e);O(),o.length>0||t.length>0?(Z(o),J(t),oe(!0),E(T(e))):E(T(e))})()}else o?D(o):t&&ne(t)}),[]),r((()=>{te&&"anonymous"===K&&ge.current!==te&&(ge.current=te,$.getFormById(te).then((async e=>{O();const o=_().language,t=e.prompt.replace("{{fid}}",te).replace("{{fname}}",e.name).replace("{{language}}",o);ae(!0);const n=await I(t);ae(!1),E(n),Y(!1)})))}),[te,O,$,E,K,I,_,ae]),r((()=>{if(W&&!ee){let e=W;X.length>0&&(e=pe(e,X)),q.length>0&&(e=le(e,q)),U(e),H({},{replace:!0}),E(null),J([]),Z([])}}),[W,ee,U,H,pe,le,X,q]);const ue=e=>{const o=L.get("append");o&&(e+="\n---\n"+o),U(e)};return e(b,{hideHeader:!0,hideFooter:!!te||v,children:[e("div",{id:"chat-container",className:k.chatContainer,style:{backgroundImage:`url(${f("CHAT_BACKGROUND_IMAGE_URL")})`},children:[G&&o("button",{onClick:()=>{G&&A(-1)},"aria-label":T("Tillbaka"),style:{position:"absolute",top:12,left:12,zIndex:100,background:"var(--colorNeutralBackground1)",border:"none",cursor:"pointer",padding:8,borderRadius:8,boxShadow:"0 2px 8px rgba(0,0,0,0.08)",display:"flex",alignItems:"center",justifyContent:"center"},children:o(m,{style:{transform:"rotate(180deg)"}})}),o("div",{style:{marginLeft:G?40:0},children:o(l,{title:F||T(f("APP_CHAT_TITLE")||"Chatt"),onNewChat:te?void 0:()=>Q(!0)})}),e("div",{className:k.chatMessages,children:[P&&o(g,{sender:"bot",content:P}),f("SHOW_CHAT_PROMPTS")&&re.length>0&&0===B.length&&o(g,{sender:"bot",content:T(f("CHAT_WELCOME")||T("Välkommen!")),children:re.map(((t,n)=>e("div",{children:["> ",o("a",{href:"./#/chat",onClick:()=>{ue(t.title+"\n---\n"+t.prompt)},children:T(t.title)}),o("br",{})]},`prompt-${n}`)))}),B.map(((t,n)=>e("div",{children:[(N&&n===B.length-1||!N&&n===B.length-2)&&o("div",{ref:M}),o(g,{sender:t.sender,content:t.content,isNew:t.isNew,showSuggestions:n===B.length-1,onSuggestionClicked:U},t.id)]},t.id))),ie&&o(g,{sender:"user",content:T("Översätter...")}),N&&o(c,{})]}),o(d,{codicent:R||s.context.selectedApp,disableSend:N,onSend:ue,onSelectFiles:de,getImageUrl:j.getImageUrl,getFileInfo:e=>$.getFileInfo(e)})]}),o(p,{open:z,title:T("Vill du rensa chatten?"),content:T("En ny startas, men chatten kommer först sparas."),onYes:()=>{Q(!1),O()},onNo:()=>Q(!1)}),o(h,{open:ee,templateVariables:q,filePlaceholders:X,onTemplateVariablesChange:J,onFilePlaceholdersChange:Z,onConfirm:()=>oe(!1),onCancel:()=>{oe(!1),E(null),J([]),Z([])},uploadFile:$.uploadFile})]})};export{v as default};
@@ -54,7 +54,9 @@ export interface CodicentServiceOptions {
54
54
  }
55
55
  export declare class CodicentService {
56
56
  createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
57
- readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
57
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string, dataFilters?: {
58
+ [key: string]: string;
59
+ }) => Promise<DataMessage[]>;
58
60
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
59
61
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
60
62
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"codicent.d.ts","sourceRoot":"","sources":["../../../src/services/codicent.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,UAAU,QAAS,MAAM,SAerC,CAAC;AA8BF,MAAM,WAA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,GAAE,MAAiB,GAAG,OAAO,CAAC,MAAM,CAAC;IAsB9F,iBAAiB,CAAC,QAAQ,GAAE,MAAiB,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC;IAoBzG;;;;;;OAMG;IACH,MAAM,CAAC,eAAe,SACd,MAAM,kBACI,MAAM,YACb,MAAM,KACd,OAAO,CAAC,mBAAmB,CAAC,CAsB7B;CACH"}
@@ -1 +1 @@
1
- import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},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:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,s(o.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()};export{c as CodicentService,s as setBaseUrl};
1
+ import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},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:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,s(o.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3)=>{const r={project:e,message:t};let c;o&&(r.messageId=o);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(r)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(c=(await t.json()).promptMessageId,!c)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const h=Date.now();for(;Date.now()-h<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${c}`,{method:"GET",headers:[["Authorization",`Bearer ${n}`]]});if(202===t.status){await new Promise((t=>setTimeout(t,i)));continue}if(!t.ok)return void console.error(`Error polling AI chat status: ${t.status}`);const o=await t.json();return o.content.replace(`@${e}`,"").replace("@codicent-mini","").trim()}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()};export{c as CodicentService,s as setBaseUrl};
package/dist/index.d.ts CHANGED
@@ -67,7 +67,9 @@ interface CodicentServiceOptions {
67
67
  }
68
68
  declare class CodicentService {
69
69
  createDataMessage: (tag: string, data: object, codicent?: string) => Promise<string>;
70
- readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
70
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string, dataFilters?: {
71
+ [key: string]: string;
72
+ }) => Promise<DataMessage[]>;
71
73
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
72
74
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
73
75
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.4.7",
3
+ "version": "0.4.9",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",