codicent-app-sdk 0.4.3 → 0.4.6

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.
@@ -14,7 +14,9 @@ export interface ColumnDefinition {
14
14
  hidden?: boolean;
15
15
  hideOnMobile?: boolean;
16
16
  maxWidth?: number;
17
- type?: "file" | "checkbox" | undefined;
17
+ type?: "file" | "checkbox" | "textarea" | undefined;
18
+ /** Number of rows for textarea type (default: 3) */
19
+ rows?: number;
18
20
  editable?: boolean;
19
21
  filterable?: boolean;
20
22
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
@@ -1 +1 @@
1
- {"version":3,"file":"ListView.d.ts","sourceRoot":"","sources":["../../../src/components/ListView.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAgB5D,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,kHAAkH;IAClH,IAAI,EAAE,KAAK,CAAC,aAAa,CAAC;IAC1B,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CACrD;AA2JD,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gHAAgH;IAChH,WAAW,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IAC7B,2HAA2H;IAC3H,MAAM,CAAC,E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O,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACrH,oBAAoB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC;CAC1E;AAID,eAAO,MAAM,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,aAAa,CAic5C,CAAC;;AAGF,wBAAoC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=require("@fluentui/react-components"),i=require("@fluentui/react-icons"),r=require("../services/codicent.js"),o=require("../hooks/useLocalization.js");const l=n.makeStyles({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),a=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},s=({data:s,columns:c,canEdit:d,onEdit:p,onDelete:h,onToggleCheckbox:x,onFilteredDataChange:u})=>{const f=l(),{visibleColumns:m,defaultSortIndex:g,defaultSortDirection:j}=t.useMemo((()=>{const e=s&&s.length>0?Array.from(new Set(s.flatMap((e=>Object.keys(e))))):[],t=(c||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[s,c]),[y,b]=t.useState(g>=0?g:null),[w,S]=t.useState(j),[C,k]=t.useState(!1),[v,W]=t.useState({title:"",text:""}),[N,$]=t.useState({}),[M,B]=t.useState(0),{t:D}=o.default(),I=e=>e.title?D(e.title):Array.isArray(e.key)?e.key[0]:e.key,A=e=>{const t=[];return e.hideOnMobile&&t.push(f.hideOnMobile),t.join(" ")},T=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),O=[...s];if(null!==y&&w){const e=m[y];O.sort(((t,n)=>{const i=a(t,e.key),r=a(n,e.key);if(null==i)return 1;if(null==r)return-1;let o=0;return o="string"==typeof i&&"string"==typeof r?i.localeCompare(r):"number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r)),"asc"===w?o:-o}))}const F=t.useMemo((()=>O.filter((e=>{for(const[t,n]of Object.entries(N)){const i=parseInt(t),r=m[i],o=a(e,r.key),l=T(o).toLowerCase(),s=n.toLowerCase();if(!l.includes(s))return!1}return!0}))),[O,N,m]);t.useEffect((()=>{u&&u(F)}),[F,u]);const L="undefined"!=typeof window?window.innerHeight-250:600,q=Math.max(0,Math.floor(M/49)-5),z=Math.min(F.length,Math.ceil((M+L)/49)+5),E=F.slice(q,z),H=49*F.length,P=49*q,R=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(m.slice(0,3).map((t=>String(a(e,t.key)??""))).join("-"))}`};return s&&0!==s.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:f.container,onScroll:e=>{B(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:e.jsxs("table",{className:f.table,children:[e.jsxs("thead",{children:[e.jsxs("tr",{children:[m.map(((t,n)=>{const i=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsxs("th",{className:`${f.th} ${A(t)}`.trim(),style:i,onClick:()=>(e=>{y===e?"asc"===w?S("desc"):"desc"===w&&(b(null),S(null)):(b(e),S("asc"))})(n),children:[I(t),y===n&&e.jsx("span",{className:f.sortIndicator,children:"asc"===w?"▲":"▼"})]},n)})),d&&e.jsx("th",{className:`${f.th} ${f.actionsColumn}`,style:{width:"100px"},children:D("Actions")})]}),e.jsxs("tr",{children:[m.map(((t,i)=>{const r=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsx("th",{className:A(t),style:r,children:t.filterable&&e.jsxs("div",{className:f.filterWrapper,children:[e.jsx("input",{type:"text",className:f.filterInput,placeholder:D("Filter")+"...",value:N[i]||"",onChange:e=>((e,t)=>{$((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(N[i]||"").length>0&&e.jsx(n.Button,{appearance:"subtle",className:f.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{$((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),d&&e.jsx("th",{className:f.actionsColumn})]})]}),e.jsxs("tbody",{children:[q>0&&e.jsx("tr",{style:{height:`${P}px`},children:e.jsx("td",{colSpan:m.length+(d?1:0),style:{padding:0,border:"none"}})}),E.map(((t,o)=>{const l=t._index,s="number"==typeof l?l:q+o;return e.jsxs("tr",{className:f.tr,children:[m.map(((i,o)=>{const l=a(t,i.key),c=i.format?i.format(l):T(l),d=i.maxWidth?`${f.td} ${f.tdTruncated} ${A(i)}`.trim():`${f.td} ${A(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&c.length>0&&(W({title:I(i),text:c}),k(!0))};if("file"===i.type&&c)return e.jsx("td",{className:d,onClick:p,children:e.jsx("a",{href:r.CodicentService.getFileUrl(c),target:"_blank",rel:"noopener noreferrer",children:D("Download")})},o);if("checkbox"===i.type){const r=!0===l||"true"===l||"yes"===l||"1"===l;return e.jsx("td",{className:d,children:e.jsx(n.Checkbox,{checked:r,onChange:(e,n)=>{x&&x(t,i.key,!0===n.checked,s)}})},o)}const h=()=>i.maxWidth&&c.length>0?e.jsx(n.Tooltip,{content:{children:c,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e.jsx("span",{children:c})}):c;return e.jsx("td",{className:d,onClick:p,children:i.action?e.jsxs("div",{className:f.cellWithAction,children:[e.jsx("span",{className:f.cellText,children:h()}),(()=>{if(!i.action)return null;const r=i.action,o=i.action.icon,l=e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(o,{}),className:f.actionIcon,onClick:e=>{e.stopPropagation(),r.onClick(t)},size:"small"});return r.tooltip?e.jsx(n.Tooltip,{content:D(r.tooltip),relationship:"label",children:l}):l})()]}):h()},o)})),d&&(p||h)&&e.jsx("td",{className:`${f.td} ${f.actionsColumn}`,children:e.jsxs("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[p&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Edit24Regular,{}),className:f.editButton,onClick:()=>p(t,s),title:D("Edit")}),h&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Delete24Regular,{}),className:f.editButton,onClick:()=>h(t,s),title:D("Delete")})]})})]},R(t,s))})),z<F.length&&e.jsx("tr",{style:{height:H-P-49*E.length+"px"},children:e.jsx("td",{colSpan:m.length+(d?1:0),style:{padding:0,border:"none"}})})]})]})}),e.jsx(n.Dialog,{open:C,onOpenChange:(e,t)=>k(t.open),children:e.jsx(n.DialogSurface,{children:e.jsxs(n.DialogBody,{children:[e.jsx(n.DialogTitle,{children:v.title}),e.jsx(n.DialogContent,{className:f.dialogContent,children:v.text})]})})})]}):e.jsx("div",{className:f.emptyState,children:D("No data to display")})};var c=t.memo(s);exports.ListView=s,exports.default=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=require("@fluentui/react-components"),i=require("@fluentui/react-icons"),r=require("../services/codicent.js"),o=require("../hooks/useLocalization.js");const l=n.makeStyles({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),a=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},s=({data:s,columns:c,canEdit:d,onEdit:p,onDelete:h,onToggleCheckbox:x,onFilteredDataChange:u})=>{const f=l(),{visibleColumns:m,defaultSortIndex:g,defaultSortDirection:j}=t.useMemo((()=>{const e=s&&s.length>0?Array.from(new Set(s.flatMap((e=>Object.keys(e))))):[],t=(c||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[s,c]),[y,b]=t.useState(g>=0?g:null),[w,S]=t.useState(j),[C,k]=t.useState(!1),[v,W]=t.useState({title:"",text:""}),[N,$]=t.useState({}),[M,B]=t.useState(0),{t:D}=o.default(),I=e=>e.title?D(e.title):Array.isArray(e.key)?e.key[0]:e.key,A=e=>{const t=[];return e.hideOnMobile&&t.push(f.hideOnMobile),t.join(" ")},T=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),O=t.useMemo((()=>{const e=[...s];if(null!==y&&w){const t=m[y];e.sort(((e,n)=>{const i=a(e,t.key),r=a(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;return o="string"==typeof i&&"string"==typeof r?i.localeCompare(r):"number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r)),"asc"===w?o:-o}))}return e}),[s,y,w,m]),F=t.useMemo((()=>O.filter((e=>{for(const[t,n]of Object.entries(N)){const i=parseInt(t),r=m[i],o=a(e,r.key),l=T(o).toLowerCase(),s=n.toLowerCase();if(!l.includes(s))return!1}return!0}))),[O,N,m]);t.useEffect((()=>{u&&u(F)}),[F,u]);const L="undefined"!=typeof window?window.innerHeight-250:600,q=Math.max(0,Math.floor(M/49)-5),z=Math.min(F.length,Math.ceil((M+L)/49)+5),E=F.slice(q,z),H=49*F.length,P=49*q,R=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(m.slice(0,3).map((t=>String(a(e,t.key)??""))).join("-"))}`};return s&&0!==s.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:f.container,onScroll:e=>{B(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:e.jsxs("table",{className:f.table,children:[e.jsxs("thead",{children:[e.jsxs("tr",{children:[m.map(((t,n)=>{const i=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsxs("th",{className:`${f.th} ${A(t)}`.trim(),style:i,onClick:()=>(e=>{y===e?"asc"===w?S("desc"):"desc"===w&&(b(null),S(null)):(b(e),S("asc"))})(n),children:[I(t),y===n&&e.jsx("span",{className:f.sortIndicator,children:"asc"===w?"▲":"▼"})]},n)})),d&&e.jsx("th",{className:`${f.th} ${f.actionsColumn}`,style:{width:"100px"},children:D("Actions")})]}),e.jsxs("tr",{children:[m.map(((t,i)=>{const r=t.maxWidth?{width:`${t.maxWidth}px`,maxWidth:`${t.maxWidth}px`}:{};return e.jsx("th",{className:A(t),style:r,children:t.filterable&&e.jsxs("div",{className:f.filterWrapper,children:[e.jsx("input",{type:"text",className:f.filterInput,placeholder:D("Filter")+"...",value:N[i]||"",onChange:e=>((e,t)=>{$((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(N[i]||"").length>0&&e.jsx(n.Button,{appearance:"subtle",className:f.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{$((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),d&&e.jsx("th",{className:f.actionsColumn})]})]}),e.jsxs("tbody",{children:[q>0&&e.jsx("tr",{style:{height:`${P}px`},children:e.jsx("td",{colSpan:m.length+(d?1:0),style:{padding:0,border:"none"}})}),E.map(((t,o)=>{const l=t._index,s="number"==typeof l?l:q+o;return e.jsxs("tr",{className:f.tr,children:[m.map(((i,o)=>{const l=a(t,i.key),c=i.format?i.format(l):T(l),d=i.maxWidth?`${f.td} ${f.tdTruncated} ${A(i)}`.trim():`${f.td} ${A(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&c.length>0&&(W({title:I(i),text:c}),k(!0))};if("file"===i.type&&c)return e.jsx("td",{className:d,onClick:p,children:e.jsx("a",{href:r.CodicentService.getFileUrl(c),target:"_blank",rel:"noopener noreferrer",children:D("Download")})},o);if("checkbox"===i.type){const r=!0===l||"true"===l||"yes"===l||"1"===l;return e.jsx("td",{className:d,children:e.jsx(n.Checkbox,{checked:r,onChange:(e,n)=>{x&&x(t,i.key,!0===n.checked,s)}})},o)}const h=()=>i.maxWidth&&c.length>0?e.jsx(n.Tooltip,{content:{children:c,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e.jsx("span",{children:c})}):c;return e.jsx("td",{className:d,onClick:p,children:i.action?e.jsxs("div",{className:f.cellWithAction,children:[e.jsx("span",{className:f.cellText,children:h()}),(()=>{if(!i.action)return null;const r=i.action,o=i.action.icon,l=e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(o,{}),className:f.actionIcon,onClick:e=>{e.stopPropagation(),r.onClick(t)},size:"small"});return r.tooltip?e.jsx(n.Tooltip,{content:D(r.tooltip),relationship:"label",children:l}):l})()]}):h()},o)})),d&&(p||h)&&e.jsx("td",{className:`${f.td} ${f.actionsColumn}`,children:e.jsxs("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[p&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Edit24Regular,{}),className:f.editButton,onClick:()=>p(t,s),title:D("Edit")}),h&&e.jsx(n.Button,{appearance:"subtle",icon:e.jsx(i.Delete24Regular,{}),className:f.editButton,onClick:()=>h(t,s),title:D("Delete")})]})})]},R(t,s))})),z<F.length&&e.jsx("tr",{style:{height:H-P-49*E.length+"px"},children:e.jsx("td",{colSpan:m.length+(d?1:0),style:{padding:0,border:"none"}})})]})]})}),e.jsx(n.Dialog,{open:C,onOpenChange:(e,t)=>k(t.open),children:e.jsx(n.DialogSurface,{children:e.jsxs(n.DialogBody,{children:[e.jsx(n.DialogTitle,{children:v.title}),e.jsx(n.DialogContent,{className:f.dialogContent,children:v.text})]})})})]}):e.jsx("div",{className:f.emptyState,children:D("No data to display")})};var c=t.memo(s);exports.ListView=s,exports.default=c;
@@ -1 +1 @@
1
- {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAenD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CA0GlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAgBnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAwHlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react"),t=require("@fluentui/react-components"),a=require("../hooks/useLocalization.js");const o=t.makeStyles({content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),n=({open:n,onClose:l,onSave:i,columns:c,initialData:s,title:d})=>{const u=o(),{t:p}=a.default(),[x,h]=r.useState({}),[y,f]=r.useState(!1);r.useEffect((()=>{n&&h(s||{})}),[n,s]);const g=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const r of e.key)if(void 0!==x[r])return r;return g(e)},k=(e,r)=>{const t=j(e);h((e=>({...e,[t]:r})))},m=c.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==g(e)));return e.jsx(t.Dialog,{open:n,onOpenChange:(e,r)=>!y&&!1===r.open&&l(),children:e.jsx(t.DialogSurface,{backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:e.jsxs(t.DialogBody,{children:[e.jsx(t.DialogTitle,{children:d||p(s?"Edit Record":"Add Record")}),e.jsx(t.DialogContent,{className:u.content,children:m.map(((r,a)=>{const o=g(r),n=(e=>{const r=j(e);return x[r]})(r),l=r.title||o;return"checkbox"===r.type?e.jsx(t.Field,{label:l,className:u.field,children:e.jsx(t.Checkbox,{checked:!0===n||"true"===n||"yes"===n||"1"===n,onChange:(e,t)=>k(r,t.checked)})},a):e.jsx(t.Field,{label:l,className:u.field,children:e.jsx(t.Input,{value:String(n??""),onChange:(e,t)=>k(r,t.value),placeholder:p("Enter")+" "+l.toLowerCase()})},a)}))}),e.jsxs(t.DialogActions,{children:[e.jsx(t.Button,{appearance:"secondary",onClick:l,disabled:y,children:p("Cancel")}),e.jsx(t.Button,{appearance:"primary",onClick:async()=>{f(!0);try{await i(x),l()}catch(e){console.error("Failed to save record:",e)}finally{f(!1)}},disabled:y,children:p(y?"Saving...":"Save")})]})]})})})};exports.RecordModal=n,exports.default=n;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),r=require("react"),a=require("@fluentui/react-components"),t=require("../hooks/useLocalization.js");const l=a.makeStyles({content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),o=({open:o,onClose:n,onSave:i,columns:c,initialData:s,title:d})=>{const u=l(),{t:x}=t.default(),[h,p]=r.useState({}),[y,f]=r.useState(!1);r.useEffect((()=>{o&&p(s||{})}),[o,s]);const g=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const r of e.key)if(void 0!==h[r])return r;return g(e)},k=(e,r)=>{const a=j(e);p((e=>({...e,[a]:r})))},m=c.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==g(e)));return e.jsx(a.Dialog,{open:o,onOpenChange:(e,r)=>!y&&!1===r.open&&n(),children:e.jsx(a.DialogSurface,{backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:e.jsxs(a.DialogBody,{children:[e.jsx(a.DialogTitle,{children:d||x(s?"Edit Record":"Add Record")}),e.jsx(a.DialogContent,{className:u.content,children:m.map(((r,t)=>{const l=g(r),o=(e=>{const r=j(e);return h[r]})(r),n=r.title||l;return"checkbox"===r.type?e.jsx(a.Field,{label:n,className:u.field,children:e.jsx(a.Checkbox,{checked:!0===o||"true"===o||"yes"===o||"1"===o,onChange:(e,a)=>k(r,a.checked)})},t):"textarea"===r.type?e.jsx(a.Field,{label:n,className:u.field,children:e.jsx(a.Textarea,{value:String(o??""),rows:r.rows??3,onChange:(e,a)=>k(r,a.value),placeholder:x("Enter")+" "+n.toLowerCase(),resize:"vertical"})},t):e.jsx(a.Field,{label:n,className:u.field,children:e.jsx(a.Input,{value:String(o??""),onChange:(e,a)=>k(r,a.value),placeholder:x("Enter")+" "+n.toLowerCase()})},t)}))}),e.jsxs(a.DialogActions,{children:[e.jsx(a.Button,{appearance:"secondary",onClick:n,disabled:y,children:x("Cancel")}),e.jsx(a.Button,{appearance:"primary",onClick:async()=>{f(!0);try{await i(h),n()}catch(e){console.error("Failed to save record:",e)}finally{f(!1)}},disabled:y,children:x(y?"Saving...":"Save")})]})]})})})};exports.RecordModal=o,exports.default=o;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../utils/wav_renderer.js");require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js");var n=require("../lib/wavtools/lib/wav_stream_player.js"),r=require("../lib/wavtools/lib/wav_recorder.js"),a=require("../config/index.js");exports.default=(o,s,i,c,l)=>{const u=!!a.getConfigValue("APP_CONFIG"),d=!!a.getConfigValue("APP_BUTTONS");u||console.warn("APP_CONFIG is not set. Voice AI will not be available."),d||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const p=a.getConfigValue("APP_CONFIG"),f=a.getConfigValue("APP_BUTTONS");a.getConfigValue("API_BASE_URL").replace(/\/$/,""),a.getConfigValue("USE_REALTIME_SESSION_ENDPOINT"),a.getConfigValue("REALTIME_SESSION_ENDPOINT");const g=c||a.getConfigValue("REALTIME_VOICE_MODEL")||"alloy",m=l||a.getConfigValue("REALTIME_VOICE_PROVIDER")||"openai",y=["alloy","shimmer","echo"],_=y.includes(g)?g:"alloy";g!==_&&console.warn(`[codicent-app-sdk] Voice "${g}" is not supported in the current SDK version. Supported voices: ${y.join(", ")}. Falling back to "${_}".`),console.log(`[codicent-app-sdk] Using voice provider: ${m}`);const S=e.useRef(new r.WavRecorder({sampleRate:24e3})),v=e.useRef(new n.WavStreamPlayer({sampleRate:24e3})),w=e.useRef(null),h=e.useRef(null),O=e.useRef(null),R=e.useRef(null),C=e.useRef(!1),I=e.useRef(null),T=e.useRef(null),E=e.useRef(null),N=e.useRef((new Date).toISOString()),[b,A]=e.useState([]),[P,V]=e.useState([]),[k,D]=e.useState(!1),[M,$]=e.useState(!1),[x,F]=e.useState(!1),[J,L]=e.useState(!1),U=e.useRef(0),j=e.useRef(0),[q,B]=e.useState(""),[W,G]=e.useState("en-US"),H=e.useRef(new Map),z=e.useRef(null),[K,Q]=e.useState((()=>u&&d&&f&&p&&p.apps&&p.apps[f]?p.apps[f].voiceInstructions||p.REALTIME_VOICE_INSTRUCTIONS||"":p&&p.REALTIME_VOICE_INSTRUCTIONS||"")),X=e.useCallback((e=>{const t=N.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,a=Math.floor(r/10)%100,o=Math.floor(r/1e3)%60,s=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${s(Math.floor(r/6e4)%60)}:${s(o)}.${s(a)}`}),[]),Y=e.useCallback((async()=>{try{N.current=(new Date).toISOString(),D(!0),V([]),A([]),H.current.clear();const e=await o.getRealtimeSessionToken(_,m);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;w.current=t,O.current||(O.current=new Audio,O.current.autoplay=!0),t.ontrack=e=>{O.current&&e.streams[0]&&(O.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});R.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const s=t.createDataChannel("oai-events");h.current=s,s.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);if("session.created"===t.type);else if("conversation.item.created"===t.type)A((e=>[...e,t.item]));else if("conversation.item.input_audio_transcription.completed"===t.type)A((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n}));else if("response.audio_transcript.delta"===t.type);else if("response.audio_transcript.done"===t.type);else if("response.output_item.added"===t.type){const e=t.item;"function_call"===e?.type&&(console.log("[Voice AI] Function call initiated:",e.name),H.current.set(e.id,{name:e.name||"",arguments:"",call_id:e.call_id||e.id}))}else if("response.function_call_arguments.delta"===t.type){const e=t.item_id,n=t.delta,r=H.current.get(e);r&&n&&(r.arguments+=n,H.current.set(e,r))}else if("response.function_call_arguments.done"===t.type){const e=t.item_id,n=H.current.get(e);if(n){console.log(`[Voice AI] Executing tool: ${n.name}`);const t=i.find((e=>e.definition.name===n.name));if(t){let e={};try{e=n.arguments?JSON.parse(n.arguments):{}}catch(t){console.error("[Voice AI] Failed to parse tool arguments:",t),e={}}Promise.resolve(t.handler(e)).then((e=>{console.log(`[Voice AI] Tool ${n.name} completed:`,e),s&&"open"===s.readyState&&(s.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify(e)}})),s.send(JSON.stringify({type:"response.create"})))})).catch((e=>{console.error(`[Voice AI] Tool ${n.name} failed:`,e),s&&"open"===s.readyState&&(s.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify({error:e.message||"Tool execution failed"})}})),s.send(JSON.stringify({type:"response.create"})))}))}else console.error(`[Voice AI] Tool not found: ${n.name}`);H.current.delete(e)}}else"error"===t.type&&console.error("Server error:",t.error)}catch(t){console.warn("Invalid message:",e.data)}})),s.onopen=()=>{console.log("Data channel opened, configuring session");const e=z.current||K;z.current=null,s.send(JSON.stringify({type:"session.update",session:{instructions:e.replace("{{name}}",q).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:_,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:i.map((e=>({type:"function",...e.definition})))}})),$(!0)},s.onclose=()=>{console.log("Data channel closed"),$(!1)};const c=await t.createOffer();await t.setLocalDescription(c);let l="gpt-4o-realtime-preview";try{if(a.getConfigValue("REALTIME_CONFIG_ENDPOINT")){const e=await o.getRealtimeConfig();e&&e.model&&(l=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const u="https://api.openai.com/v1/realtime",d=await fetch(`${u}?model=${l}`,{method:"POST",body:c.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!d.ok)throw new Error(`Failed to get SDP answer: ${d.statusText}`);const p={type:"answer",sdp:await d.text()};await t.setRemoteDescription(p),F(!1);const f=S.current,g=v.current;await f.begin(),await g.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),D(!1),e}}),[o,_,K,q,W,i]),Z=e.useCallback((async()=>{D(!1),$(!1),V([]),A([]),H.current.clear(),z.current=null,h.current&&(h.current.close(),h.current=null),w.current&&(w.current.close(),w.current=null),R.current&&(R.current.getTracks().forEach((e=>e.stop())),R.current=null),O.current&&(O.current.pause(),O.current.srcObject=null);const e=S.current;await e.end();const t=v.current;await t.interrupt()}),[]),ee=e.useCallback((async e=>{const t=h.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),te=e.useCallback((async()=>{L(!0);const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),ne=e.useCallback((async()=>{L(!1);const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),re=e.useCallback((async e=>{const t=h.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),F("none"===e)}),[]);e.useEffect((()=>{if(q&&M){const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:K.replace("{{name}}",q).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString())}}))}}),[K,q,W,M]),e.useEffect((()=>{let e=!0;const n=S.current,r=I.current;let a=null;const o=v.current,s=T.current;let i=null;const c=()=>{if(e){if(r&&(r.width&&r.height||(r.width=r.offsetWidth,r.height=r.offsetHeight),a=a||r.getContext("2d"),a)){a.clearRect(0,0,r.width,r.height);const e=n.recording?n.getFrequencies("voice"):{values:new Float32Array([0])},o=1-Math.max(...e.values);U.current=o,t.WavRenderer.drawCircularBars(r,a,e.values,"#0099ff",20,0,8)}if(s&&(s.width&&s.height||(s.width=s.offsetWidth,s.height=s.offsetHeight),i=i||s.getContext("2d"),i)){i.clearRect(0,0,s.width,s.height);const e=o.analyser?o.getFrequencies("voice"):{values:new Float32Array([0])},n=1-Math.max(...e.values);j.current=n,t.WavRenderer.drawCircularBars(s,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),e.useEffect((()=>{!C.current&&i&&K&&(C.current=!0)}),[i,K]);const ae=e.useCallback((e=>{Q(e);const t=h.current;if(t&&"open"===t.readyState){const n=e.replace("{{name}}",q).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString());t.send(JSON.stringify({type:"session.update",session:{instructions:n}}))}else z.current=e}),[q,W]);return e.useMemo((()=>{if(u&&d)return{items:b,realtimeEvents:P,isConnected:k,isSessionReady:M,canPushToTalk:x,isRecording:J,clientCanvasRef:I,serverCanvasRef:T,eventsScrollRef:E,formatTime:X,connectConversation:Y,disconnectConversation:Z,deleteConversationItem:ee,startRecording:te,stopRecording:ne,changeTurnEndType:re,getRecorderLevel:()=>U.current,getStreamLevel:()=>j.current,setUsername:B,updateInstructions:ae,setLanguage:G}}),[u,d,b,P,k,M,x,J,I,T,E])};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../utils/wav_renderer.js");require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js");var n=require("../lib/wavtools/lib/wav_stream_player.js"),r=require("../lib/wavtools/lib/wav_recorder.js"),a=require("../config/index.js");exports.default=(o,s,i,c,l)=>{const u=!!a.getConfigValue("APP_CONFIG"),d=!!a.getConfigValue("APP_BUTTONS");u||console.warn("APP_CONFIG is not set. Voice AI will not be available."),d||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const p=a.getConfigValue("APP_CONFIG"),f=a.getConfigValue("APP_BUTTONS");a.getConfigValue("API_BASE_URL").replace(/\/$/,""),a.getConfigValue("USE_REALTIME_SESSION_ENDPOINT"),a.getConfigValue("REALTIME_SESSION_ENDPOINT");const g=c||a.getConfigValue("REALTIME_VOICE_MODEL")||"alloy",m=l||a.getConfigValue("REALTIME_VOICE_PROVIDER")||"openai",y=["alloy","shimmer","echo"],_=y.includes(g)?g:"alloy";g!==_&&console.warn(`[codicent-app-sdk] Voice "${g}" is not supported in the current SDK version. Supported voices: ${y.join(", ")}. Falling back to "${_}".`);const S=e.useRef(new r.WavRecorder({sampleRate:24e3})),w=e.useRef(new n.WavStreamPlayer({sampleRate:24e3})),v=e.useRef(null),h=e.useRef(null),O=e.useRef(null),R=e.useRef(null),C=e.useRef(!1),I=e.useRef(null),T=e.useRef(null),E=e.useRef(null),N=e.useRef((new Date).toISOString()),[b,A]=e.useState([]),[P,V]=e.useState([]),[k,D]=e.useState(!1),[M,x]=e.useState(!1),[F,J]=e.useState(!1),[$,L]=e.useState(!1),j=e.useRef(0),q=e.useRef(0),[U,B]=e.useState(""),[W,G]=e.useState("en-US"),H=e.useRef(new Map),z=e.useRef(null),[K,Q]=e.useState((()=>u&&d&&f&&p&&p.apps&&p.apps[f]?p.apps[f].voiceInstructions||p.REALTIME_VOICE_INSTRUCTIONS||"":p&&p.REALTIME_VOICE_INSTRUCTIONS||"")),X=e.useCallback((e=>{const t=N.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,a=Math.floor(r/10)%100,o=Math.floor(r/1e3)%60,s=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${s(Math.floor(r/6e4)%60)}:${s(o)}.${s(a)}`}),[]),Y=e.useCallback((async()=>{try{N.current=(new Date).toISOString(),D(!0),V([]),A([]),H.current.clear();const e=await o.getRealtimeSessionToken(_,m);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;v.current=t,O.current||(O.current=new Audio,O.current.autoplay=!0),t.ontrack=e=>{O.current&&e.streams[0]&&(O.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});R.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const s=t.createDataChannel("oai-events");h.current=s,s.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);if("session.created"===t.type);else if("conversation.item.created"===t.type)A((e=>[...e,t.item]));else if("conversation.item.input_audio_transcription.completed"===t.type)A((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n}));else if("response.audio_transcript.delta"===t.type);else if("response.audio_transcript.done"===t.type);else if("response.output_item.added"===t.type){const e=t.item;"function_call"===e?.type&&(console.log("[Voice AI] Function call initiated:",e.name),H.current.set(e.id,{name:e.name||"",arguments:"",call_id:e.call_id||e.id}))}else if("response.function_call_arguments.delta"===t.type){const e=t.item_id,n=t.delta,r=H.current.get(e);r&&n&&(r.arguments+=n,H.current.set(e,r))}else if("response.function_call_arguments.done"===t.type){const e=t.item_id,n=H.current.get(e);if(n){console.log(`[Voice AI] Executing tool: ${n.name}`);const t=i.find((e=>e.definition.name===n.name));if(t){let e={};try{e=n.arguments?JSON.parse(n.arguments):{}}catch(t){console.error("[Voice AI] Failed to parse tool arguments:",t),e={}}Promise.resolve(t.handler(e)).then((e=>{console.log(`[Voice AI] Tool ${n.name} completed:`,e),s&&"open"===s.readyState&&(s.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify(e)}})),s.send(JSON.stringify({type:"response.create"})))})).catch((e=>{console.error(`[Voice AI] Tool ${n.name} failed:`,e),s&&"open"===s.readyState&&(s.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify({error:e.message||"Tool execution failed"})}})),s.send(JSON.stringify({type:"response.create"})))}))}else console.error(`[Voice AI] Tool not found: ${n.name}`);H.current.delete(e)}}else"error"===t.type&&console.error("Server error:",t.error)}catch(t){console.warn("Invalid message:",e.data)}})),s.onopen=()=>{console.log("Data channel opened, configuring session");const e=z.current||K;z.current=null,s.send(JSON.stringify({type:"session.update",session:{instructions:e.replace("{{name}}",U).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:_,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:i.map((e=>({type:"function",...e.definition})))}})),x(!0)},s.onclose=()=>{console.log("Data channel closed"),x(!1)};const c=await t.createOffer();await t.setLocalDescription(c);let l="gpt-4o-realtime-preview";try{if(a.getConfigValue("REALTIME_CONFIG_ENDPOINT")){const e=await o.getRealtimeConfig();e&&e.model&&(l=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const u="https://api.openai.com/v1/realtime",d=await fetch(`${u}?model=${l}`,{method:"POST",body:c.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!d.ok)throw new Error(`Failed to get SDP answer: ${d.statusText}`);const p={type:"answer",sdp:await d.text()};await t.setRemoteDescription(p),J(!1);const f=S.current,g=w.current;await f.begin(),await g.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),D(!1),e}}),[o,_,K,U,W,i]),Z=e.useCallback((async()=>{D(!1),x(!1),V([]),A([]),H.current.clear(),z.current=null,h.current&&(h.current.close(),h.current=null),v.current&&(v.current.close(),v.current=null),R.current&&(R.current.getTracks().forEach((e=>e.stop())),R.current=null),O.current&&(O.current.pause(),O.current.srcObject=null);const e=S.current;await e.end();const t=w.current;await t.interrupt()}),[]),ee=e.useCallback((async e=>{const t=h.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),te=e.useCallback((async()=>{L(!0);const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),ne=e.useCallback((async()=>{L(!1);const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),re=e.useCallback((async e=>{const t=h.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),J("none"===e)}),[]);e.useEffect((()=>{if(U&&M){const e=h.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:K.replace("{{name}}",U).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString())}}))}}),[K,U,W,M]),e.useEffect((()=>{let e=!0;const n=S.current,r=I.current;let a=null;const o=w.current,s=T.current;let i=null;const c=()=>{if(e){if(r&&(r.width&&r.height||(r.width=r.offsetWidth,r.height=r.offsetHeight),a=a||r.getContext("2d"),a)){a.clearRect(0,0,r.width,r.height);const e=n.recording?n.getFrequencies("voice"):{values:new Float32Array([0])},o=1-Math.max(...e.values);j.current=o,t.WavRenderer.drawCircularBars(r,a,e.values,"#0099ff",20,0,8)}if(s&&(s.width&&s.height||(s.width=s.offsetWidth,s.height=s.offsetHeight),i=i||s.getContext("2d"),i)){i.clearRect(0,0,s.width,s.height);const e=o.analyser?o.getFrequencies("voice"):{values:new Float32Array([0])},n=1-Math.max(...e.values);q.current=n,t.WavRenderer.drawCircularBars(s,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),e.useEffect((()=>{!C.current&&i&&K&&(C.current=!0)}),[i,K]);const ae=e.useCallback((e=>{Q(e);const t=h.current;if(t&&"open"===t.readyState){const n=e.replace("{{name}}",U).replace("{{language}}",W).replace("{{time}}",(new Date).toISOString());t.send(JSON.stringify({type:"session.update",session:{instructions:n}}))}else z.current=e}),[U,W]);return e.useMemo((()=>{if(u&&d)return{items:b,realtimeEvents:P,isConnected:k,isSessionReady:M,canPushToTalk:F,isRecording:$,clientCanvasRef:I,serverCanvasRef:T,eventsScrollRef:E,formatTime:X,connectConversation:Y,disconnectConversation:Z,deleteConversationItem:ee,startRecording:te,stopRecording:ne,changeTurnEndType:re,getRecorderLevel:()=>j.current,getStreamLevel:()=>q.current,setUsername:B,updateInstructions:ae,setLanguage:G}}),[u,d,b,P,k,M,F,$,I,T,E])};
@@ -54,7 +54,7 @@ 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) => Promise<DataMessage[]>;
57
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
58
58
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
59
59
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
60
60
  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,CA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AQG;IACH,MAAM,CAAC,gBAAgB,YACZ,MAAM,YACN,MAAM,cACH,MAAM,mBACF,MAAM,oBACL,MAAM,KACtB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+E5B;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,mBAO7B;IAGF,OAAO,CAAC,kBAAkB;IAM1B,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,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)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.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)=>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;
@@ -14,7 +14,9 @@ export interface ColumnDefinition {
14
14
  hidden?: boolean;
15
15
  hideOnMobile?: boolean;
16
16
  maxWidth?: number;
17
- type?: "file" | "checkbox" | undefined;
17
+ type?: "file" | "checkbox" | "textarea" | undefined;
18
+ /** Number of rows for textarea type (default: 3) */
19
+ rows?: number;
18
20
  editable?: boolean;
19
21
  filterable?: boolean;
20
22
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
@@ -1 +1 @@
1
- {"version":3,"file":"ListView.d.ts","sourceRoot":"","sources":["../../../src/components/ListView.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAgB5D,uEAAuE;AACvE,MAAM,WAAW,YAAY;IAC3B,kHAAkH;IAClH,IAAI,EAAE,KAAK,CAAC,aAAa,CAAC;IAC1B,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iFAAiF;IACjF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;CACrD;AA2JD,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,CAAC;IACvC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,UAAU,CAAC,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AC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACrH,oBAAoB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC;CAC1E;AAID,eAAO,MAAM,QAAQ,EAAE,KAAK,CAAC,EAAE,CAAC,aAAa,CAic5C,CAAC;;AAGF,wBAAoC"}
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import i,{useMemo as r,useState as o,useEffect as l}from"react";import{makeStyles as a,Button as c,Checkbox as d,Dialog as s,DialogSurface as p,DialogBody as h,DialogTitle as m,DialogContent as u,Tooltip as f}from"@fluentui/react-components";import{Edit24Regular as x,Delete24Regular as g}from"@fluentui/react-icons";import{CodicentService as y}from"../services/codicent.js";import b from"../hooks/useLocalization.js";const w=a({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),k=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},C=({data:i,columns:a,canEdit:C,onEdit:v,onDelete:S,onToggleCheckbox:W,onFilteredDataChange:N})=>{const $=w(),{visibleColumns:j,defaultSortIndex:I,defaultSortDirection:A}=r((()=>{const e=i&&i.length>0?Array.from(new Set(i.flatMap((e=>Object.keys(e))))):[],t=(a||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[i,a]),[M,O]=o(I>=0?I:null),[T,B]=o(A),[z,D]=o(!1),[F,L]=o({title:"",text:""}),[H,E]=o({}),[P,Y]=o(0),{t:R}=b(),_=e=>e.title?R(e.title):Array.isArray(e.key)?e.key[0]:e.key,J=e=>{const t=[];return e.hideOnMobile&&t.push($.hideOnMobile),t.join(" ")},U=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),X=[...i];if(null!==M&&T){const e=j[M];X.sort(((t,n)=>{const i=k(t,e.key),r=k(n,e.key);if(null==i)return 1;if(null==r)return-1;let o=0;return o="string"==typeof i&&"string"==typeof r?i.localeCompare(r):"number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r)),"asc"===T?o:-o}))}const q=r((()=>X.filter((e=>{for(const[t,n]of Object.entries(H)){const i=parseInt(t),r=j[i],o=k(e,r.key),l=U(o).toLowerCase(),a=n.toLowerCase();if(!l.includes(a))return!1}return!0}))),[X,H,j]);l((()=>{N&&N(q)}),[q,N]);const G="undefined"!=typeof window?window.innerHeight-250:600,K=Math.max(0,Math.floor(P/49)-5),Q=Math.min(q.length,Math.ceil((P+G)/49)+5),V=q.slice(K,Q),Z=49*q.length,ee=49*K,te=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(j.slice(0,3).map((t=>String(k(e,t.key)??""))).join("-"))}`};return i&&0!==i.length?t(n,{children:[e("div",{className:$.container,onScroll:e=>{Y(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:t("table",{className:$.table,children:[t("thead",{children:[t("tr",{children:[j.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return t("th",{className:`${$.th} ${J(n)}`.trim(),style:r,onClick:()=>(e=>{M===e?"asc"===T?B("desc"):"desc"===T&&(O(null),B(null)):(O(e),B("asc"))})(i),children:[_(n),M===i&&e("span",{className:$.sortIndicator,children:"asc"===T?"▲":"▼"})]},i)})),C&&e("th",{className:`${$.th} ${$.actionsColumn}`,style:{width:"100px"},children:R("Actions")})]}),t("tr",{children:[j.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return e("th",{className:J(n),style:r,children:n.filterable&&t("div",{className:$.filterWrapper,children:[e("input",{type:"text",className:$.filterInput,placeholder:R("Filter")+"...",value:H[i]||"",onChange:e=>((e,t)=>{E((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(H[i]||"").length>0&&e(c,{appearance:"subtle",className:$.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{E((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),C&&e("th",{className:$.actionsColumn})]})]}),t("tbody",{children:[K>0&&e("tr",{style:{height:`${ee}px`},children:e("td",{colSpan:j.length+(C?1:0),style:{padding:0,border:"none"}})}),V.map(((n,i)=>{const r=n._index,o="number"==typeof r?r:K+i;return t("tr",{className:$.tr,children:[j.map(((i,r)=>{const l=k(n,i.key),a=i.format?i.format(l):U(l),s=i.maxWidth?`${$.td} ${$.tdTruncated} ${J(i)}`.trim():`${$.td} ${J(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&a.length>0&&(L({title:_(i),text:a}),D(!0))};if("file"===i.type&&a)return e("td",{className:s,onClick:p,children:e("a",{href:y.getFileUrl(a),target:"_blank",rel:"noopener noreferrer",children:R("Download")})},r);if("checkbox"===i.type){return e("td",{className:s,children:e(d,{checked:!0===l||"true"===l||"yes"===l||"1"===l,onChange:(e,t)=>{W&&W(n,i.key,!0===t.checked,o)}})},r)}const h=()=>i.maxWidth&&a.length>0?e(f,{content:{children:a,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e("span",{children:a})}):a;return e("td",{className:s,onClick:p,children:i.action?t("div",{className:$.cellWithAction,children:[e("span",{className:$.cellText,children:h()}),(()=>{if(!i.action)return null;const t=i.action,r=i.action.icon,o=e(c,{appearance:"subtle",icon:e(r,{}),className:$.actionIcon,onClick:e=>{e.stopPropagation(),t.onClick(n)},size:"small"});return t.tooltip?e(f,{content:R(t.tooltip),relationship:"label",children:o}):o})()]}):h()},r)})),C&&(v||S)&&e("td",{className:`${$.td} ${$.actionsColumn}`,children:t("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[v&&e(c,{appearance:"subtle",icon:e(x,{}),className:$.editButton,onClick:()=>v(n,o),title:R("Edit")}),S&&e(c,{appearance:"subtle",icon:e(g,{}),className:$.editButton,onClick:()=>S(n,o),title:R("Delete")})]})})]},te(n,o))})),Q<q.length&&e("tr",{style:{height:Z-ee-49*V.length+"px"},children:e("td",{colSpan:j.length+(C?1:0),style:{padding:0,border:"none"}})})]})]})}),e(s,{open:z,onOpenChange:(e,t)=>D(t.open),children:e(p,{children:t(h,{children:[e(m,{children:F.title}),e(u,{className:$.dialogContent,children:F.text})]})})})]}):e("div",{className:$.emptyState,children:R("No data to display")})};var v=i.memo(C);export{C as ListView,v as default};
1
+ import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import i,{useMemo as r,useState as o,useEffect as l}from"react";import{makeStyles as a,Button as c,Checkbox as d,Dialog as s,DialogSurface as p,DialogBody as h,DialogTitle as m,DialogContent as u,Tooltip as f}from"@fluentui/react-components";import{Edit24Regular as x,Delete24Regular as g}from"@fluentui/react-icons";import{CodicentService as y}from"../services/codicent.js";import b from"../hooks/useLocalization.js";const w=a({container:{width:"100%",overflowX:"auto",userSelect:"text"},table:{width:"100%",borderCollapse:"collapse",backgroundColor:"#ffffff",fontSize:"14px",tableLayout:"fixed",userSelect:"text"},th:{textAlign:"left",padding:"12px 8px",borderBottom:"2px solid #e0e0e0",fontWeight:"600",backgroundColor:"#f5f5f5",position:"sticky",top:0,zIndex:1,cursor:"pointer",userSelect:"none","&:hover":{backgroundColor:"#e8e8e8"}},td:{padding:"12px 8px",borderBottom:"1px solid #e0e0e0",verticalAlign:"top",wordWrap:"break-word",overflow:"hidden",userSelect:"text"},tdTruncated:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap","@media (hover: none)":{cursor:"pointer"}},tr:{"&:hover":{backgroundColor:"#f9f9f9"}},emptyState:{padding:"20px",textAlign:"center",color:"#666"},sortIndicator:{marginLeft:"4px",fontSize:"10px"},hideOnMobile:{"@media (max-width: 768px)":{display:"none"}},dialogContent:{wordWrap:"break-word",whiteSpace:"pre-wrap",maxHeight:"60vh",overflowY:"auto"},thumbnail:{maxWidth:"50px",maxHeight:"50px",objectFit:"cover"},tooltip:{maxWidth:"600px",whiteSpace:"normal",wordWrap:"break-word"},editButton:{minWidth:"auto",padding:"4px 8px"},actionsColumn:{width:"100px",textAlign:"center"},filterInput:{width:"100%",padding:"4px 8px",fontSize:"14px",border:"1px solid #e0e0e0",borderRadius:"4px",paddingRight:"28px"},filterWrapper:{position:"relative"},clearFilterButton:{position:"absolute",right:"6px",top:"50%",transform:"translateY(-50%)",minWidth:"auto",height:"20px",padding:"0 6px",lineHeight:"18px"},filterToolbar:{display:"flex",justifyContent:"flex-end",padding:"8px",gap:"8px"},cellWithAction:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:"4px"},actionIcon:{minWidth:"auto",padding:"2px",marginLeft:"4px",flexShrink:0,cursor:"pointer",opacity:.7,"&:hover":{opacity:1}},cellText:{flex:1,overflow:"hidden",textOverflow:"ellipsis"}}),k=(e,t)=>{if("string"==typeof t)return e[t];for(const n of t)if(void 0!==e[n])return e[n]},C=({data:i,columns:a,canEdit:C,onEdit:v,onDelete:S,onToggleCheckbox:W,onFilteredDataChange:N})=>{const $=w(),{visibleColumns:j,defaultSortIndex:I,defaultSortDirection:A}=r((()=>{const e=i&&i.length>0?Array.from(new Set(i.flatMap((e=>Object.keys(e))))):[],t=(a||e.map((e=>({key:e})))).filter((e=>!e.hidden)),n=t.findIndex((e=>e.defaultSort));return{visibleColumns:t,defaultSortIndex:n,defaultSortDirection:n>=0&&t[n].defaultSort||null}}),[i,a]),[M,O]=o(I>=0?I:null),[T,B]=o(A),[z,D]=o(!1),[F,L]=o({title:"",text:""}),[H,E]=o({}),[P,Y]=o(0),{t:R}=b(),_=e=>e.title?R(e.title):Array.isArray(e.key)?e.key[0]:e.key,J=e=>{const t=[];return e.hideOnMobile&&t.push($.hideOnMobile),t.join(" ")},U=e=>null==e||"string"==typeof e&&e.startsWith("[")&&e.endsWith("]")?"":"object"==typeof e?JSON.stringify(e):String(e),X=r((()=>{const e=[...i];if(null!==M&&T){const t=j[M];e.sort(((e,n)=>{const i=k(e,t.key),r=k(n,t.key);if(null==i)return 1;if(null==r)return-1;let o=0;return o="string"==typeof i&&"string"==typeof r?i.localeCompare(r):"number"==typeof i&&"number"==typeof r?i-r:String(i).localeCompare(String(r)),"asc"===T?o:-o}))}return e}),[i,M,T,j]),q=r((()=>X.filter((e=>{for(const[t,n]of Object.entries(H)){const i=parseInt(t),r=j[i],o=k(e,r.key),l=U(o).toLowerCase(),a=n.toLowerCase();if(!l.includes(a))return!1}return!0}))),[X,H,j]);l((()=>{N&&N(q)}),[q,N]);const G="undefined"!=typeof window?window.innerHeight-250:600,K=Math.max(0,Math.floor(P/49)-5),Q=Math.min(q.length,Math.ceil((P+G)/49)+5),V=q.slice(K,Q),Z=49*q.length,ee=49*K,te=(e,t)=>{if(void 0!==e.id)return String(e.id);return`row-${t}-${(e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return Math.abs(t)})(j.slice(0,3).map((t=>String(k(e,t.key)??""))).join("-"))}`};return i&&0!==i.length?t(n,{children:[e("div",{className:$.container,onScroll:e=>{Y(e.currentTarget.scrollTop)},style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:t("table",{className:$.table,children:[t("thead",{children:[t("tr",{children:[j.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return t("th",{className:`${$.th} ${J(n)}`.trim(),style:r,onClick:()=>(e=>{M===e?"asc"===T?B("desc"):"desc"===T&&(O(null),B(null)):(O(e),B("asc"))})(i),children:[_(n),M===i&&e("span",{className:$.sortIndicator,children:"asc"===T?"▲":"▼"})]},i)})),C&&e("th",{className:`${$.th} ${$.actionsColumn}`,style:{width:"100px"},children:R("Actions")})]}),t("tr",{children:[j.map(((n,i)=>{const r=n.maxWidth?{width:`${n.maxWidth}px`,maxWidth:`${n.maxWidth}px`}:{};return e("th",{className:J(n),style:r,children:n.filterable&&t("div",{className:$.filterWrapper,children:[e("input",{type:"text",className:$.filterInput,placeholder:R("Filter")+"...",value:H[i]||"",onChange:e=>((e,t)=>{E((n=>{const i={...n};return""===t.trim()?delete i[e]:i[e]=t,i}))})(i,e.target.value),onClick:e=>e.stopPropagation()}),(H[i]||"").length>0&&e(c,{appearance:"subtle",className:$.clearFilterButton,onClick:e=>{e.stopPropagation(),(e=>{E((t=>{const n={...t};return delete n[e],n}))})(i)},children:"×"})]})},i)})),C&&e("th",{className:$.actionsColumn})]})]}),t("tbody",{children:[K>0&&e("tr",{style:{height:`${ee}px`},children:e("td",{colSpan:j.length+(C?1:0),style:{padding:0,border:"none"}})}),V.map(((n,i)=>{const r=n._index,o="number"==typeof r?r:K+i;return t("tr",{className:$.tr,children:[j.map(((i,r)=>{const l=k(n,i.key),a=i.format?i.format(l):U(l),s=i.maxWidth?`${$.td} ${$.tdTruncated} ${J(i)}`.trim():`${$.td} ${J(i)}`.trim(),p=()=>{window.matchMedia("(hover: hover)").matches||i.maxWidth&&a.length>0&&(L({title:_(i),text:a}),D(!0))};if("file"===i.type&&a)return e("td",{className:s,onClick:p,children:e("a",{href:y.getFileUrl(a),target:"_blank",rel:"noopener noreferrer",children:R("Download")})},r);if("checkbox"===i.type){return e("td",{className:s,children:e(d,{checked:!0===l||"true"===l||"yes"===l||"1"===l,onChange:(e,t)=>{W&&W(n,i.key,!0===t.checked,o)}})},r)}const h=()=>i.maxWidth&&a.length>0?e(f,{content:{children:a,style:{maxWidth:"600px",whiteSpace:"normal"}},relationship:"description",children:e("span",{children:a})}):a;return e("td",{className:s,onClick:p,children:i.action?t("div",{className:$.cellWithAction,children:[e("span",{className:$.cellText,children:h()}),(()=>{if(!i.action)return null;const t=i.action,r=i.action.icon,o=e(c,{appearance:"subtle",icon:e(r,{}),className:$.actionIcon,onClick:e=>{e.stopPropagation(),t.onClick(n)},size:"small"});return t.tooltip?e(f,{content:R(t.tooltip),relationship:"label",children:o}):o})()]}):h()},r)})),C&&(v||S)&&e("td",{className:`${$.td} ${$.actionsColumn}`,children:t("div",{style:{display:"flex",gap:"4px",justifyContent:"center"},children:[v&&e(c,{appearance:"subtle",icon:e(x,{}),className:$.editButton,onClick:()=>v(n,o),title:R("Edit")}),S&&e(c,{appearance:"subtle",icon:e(g,{}),className:$.editButton,onClick:()=>S(n,o),title:R("Delete")})]})})]},te(n,o))})),Q<q.length&&e("tr",{style:{height:Z-ee-49*V.length+"px"},children:e("td",{colSpan:j.length+(C?1:0),style:{padding:0,border:"none"}})})]})]})}),e(s,{open:z,onOpenChange:(e,t)=>D(t.open),children:e(p,{children:t(h,{children:[e(m,{children:F.title}),e(u,{className:$.dialogContent,children:F.text})]})})})]}):e("div",{className:$.emptyState,children:R("No data to display")})};var v=i.memo(C);export{C as ListView,v as default};
@@ -1 +1 @@
1
- {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAenD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CA0GlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"RecordModal.d.ts","sourceRoot":"","sources":["../../../src/components/RecordModal.tsx"],"names":[],"mappings":"AAWA,OAAO,KAA8B,MAAM,OAAO,CAAC;AAgBnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiB9C,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,OAAO,CAAC;IACd,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,MAAM,EAAE,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD,OAAO,EAAE,gBAAgB,EAAE,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,eAAO,MAAM,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC,gBAAgB,CAwHlD,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -1 +1 @@
1
- import{jsx as e,jsxs as r}from"react/jsx-runtime";import{useState as n,useEffect as o}from"react";import{makeStyles as a,Dialog as t,DialogSurface as c,DialogBody as i,DialogTitle as l,DialogContent as d,Field as s,Checkbox as p,Input as h,DialogActions as f,Button as m}from"@fluentui/react-components";import y from"../hooks/useLocalization.js";const u=a({content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),k=({open:a,onClose:k,onSave:x,columns:g,initialData:v,title:C})=>{const b=u(),{t:A}=y(),[S,w]=n({}),[D,N]=n(!1);o((()=>{a&&w(v||{})}),[a,v]);const j=e=>Array.isArray(e.key)?e.key[0]:e.key,E=e=>{if(Array.isArray(e.key))for(const r of e.key)if(void 0!==S[r])return r;return j(e)},L=(e,r)=>{const n=E(e);w((e=>({...e,[n]:r})))},R=g.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==j(e)));return e(t,{open:a,onOpenChange:(e,r)=>!D&&!1===r.open&&k(),children:e(c,{backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:r(i,{children:[e(l,{children:C||A(v?"Edit Record":"Add Record")}),e(d,{className:b.content,children:R.map(((r,n)=>{const o=j(r),a=(e=>{const r=E(e);return S[r]})(r),t=r.title||o;return"checkbox"===r.type?e(s,{label:t,className:b.field,children:e(p,{checked:!0===a||"true"===a||"yes"===a||"1"===a,onChange:(e,n)=>L(r,n.checked)})},n):e(s,{label:t,className:b.field,children:e(h,{value:String(a??""),onChange:(e,n)=>L(r,n.value),placeholder:A("Enter")+" "+t.toLowerCase()})},n)}))}),r(f,{children:[e(m,{appearance:"secondary",onClick:k,disabled:D,children:A("Cancel")}),e(m,{appearance:"primary",onClick:async()=>{N(!0);try{await x(S),k()}catch(e){console.error("Failed to save record:",e)}finally{N(!1)}},disabled:D,children:A(D?"Saving...":"Save")})]})]})})})};export{k as RecordModal,k as default};
1
+ import{jsx as e,jsxs as r}from"react/jsx-runtime";import{useState as a,useEffect as n}from"react";import{makeStyles as o,Dialog as l,DialogSurface as t,DialogBody as c,DialogTitle as i,DialogContent as d,Field as s,Checkbox as p,Textarea as h,Input as f,DialogActions as m,Button as y}from"@fluentui/react-components";import u from"../hooks/useLocalization.js";const k=o({content:{display:"flex",flexDirection:"column",gap:"16px",minWidth:"400px",maxHeight:"60vh",overflowY:"auto"},field:{display:"flex",flexDirection:"column"}}),v=({open:o,onClose:v,onSave:g,columns:x,initialData:C,title:b})=>{const w=k(),{t:A}=u(),[S,N]=a({}),[D,E]=a(!1);n((()=>{o&&N(C||{})}),[o,C]);const L=e=>Array.isArray(e.key)?e.key[0]:e.key,j=e=>{if(Array.isArray(e.key))for(const r of e.key)if(void 0!==S[r])return r;return L(e)},z=(e,r)=>{const a=j(e);N((e=>({...e,[a]:r})))},R=x.filter((e=>!e.hidden&&"file"!==e.type&&"createdAt"!==L(e)));return e(l,{open:o,onOpenChange:(e,r)=>!D&&!1===r.open&&v(),children:e(t,{backdrop:{style:{backgroundColor:"rgba(0, 0, 0, 0.4)"}},children:r(c,{children:[e(i,{children:b||A(C?"Edit Record":"Add Record")}),e(d,{className:w.content,children:R.map(((r,a)=>{const n=L(r),o=(e=>{const r=j(e);return S[r]})(r),l=r.title||n;return"checkbox"===r.type?e(s,{label:l,className:w.field,children:e(p,{checked:!0===o||"true"===o||"yes"===o||"1"===o,onChange:(e,a)=>z(r,a.checked)})},a):"textarea"===r.type?e(s,{label:l,className:w.field,children:e(h,{value:String(o??""),rows:r.rows??3,onChange:(e,a)=>z(r,a.value),placeholder:A("Enter")+" "+l.toLowerCase(),resize:"vertical"})},a):e(s,{label:l,className:w.field,children:e(f,{value:String(o??""),onChange:(e,a)=>z(r,a.value),placeholder:A("Enter")+" "+l.toLowerCase()})},a)}))}),r(m,{children:[e(y,{appearance:"secondary",onClick:v,disabled:D,children:A("Cancel")}),e(y,{appearance:"primary",onClick:async()=>{E(!0);try{await g(S),v()}catch(e){console.error("Failed to save record:",e)}finally{E(!1)}},disabled:D,children:A(D?"Saving...":"Save")})]})]})})})};export{v as RecordModal,v as default};
@@ -1 +1 @@
1
- import{useRef as e,useState as t,useCallback as n,useEffect as r,useMemo as o}from"react";import{WavRenderer as a}from"../utils/wav_renderer.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import{WavStreamPlayer as s}from"../lib/wavtools/lib/wav_stream_player.js";import{WavRecorder as i}from"../lib/wavtools/lib/wav_recorder.js";import{getConfigValue as c}from"../config/index.js";const l=(l,u,d,p,m)=>{const f=!!c("APP_CONFIG"),g=!!c("APP_BUTTONS");f||console.warn("APP_CONFIG is not set. Voice AI will not be available."),g||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const y=c("APP_CONFIG"),_=c("APP_BUTTONS");c("API_BASE_URL").replace(/\/$/,""),c("USE_REALTIME_SESSION_ENDPOINT"),c("REALTIME_SESSION_ENDPOINT");const w=p||c("REALTIME_VOICE_MODEL")||"alloy",h=m||c("REALTIME_VOICE_PROVIDER")||"openai",S=["alloy","shimmer","echo"],v=S.includes(w)?w:"alloy";w!==v&&console.warn(`[codicent-app-sdk] Voice "${w}" is not supported in the current SDK version. Supported voices: ${S.join(", ")}. Falling back to "${v}".`),console.log(`[codicent-app-sdk] Using voice provider: ${h}`);const O=e(new i({sampleRate:24e3})),I=e(new s({sampleRate:24e3})),T=e(null),N=e(null),E=e(null),R=e(null),A=e(!1),C=e(null),P=e(null),b=e(null),D=e((new Date).toISOString()),[$,F]=t([]),[J,M]=t([]),[k,x]=t(!1),[L,V]=t(!1),[U,j]=t(!1),[B,G]=t(!1),q=e(0),W=e(0),[H,z]=t(""),[K,Q]=t("en-US"),X=e(new Map),Y=e(null),[Z,ee]=t((()=>f&&g&&_&&y&&y.apps&&y.apps[_]?y.apps[_].voiceInstructions||y.REALTIME_VOICE_INSTRUCTIONS||"":y&&y.REALTIME_VOICE_INSTRUCTIONS||"")),te=n((e=>{const t=D.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,o=Math.floor(r/10)%100,a=Math.floor(r/1e3)%60,s=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${s(Math.floor(r/6e4)%60)}:${s(a)}.${s(o)}`}),[]),ne=n((async()=>{try{D.current=(new Date).toISOString(),x(!0),M([]),F([]),X.current.clear();const e=await l.getRealtimeSessionToken(v,h);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;T.current=t,E.current||(E.current=new Audio,E.current.autoplay=!0),t.ontrack=e=>{E.current&&e.streams[0]&&(E.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});R.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const o=t.createDataChannel("oai-events");N.current=o,o.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);if("session.created"===t.type);else if("conversation.item.created"===t.type)F((e=>[...e,t.item]));else if("conversation.item.input_audio_transcription.completed"===t.type)F((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n}));else if("response.audio_transcript.delta"===t.type);else if("response.audio_transcript.done"===t.type);else if("response.output_item.added"===t.type){const e=t.item;"function_call"===e?.type&&(console.log("[Voice AI] Function call initiated:",e.name),X.current.set(e.id,{name:e.name||"",arguments:"",call_id:e.call_id||e.id}))}else if("response.function_call_arguments.delta"===t.type){const e=t.item_id,n=t.delta,r=X.current.get(e);r&&n&&(r.arguments+=n,X.current.set(e,r))}else if("response.function_call_arguments.done"===t.type){const e=t.item_id,n=X.current.get(e);if(n){console.log(`[Voice AI] Executing tool: ${n.name}`);const t=d.find((e=>e.definition.name===n.name));if(t){let e={};try{e=n.arguments?JSON.parse(n.arguments):{}}catch(t){console.error("[Voice AI] Failed to parse tool arguments:",t),e={}}Promise.resolve(t.handler(e)).then((e=>{console.log(`[Voice AI] Tool ${n.name} completed:`,e),o&&"open"===o.readyState&&(o.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify(e)}})),o.send(JSON.stringify({type:"response.create"})))})).catch((e=>{console.error(`[Voice AI] Tool ${n.name} failed:`,e),o&&"open"===o.readyState&&(o.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify({error:e.message||"Tool execution failed"})}})),o.send(JSON.stringify({type:"response.create"})))}))}else console.error(`[Voice AI] Tool not found: ${n.name}`);X.current.delete(e)}}else"error"===t.type&&console.error("Server error:",t.error)}catch(t){console.warn("Invalid message:",e.data)}})),o.onopen=()=>{console.log("Data channel opened, configuring session");const e=Y.current||Z;Y.current=null,o.send(JSON.stringify({type:"session.update",session:{instructions:e.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:v,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:d.map((e=>({type:"function",...e.definition})))}})),V(!0)},o.onclose=()=>{console.log("Data channel closed"),V(!1)};const a=await t.createOffer();await t.setLocalDescription(a);let s="gpt-4o-realtime-preview";try{if(c("REALTIME_CONFIG_ENDPOINT")){const e=await l.getRealtimeConfig();e&&e.model&&(s=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const i="https://api.openai.com/v1/realtime",u=await fetch(`${i}?model=${s}`,{method:"POST",body:a.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!u.ok)throw new Error(`Failed to get SDP answer: ${u.statusText}`);const p={type:"answer",sdp:await u.text()};await t.setRemoteDescription(p),j(!1);const m=O.current,f=I.current;await m.begin(),await f.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),x(!1),e}}),[l,v,Z,H,K,d]),re=n((async()=>{x(!1),V(!1),M([]),F([]),X.current.clear(),Y.current=null,N.current&&(N.current.close(),N.current=null),T.current&&(T.current.close(),T.current=null),R.current&&(R.current.getTracks().forEach((e=>e.stop())),R.current=null),E.current&&(E.current.pause(),E.current.srcObject=null);const e=O.current;await e.end();const t=I.current;await t.interrupt()}),[]),oe=n((async e=>{const t=N.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),ae=n((async()=>{G(!0);const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),se=n((async()=>{G(!1);const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),ie=n((async e=>{const t=N.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),j("none"===e)}),[]);r((()=>{if(H&&L){const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:Z.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString())}}))}}),[Z,H,K,L]),r((()=>{let e=!0;const t=O.current,n=C.current;let r=null;const o=I.current,s=P.current;let i=null;const c=()=>{if(e){if(n&&(n.width&&n.height||(n.width=n.offsetWidth,n.height=n.offsetHeight),r=r||n.getContext("2d"),r)){r.clearRect(0,0,n.width,n.height);const e=t.recording?t.getFrequencies("voice"):{values:new Float32Array([0])},o=1-Math.max(...e.values);q.current=o,a.drawCircularBars(n,r,e.values,"#0099ff",20,0,8)}if(s&&(s.width&&s.height||(s.width=s.offsetWidth,s.height=s.offsetHeight),i=i||s.getContext("2d"),i)){i.clearRect(0,0,s.width,s.height);const e=o.analyser?o.getFrequencies("voice"):{values:new Float32Array([0])},t=1-Math.max(...e.values);W.current=t,a.drawCircularBars(s,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),r((()=>{!A.current&&d&&Z&&(A.current=!0)}),[d,Z]);const ce=n((e=>{ee(e);const t=N.current;if(t&&"open"===t.readyState){const n=e.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString());t.send(JSON.stringify({type:"session.update",session:{instructions:n}}))}else Y.current=e}),[H,K]);return o((()=>{if(f&&g)return{items:$,realtimeEvents:J,isConnected:k,isSessionReady:L,canPushToTalk:U,isRecording:B,clientCanvasRef:C,serverCanvasRef:P,eventsScrollRef:b,formatTime:te,connectConversation:ne,disconnectConversation:re,deleteConversationItem:oe,startRecording:ae,stopRecording:se,changeTurnEndType:ie,getRecorderLevel:()=>q.current,getStreamLevel:()=>W.current,setUsername:z,updateInstructions:ce,setLanguage:Q}}),[f,g,$,J,k,L,U,B,C,P,b])};export{l as default};
1
+ import{useRef as e,useState as t,useCallback as n,useEffect as r,useMemo as o}from"react";import{WavRenderer as a}from"../utils/wav_renderer.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import{WavStreamPlayer as s}from"../lib/wavtools/lib/wav_stream_player.js";import{WavRecorder as i}from"../lib/wavtools/lib/wav_recorder.js";import{getConfigValue as c}from"../config/index.js";const l=(l,u,d,p,m)=>{const f=!!c("APP_CONFIG"),g=!!c("APP_BUTTONS");f||console.warn("APP_CONFIG is not set. Voice AI will not be available."),g||console.warn("APP_BUTTONS is not set. Voice AI will not be available.");const y=c("APP_CONFIG"),_=c("APP_BUTTONS");c("API_BASE_URL").replace(/\/$/,""),c("USE_REALTIME_SESSION_ENDPOINT"),c("REALTIME_SESSION_ENDPOINT");const w=p||c("REALTIME_VOICE_MODEL")||"alloy",h=m||c("REALTIME_VOICE_PROVIDER")||"openai",S=["alloy","shimmer","echo"],v=S.includes(w)?w:"alloy";w!==v&&console.warn(`[codicent-app-sdk] Voice "${w}" is not supported in the current SDK version. Supported voices: ${S.join(", ")}. Falling back to "${v}".`);const O=e(new i({sampleRate:24e3})),I=e(new s({sampleRate:24e3})),T=e(null),N=e(null),E=e(null),R=e(null),A=e(!1),C=e(null),P=e(null),b=e(null),D=e((new Date).toISOString()),[F,J]=t([]),[M,$]=t([]),[x,L]=t(!1),[V,k]=t(!1),[U,j]=t(!1),[B,G]=t(!1),q=e(0),W=e(0),[H,z]=t(""),[K,Q]=t("en-US"),X=e(new Map),Y=e(null),[Z,ee]=t((()=>f&&g&&_&&y&&y.apps&&y.apps[_]?y.apps[_].voiceInstructions||y.REALTIME_VOICE_INSTRUCTIONS||"":y&&y.REALTIME_VOICE_INSTRUCTIONS||"")),te=n((e=>{const t=D.current,n=new Date(t).valueOf(),r=new Date(e).valueOf()-n,o=Math.floor(r/10)%100,a=Math.floor(r/1e3)%60,s=e=>{let t=e+"";for(;t.length<2;)t="0"+t;return t};return`${s(Math.floor(r/6e4)%60)}:${s(a)}.${s(o)}`}),[]),ne=n((async()=>{try{D.current=(new Date).toISOString(),L(!0),$([]),J([]),X.current.clear();const e=await l.getRealtimeSessionToken(v,h);if(!e)throw new Error("No ephemeral key returned from session endpoint");const t=new RTCPeerConnection;T.current=t,E.current||(E.current=new Audio,E.current.autoplay=!0),t.ontrack=e=>{E.current&&e.streams[0]&&(E.current.srcObject=e.streams[0])};const n=await navigator.mediaDevices.getUserMedia({audio:!0});R.current=n;const r=n.getTracks()[0];t.addTrack(r,n);const o=t.createDataChannel("oai-events");N.current=o,o.addEventListener("message",(e=>{try{const t=JSON.parse(e.data);if("session.created"===t.type);else if("conversation.item.created"===t.type)J((e=>[...e,t.item]));else if("conversation.item.input_audio_transcription.completed"===t.type)J((e=>{const n=[...e],r=n.findIndex((e=>e.id===t.item_id));return-1!==r&&n[r].formatted&&(n[r].formatted.transcript=t.transcript),n}));else if("response.audio_transcript.delta"===t.type);else if("response.audio_transcript.done"===t.type);else if("response.output_item.added"===t.type){const e=t.item;"function_call"===e?.type&&(console.log("[Voice AI] Function call initiated:",e.name),X.current.set(e.id,{name:e.name||"",arguments:"",call_id:e.call_id||e.id}))}else if("response.function_call_arguments.delta"===t.type){const e=t.item_id,n=t.delta,r=X.current.get(e);r&&n&&(r.arguments+=n,X.current.set(e,r))}else if("response.function_call_arguments.done"===t.type){const e=t.item_id,n=X.current.get(e);if(n){console.log(`[Voice AI] Executing tool: ${n.name}`);const t=d.find((e=>e.definition.name===n.name));if(t){let e={};try{e=n.arguments?JSON.parse(n.arguments):{}}catch(t){console.error("[Voice AI] Failed to parse tool arguments:",t),e={}}Promise.resolve(t.handler(e)).then((e=>{console.log(`[Voice AI] Tool ${n.name} completed:`,e),o&&"open"===o.readyState&&(o.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify(e)}})),o.send(JSON.stringify({type:"response.create"})))})).catch((e=>{console.error(`[Voice AI] Tool ${n.name} failed:`,e),o&&"open"===o.readyState&&(o.send(JSON.stringify({type:"conversation.item.create",item:{type:"function_call_output",call_id:n.call_id,output:JSON.stringify({error:e.message||"Tool execution failed"})}})),o.send(JSON.stringify({type:"response.create"})))}))}else console.error(`[Voice AI] Tool not found: ${n.name}`);X.current.delete(e)}}else"error"===t.type&&console.error("Server error:",t.error)}catch(t){console.warn("Invalid message:",e.data)}})),o.onopen=()=>{console.log("Data channel opened, configuring session");const e=Y.current||Z;Y.current=null,o.send(JSON.stringify({type:"session.update",session:{instructions:e.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString()),modalities:["text","audio"],input_audio_transcription:{model:"whisper-1"},turn_detection:{type:"server_vad",threshold:.5,prefix_padding_ms:300,silence_duration_ms:500},voice:v,temperature:.8,max_response_output_tokens:4096,input_audio_format:"pcm16",output_audio_format:"pcm16",tools:d.map((e=>({type:"function",...e.definition})))}})),k(!0)},o.onclose=()=>{console.log("Data channel closed"),k(!1)};const a=await t.createOffer();await t.setLocalDescription(a);let s="gpt-4o-realtime-preview";try{if(c("REALTIME_CONFIG_ENDPOINT")){const e=await l.getRealtimeConfig();e&&e.model&&(s=e.model)}}catch(e){console.warn("Failed to fetch realtime config, using default model:",e)}const i="https://api.openai.com/v1/realtime",u=await fetch(`${i}?model=${s}`,{method:"POST",body:a.sdp,headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/sdp"}});if(!u.ok)throw new Error(`Failed to get SDP answer: ${u.statusText}`);const p={type:"answer",sdp:await u.text()};await t.setRemoteDescription(p),j(!1);const m=O.current,f=I.current;await m.begin(),await f.connect()}catch(e){throw console.error("[codicent-app-sdk] Failed to establish WebRTC connection:",e),L(!1),e}}),[l,v,Z,H,K,d]),re=n((async()=>{L(!1),k(!1),$([]),J([]),X.current.clear(),Y.current=null,N.current&&(N.current.close(),N.current=null),T.current&&(T.current.close(),T.current=null),R.current&&(R.current.getTracks().forEach((e=>e.stop())),R.current=null),E.current&&(E.current.pause(),E.current.srcObject=null);const e=O.current;await e.end();const t=I.current;await t.interrupt()}),[]),oe=n((async e=>{const t=N.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"conversation.item.delete",item_id:e}))}),[]),ae=n((async()=>{G(!0);const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"input_audio_buffer.commit"}))}),[]),se=n((async()=>{G(!1);const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"response.create"}))}),[]),ie=n((async e=>{const t=N.current;t&&"open"===t.readyState&&t.send(JSON.stringify({type:"session.update",session:{turn_detection:"none"===e?null:{type:"server_vad"}}})),j("none"===e)}),[]);r((()=>{if(H&&V){const e=N.current;e&&"open"===e.readyState&&e.send(JSON.stringify({type:"session.update",session:{instructions:Z.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString())}}))}}),[Z,H,K,V]),r((()=>{let e=!0;const t=O.current,n=C.current;let r=null;const o=I.current,s=P.current;let i=null;const c=()=>{if(e){if(n&&(n.width&&n.height||(n.width=n.offsetWidth,n.height=n.offsetHeight),r=r||n.getContext("2d"),r)){r.clearRect(0,0,n.width,n.height);const e=t.recording?t.getFrequencies("voice"):{values:new Float32Array([0])},o=1-Math.max(...e.values);q.current=o,a.drawCircularBars(n,r,e.values,"#0099ff",20,0,8)}if(s&&(s.width&&s.height||(s.width=s.offsetWidth,s.height=s.offsetHeight),i=i||s.getContext("2d"),i)){i.clearRect(0,0,s.width,s.height);const e=o.analyser?o.getFrequencies("voice"):{values:new Float32Array([0])},t=1-Math.max(...e.values);W.current=t,a.drawCircularBars(s,i,e.values,"#009900",20,0,8)}window.requestAnimationFrame(c)}};return c(),()=>{e=!1}}),[]),r((()=>{!A.current&&d&&Z&&(A.current=!0)}),[d,Z]);const ce=n((e=>{ee(e);const t=N.current;if(t&&"open"===t.readyState){const n=e.replace("{{name}}",H).replace("{{language}}",K).replace("{{time}}",(new Date).toISOString());t.send(JSON.stringify({type:"session.update",session:{instructions:n}}))}else Y.current=e}),[H,K]);return o((()=>{if(f&&g)return{items:F,realtimeEvents:M,isConnected:x,isSessionReady:V,canPushToTalk:U,isRecording:B,clientCanvasRef:C,serverCanvasRef:P,eventsScrollRef:b,formatTime:te,connectConversation:ne,disconnectConversation:re,deleteConversationItem:oe,startRecording:ae,stopRecording:se,changeTurnEndType:ie,getRecorderLevel:()=>q.current,getStreamLevel:()=>W.current,setUsername:z,updateInstructions:ce,setLanguage:Q}}),[f,g,F,M,x,V,U,B,C,P,b])};export{l as default};
@@ -54,7 +54,7 @@ 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) => Promise<DataMessage[]>;
57
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
58
58
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
59
59
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
60
60
  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,W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AmB,MAAM,YAAY,MAAM,qBAqBlD;IAEF,SAAS,+BAqCP;IAEF,YAAY,+BAeV;IAEF,MAAM,CAAC,YAAY,SAAgB,QAAQ,mBAyBzC;IAEF,MAAM,CAAC,mBAAmB,YAAmB,MAAM,YAAW,MAAM,cAAgC,MAAM,iCA+BxG;IAEF;;;;;;;;OAQG;IACH,MAAM,CAAC,gBAAgB,YACZ,MAAM,YACN,MAAM,cACH,MAAM,mBACF,MAAM,oBACL,MAAM,KACtB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA+E5B;IAEF,QAAQ,QAAa,OAAO,CAAC,IAAI,EAAE,CAAC,CAMlC;IAEF,WAAW,OAAc,MAAM,mBAO7B;IAGF,OAAO,CAAC,kBAAkB;IAM1B,aAAa,cAAqB,MAAM,KAAG,OAAO,CAAC,MAAM,GAAG,QAAQ,GAAG,SAAS,CAAC,CAiB/E;IAEF,gBAAgB,cAAqB,MAAM,UAAU,MAAM,GAAG,QAAQ,sBAcpE;IAEI,uBAAuB,CAAC,KAAK,GAAE,MAAgB,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
- 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)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.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)=>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};
package/dist/index.d.ts CHANGED
@@ -67,7 +67,7 @@ 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) => Promise<DataMessage[]>;
70
+ readDataMessages: (tag: string, search?: string, codicent?: string, start?: number, length?: number, afterTimestamp?: string, beforeTimestamp?: string) => Promise<DataMessage[]>;
71
71
  readOneDataMessage: (id: string) => Promise<DataMessage | null>;
72
72
  updateDataMessage: (id: string, data: object, codicent?: string) => Promise<string>;
73
73
  deleteDataMessage: (id: string, codicent?: string) => Promise<string>;
@@ -1081,7 +1081,9 @@ interface ColumnDefinition {
1081
1081
  hidden?: boolean;
1082
1082
  hideOnMobile?: boolean;
1083
1083
  maxWidth?: number;
1084
- type?: "file" | "checkbox" | undefined;
1084
+ type?: "file" | "checkbox" | "textarea" | undefined;
1085
+ /** Number of rows for textarea type (default: 3) */
1086
+ rows?: number;
1085
1087
  editable?: boolean;
1086
1088
  filterable?: boolean;
1087
1089
  /** Default sort direction for this column. If multiple columns have defaultSort, only the first one is used. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.4.3",
3
+ "version": "0.4.6",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",