codicent-app-sdk 0.4.13 → 0.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -129,9 +129,29 @@ DEFAULT_LANGUAGE: string
129
129
  SUBSCRIPTION_NEEDED: boolean
130
130
  REALTIME_VOICE_MODEL: string // Voice model: "alloy", "shimmer", or "echo" (default: "alloy")
131
131
  USE_REALTIME_SESSION_ENDPOINT: boolean // Use secure session endpoint (default: true)
132
+
133
+ // Compose page location options:
134
+ COMPOSE_HIDE_LOCATION: string // Set to "true" to hide the GPS toggle button entirely
135
+ COMPOSE_AUTO_LOCATION: string // Set to "true" to automatically capture GPS on compose page load
132
136
  // ...and more
133
137
  ```
134
138
 
139
+ #### Compose page GPS / location
140
+
141
+ The `Compose` page (route `/new`) supports GPS location tagging. When a location is attached, a `#gps(lat,lon)` tag is appended to the message content — readable by the AI chat instructions and queryable via tag search.
142
+
143
+ | Option | Value | Behaviour |
144
+ |--------|-------|-----------|
145
+ | `COMPOSE_HIDE_LOCATION` | `"true"` | Hides the GPS toggle button; users cannot attach location |
146
+ | `COMPOSE_HIDE_LOCATION` | `"false"` (default) | Shows the GPS toggle button; users opt-in per post |
147
+ | `COMPOSE_AUTO_LOCATION` | `"true"` | GPS is fetched **automatically** when the compose page opens — no button tap required. The toggle button is still shown so users can remove it if desired |
148
+
149
+ Example — always capture location (e.g. a spot-logging app):
150
+ ```js
151
+ COMPOSE_HIDE_LOCATION: "false",
152
+ COMPOSE_AUTO_LOCATION: "true",
153
+ ```
154
+
135
155
  For AI voice configuration and security, see the [Voice Upgrade Guide](VOICE_UPGRADE_GUIDE.md).
136
156
 
137
157
  #### Using Custom Domains
@@ -1,5 +1,5 @@
1
1
  export { default as useStateWithLocalStorage } from "./useStateWithLocalStorage";
2
- export { default as useAuthState, type UseAuthState } from "./useAuthState";
2
+ export { default as useAuthState, type UseAuthState, type AuthStateOptions } from "./useAuthState";
3
3
  export * from "./useChat";
4
4
  export { default as useCodicentState } from "./useCodicentState";
5
5
  export * from "./useAudioRecorder";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC5E,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACjE,cAAc,oBAAoB,CAAC;AAEnC,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,YAAY,CAAC;AACjD,YAAY,EAAE,IAAI,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACrE,cAAc,sBAAsB,CAAC;AACrC,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC/D,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAC3E,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACnG,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACjE,cAAc,oBAAoB,CAAC;AAEnC,OAAO,EAAE,OAAO,IAAI,QAAQ,EAAE,MAAM,YAAY,CAAC;AACjD,YAAY,EAAE,IAAI,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACrE,cAAc,sBAAsB,CAAC;AACrC,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC/D,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAC3E,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC"}
@@ -14,6 +14,12 @@ export interface UseAuthState {
14
14
  loginWithRedirect: (options?: RedirectLoginOptions<AppState>) => Promise<void>;
15
15
  loginPasswordless: (email: string) => Promise<void>;
16
16
  }
17
- declare const useAuthState: (auth0: Auth0ContextInterface) => UseAuthState;
17
+ export interface AuthStateOptions {
18
+ /** Override the backend login call. Defaults to Auth0-based LoginAuth0User endpoint. */
19
+ loginFn?: (service: CodicentService, userId: string, accessToken: string) => Promise<string | null | "">;
20
+ /** Override the backend register call. Defaults to Auth0-based RegisterAuth0User endpoint. */
21
+ registerFn?: (service: CodicentService, nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
22
+ }
23
+ declare const useAuthState: (auth0: Auth0ContextInterface, options?: AuthStateOptions) => UseAuthState;
18
24
  export default useAuthState;
19
25
  //# sourceMappingURL=useAuthState.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAuthState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAuthState.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC;AAUrC,MAAM,WAAW,YAAY;IAC3B,eAAe,EAAE,OAAO,CAAC;IACzB,YAAY,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IAInB,IAAI,EAAE,GAAG,CAAC;IACV,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/E,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACrD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,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,KAChB,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB;AAED,QAAA,MAAM,YAAY,UAAW,qBAAqB,YAAY,gBAAgB,KAAG,YAyRhF,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("../services/codicent.js");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("react/jsx-runtime"),require("@fluentui/react-components"),require("../components/Spinner.js"),require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js"),require("@fluentui/react-icons");var o=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./useLocalization.js"),require("./useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/Content.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/Page.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js"),require("../components/CookieBanner.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("react-router-dom"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");exports.default=s=>{const{isAuthenticated:n,getAccessTokenSilently:t,user:i,isLoading:a,logout:u,getAccessTokenWithPopup:c,loginWithRedirect:l,loginWithPopup:g}=s,[p,q]=e.useState(null),[j,m]=e.useState(void 0),[C,E]=e.useState(null),[d,P]=e.useState(""),_=e.useMemo((()=>new r.CodicentService({API_BASE_URL:o.getConfigValue("API_BASE_URL"),APP_LOG_CODICENT:o.getConfigValue("APP_LOG_CODICENT"),APP_LOG_TOKEN:o.getConfigValue("APP_LOG_TOKEN"),APP_NAME:o.getConfigValue("APP_NAME"),APP_PREFIX:o.getConfigValue("APP_PREFIX"),APP_TEMPLATE:o.getConfigValue("APP_TEMPLATE"),BUTTON_TAG:o.getConfigValue("BUTTON_TAG"),STRIPE_PUBLIC_KEY:o.getConfigValue("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:o.getConfigValue("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:o.getConfigValue("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:o.getConfigValue("SUBSCRIPTION_NEEDED"),USER_PREFIX:o.getConfigValue("USER_PREFIX"),ANONYMOUS_TOKEN:o.getConfigValue("ANONYMOUS_TOKEN")})),[]);e.useEffect((()=>{!a&&n&&(async()=>{try{const e=await t({});console.debug("CODICENT: ACCESS TOKEN",e),q(e)}catch(e){console.debug("CODICENT: Failed to get access token",e);const r=e;if(r&&"object"==typeof r&&"error"in r&&"login_required"===r.error)console.warn("CODICENT: Login required"),T();else if(r&&"object"==typeof r&&"error"in r&&"consent_required"===r.error)try{const e=await c();if(!e)return void E("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),q(e)}catch(e){console.warn("CODICENT: Failed to get access token with popup",e),T()}else E("Failed to get access token: "+(r.message?.toString()||r.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",r)}})().then((()=>{}))}),[n,c,t,l,a]),e.useEffect((()=>{if(i&&i.sub&&p&&void 0===j){let e=!0;return _.loginUser(i.sub,p).then((r=>{e&&(null===r?m(!1):""===r?E("Kontrollera internetanslutningen och försök igen."):(_.setToken(p),_.getNickname().then(P),m(!0)))})).catch((()=>{e&&(E("Ett fel uppstod. Försök igen senare."),m(!1))})),()=>{e=!1}}}),[i,p,j,_]);const T=e.useCallback((()=>{_.logout(),q(null),E(null),m(void 0),P(""),u({logoutParams:{returnTo:o.getConfigValue("AUTH_REDIRECT_URL")}})}),[_,u]),S=e.useCallback((async e=>{const r=await _.registerUser(e,i.email,i.sub,p);return r&&(_.setToken(p),m(!0)),r}),[_,i,p]);e.useEffect((()=>{_.onUnauthorized=T}),[_]);const f=e.useCallback((async e=>{try{await g({authorizationParams:{connection:"email",login_hint:e}})}catch(e){console.error("Passwordless login failed:",e),E(`Passwordless login failed: ${e}`)}}),[g]);return e.useMemo((()=>({isAuthenticated:n,isRegistered:j,accessToken:p,authError:C,isLoading:a,user:i,nickname:d,logout:T,registerUser:S,codicentService:_,loginWithRedirect:l,loginPasswordless:f})),[n,j,p,C,a,i,d,T,S,_,l,f])};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),r=require("../services/codicent.js");require("../components/Markdown.js"),require("../components/Textarea.js"),require("../components/Button.js"),require("../components/CompoundButton.js"),require("react/jsx-runtime"),require("@fluentui/react-components"),require("../components/Spinner.js"),require("../components/TextHeader.js"),require("../components/TypingIndicator.js"),require("../components/Dialog.js"),require("../components/ChatInput.js"),require("../components/CombinedPlaceholderDialog.js"),require("../components/ChatMessage.js"),require("../components/Header.js"),require("@fluentui/react-icons");var o=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("../_virtual/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("./useLocalization.js"),require("./useAppStyles.js"),require("../components/FileThumbnail.js"),require("../components/MessageInput.js"),require("../components/UploadFile.js"),require("../components/SnapFooter.js"),require("../components/Profile.js"),require("../components/MessageItem.js"),require("../components/Content.js"),require("../components/AiInput.js"),require("../components/SearchBox.js"),require("../components/HtmlView.js"),require("../components/Footer.js"),require("../components/Page.js"),require("../components/QrCodeDialog.js"),require("../components/QrScanner.js"),require("../components/OfflineMessage.js"),require("../components/LanguageSelector.js"),require("../components/ListView.js"),require("../components/RecordModal.js"),require("../components/BulkUploadDialog.js"),require("../components/CookieBanner.js"),require("../pages/AppFrame.js"),require("../pages/Chat.js"),require("../pages/Compose.js"),require("../pages/Snap.js"),require("../pages/Search.js"),require("../pages/Login.js"),require("../pages/CrmPage.js"),require("../pages/CrmPagePersistent.js"),require("../pages/ImageView.js"),require("../pages/FormInvite.js"),require("../pages/FormAccept.js"),require("../pages/Sales.js"),require("../pages/Purchase.js"),require("../pages/QrScan.js"),require("react-dom/client"),require("react-router-dom"),require("../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js");exports.default=(s,n)=>{const{isAuthenticated:t,getAccessTokenSilently:i,user:a,isLoading:u,logout:c,getAccessTokenWithPopup:l,loginWithRedirect:g,loginWithPopup:p}=s,[q,m]=e.useState(null),[j,C]=e.useState(void 0),[E,d]=e.useState(null),[P,_]=e.useState(""),T=e.useMemo((()=>new r.CodicentService({API_BASE_URL:o.getConfigValue("API_BASE_URL"),APP_LOG_CODICENT:o.getConfigValue("APP_LOG_CODICENT"),APP_LOG_TOKEN:o.getConfigValue("APP_LOG_TOKEN"),APP_NAME:o.getConfigValue("APP_NAME"),APP_PREFIX:o.getConfigValue("APP_PREFIX"),APP_TEMPLATE:o.getConfigValue("APP_TEMPLATE"),BUTTON_TAG:o.getConfigValue("BUTTON_TAG"),STRIPE_PUBLIC_KEY:o.getConfigValue("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:o.getConfigValue("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:o.getConfigValue("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:o.getConfigValue("SUBSCRIPTION_NEEDED"),USER_PREFIX:o.getConfigValue("USER_PREFIX"),ANONYMOUS_TOKEN:o.getConfigValue("ANONYMOUS_TOKEN")})),[]);e.useEffect((()=>{!u&&t&&(async()=>{try{const e=await i({});console.debug("CODICENT: ACCESS TOKEN",e),m(e)}catch(e){console.debug("CODICENT: Failed to get access token",e);const r=e;if(r&&"object"==typeof r&&"error"in r&&"login_required"===r.error)console.warn("CODICENT: Login required"),S();else if(r&&"object"==typeof r&&"error"in r&&"consent_required"===r.error)try{const e=await l();if(!e)return void d("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),m(e)}catch(e){console.warn("CODICENT: Failed to get access token with popup",e),S()}else d("Failed to get access token: "+(r.message?.toString()||r.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",r)}})().then((()=>{}))}),[t,l,i,g,u]),e.useEffect((()=>{if(a&&a.sub&&q&&void 0===j){let e=!0;return(n?.loginFn?n.loginFn(T,a.sub,q):T.loginUser(a.sub,q)).then((r=>{e&&(null===r?C(!1):""===r?d("Kontrollera internetanslutningen och försök igen."):(T.setToken(r),T.getNickname().then(_),C(!0)))})).catch((()=>{e&&(d("Ett fel uppstod. Försök igen senare."),C(!1))})),()=>{e=!1}}}),[a,q,j,T]);const S=e.useCallback((()=>{T.logout(),m(null),d(null),C(void 0),_(""),c({logoutParams:{returnTo:o.getConfigValue("AUTH_REDIRECT_URL")}})}),[T,c]),f=e.useCallback((async e=>{const r=n?.registerFn?await n.registerFn(T,e,a.email,a.sub,q):await T.registerUser(e,a.email,a.sub,q);return r&&(T.setToken(r),C(!0)),r}),[T,a,q]);e.useEffect((()=>{T.onUnauthorized=S}),[T]);const A=e.useCallback((async e=>{try{await p({authorizationParams:{connection:"email",login_hint:e}})}catch(e){console.error("Passwordless login failed:",e),d(`Passwordless login failed: ${e}`)}}),[p]);return e.useMemo((()=>({isAuthenticated:t,isRegistered:j,accessToken:q,authError:E,isLoading:u,user:a,nickname:P,logout:S,registerUser:f,codicentService:T,loginWithRedirect:g,loginPasswordless:A})),[t,j,q,E,u,a,P,S,f,T,g,A])};
@@ -2,7 +2,7 @@ import { Auth0ContextInterface } from "@auth0/auth0-react";
2
2
  import { CodicentService } from "../services";
3
3
  import { AppStateMachine, StateContext, AppStateDefinition } from "../utils";
4
4
  import { AudioRecorderState } from "./useAudioRecorder";
5
- import { UseAuthState } from "./useAuthState";
5
+ import { AuthStateOptions, UseAuthState } from "./useAuthState";
6
6
  import { RealtimeVoice } from "./useRealtimeVoiceAI";
7
7
  import { ToolsConfig } from "./useTools";
8
8
  export interface CodicentAppState {
@@ -29,6 +29,7 @@ export interface CodicentAppState {
29
29
  export interface UseCodicentAppOptions {
30
30
  auth0: Auth0ContextInterface;
31
31
  toolsConfig?: ToolsConfig;
32
+ authOptions?: AuthStateOptions;
32
33
  }
33
- export declare const useCodicentApp: ({ auth0, toolsConfig }: UseCodicentAppOptions) => CodicentAppState;
34
+ export declare const useCodicentApp: ({ auth0, toolsConfig, authOptions }: UseCodicentAppOptions) => CodicentAppState;
34
35
  //# sourceMappingURL=useCodicentApp.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useCodicentApp.d.ts","sourceRoot":"","sources":["../../../src/hooks/useCodicentApp.tsx"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,kBAAkB,EAAyB,MAAM,UAAU,CAAC;AACpG,OAAyB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB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@@ -1 +1 @@
1
- "use strict";var e=require("react");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime");var t=require("../utils/appState.js");require("../_virtual/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("../utils/cacheManager.js");var r=require("./useAudioRecorder.js"),s=require("./useAuthState.js"),n=require("./useRealtimeVoiceAI.js"),a=require("./useTools.js"),c=require("../config/index.js");exports.useCodicentApp=({auth0:u,toolsConfig:i})=>{const o=s.default(u),l=e.useRef(t.createAppStateMachine(o.codicentService,(()=>{}))),[d,m]=e.useState(),{service:p,context:f}=l.current,{nickname:h,name:g,error:A,errorType:k,selectedApp:v}=f,C=e.useCallback(((e,t)=>{const r=e.get("file").name;p.uploadFile(r,e).then((e=>{p.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[p]),b=r.useAudioRecorder(C),[S,q]=e.useState(),[j,w]=e.useState(),[y,x]=e.useState(!1),T=e.useMemo((()=>new Audio("./notification.mp3")),[]),_=e.useCallback((()=>x(!0)),[]),E=a.default(p,q,w,T,S,_,i),I=e.useMemo((()=>c.getConfigValue("REALTIME_VOICE_API_KEY")||""),[]),M=n.default(p,I,E);e.useEffect((()=>{y&&(M?.disconnectConversation(),x(!1))}),[y,M]),e.useEffect((()=>{o.isAuthenticated&&o.user&&o.accessToken&&l.current.updateContext({isAuthenticated:o.isAuthenticated,user:{sub:o.user.sub,email:o.user.email},accessToken:o.accessToken})}),[o.isAuthenticated,o.user,o.accessToken]);const R=e.useRef(o.isAuthenticated);e.useEffect((()=>{const e=!0===R.current,t=!0===o.isAuthenticated;e&&!t&&l.current.logout(),R.current=o.isAuthenticated}),[o.isAuthenticated]),e.useEffect((()=>l.current.updateContext({nickname:o.nickname})),[o.nickname]),e.useEffect((()=>{l.current.update();let e,t=l.current.getCurrentStateName();m(l.current.getCurrentStateName()),JSON.stringify(l.current.context);let r=!1;const s=n=>setInterval((()=>{const n=l.current.getCurrentStateName();if("hasAccess"===n&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=s(1e3));if("hasAccess"!==n&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=s(200));const a=JSON.stringify(l.current.context);l.current.update();const c=JSON.stringify(l.current.context),u=l.current.getCurrentStateName();u===t&&a===c||(m(u),t=u)}),n);return e=s(200),()=>clearInterval(e)}),[]);const N=e.useCallback((e=>e.replace("{nickname}",h||"unknown").replace("{token}",encodeURIComponent(o.accessToken||"unknown")).replace("{app}",v||"unknown")),[h,o.accessToken,v]),O=e.useCallback((e=>{l.current.updateContext({isAnonymous:e})}),[]),J=e.useCallback((()=>l.current.isBusy()),[]);return e.useMemo((()=>({audio:b,auth:o,currentStateName:d,stateMachine:l.current,service:p,context:f,state:d,nickname:h,name:g,error:A,errorType:k,fixAppUrl:N,setAnonymous:O,allStates:l.current.allStates,isBusy:J,voice:M,html:S,setHtml:q,script:j})),[d,h,g,A,k,S,j,o.isAuthenticated,o.isLoading,b.isRecording,M?.isConnected,N,O,J])};
1
+ "use strict";var e=require("react");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime");var t=require("../utils/appState.js");require("../_virtual/index.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js"),require("../utils/cacheManager.js");var r=require("./useAudioRecorder.js"),s=require("./useAuthState.js"),n=require("./useRealtimeVoiceAI.js"),a=require("./useTools.js"),c=require("../config/index.js");exports.useCodicentApp=({auth0:u,toolsConfig:i,authOptions:o})=>{const l=s.default(u,o),d=e.useRef(t.createAppStateMachine(l.codicentService,(()=>{}))),[m,p]=e.useState(),{service:f,context:h}=d.current,{nickname:g,name:A,error:k,errorType:v,selectedApp:C}=h,b=e.useCallback(((e,t)=>{const r=e.get("file").name;f.uploadFile(r,e).then((e=>{f.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[f]),S=r.useAudioRecorder(b),[q,j]=e.useState(),[w,y]=e.useState(),[x,T]=e.useState(!1),_=e.useMemo((()=>new Audio("./notification.mp3")),[]),E=e.useCallback((()=>T(!0)),[]),I=a.default(f,j,y,_,q,E,i),M=e.useMemo((()=>c.getConfigValue("REALTIME_VOICE_API_KEY")||""),[]),R=n.default(f,M,I);e.useEffect((()=>{x&&(R?.disconnectConversation(),T(!1))}),[x,R]),e.useEffect((()=>{l.isAuthenticated&&l.user&&l.accessToken&&d.current.updateContext({isAuthenticated:l.isAuthenticated,user:{sub:l.user.sub,email:l.user.email},accessToken:l.accessToken})}),[l.isAuthenticated,l.user,l.accessToken]);const N=e.useRef(l.isAuthenticated);e.useEffect((()=>{const e=!0===N.current,t=!0===l.isAuthenticated;e&&!t&&d.current.logout(),N.current=l.isAuthenticated}),[l.isAuthenticated]),e.useEffect((()=>d.current.updateContext({nickname:l.nickname})),[l.nickname]),e.useEffect((()=>{d.current.update();let e,t=d.current.getCurrentStateName();p(d.current.getCurrentStateName()),JSON.stringify(d.current.context);let r=!1;const s=n=>setInterval((()=>{const n=d.current.getCurrentStateName();if("hasAccess"===n&&!r)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),r=!0,clearInterval(e),void(e=s(1e3));if("hasAccess"!==n&&r)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),r=!1,clearInterval(e),void(e=s(200));const a=JSON.stringify(d.current.context);d.current.update();const c=JSON.stringify(d.current.context),u=d.current.getCurrentStateName();u===t&&a===c||(p(u),t=u)}),n);return e=s(200),()=>clearInterval(e)}),[]);const O=e.useCallback((e=>e.replace("{nickname}",g||"unknown").replace("{token}",encodeURIComponent(l.accessToken||"unknown")).replace("{app}",C||"unknown")),[g,l.accessToken,C]),J=e.useCallback((e=>{d.current.updateContext({isAnonymous:e})}),[]),L=e.useCallback((()=>d.current.isBusy()),[]);return e.useMemo((()=>({audio:S,auth:l,currentStateName:m,stateMachine:d.current,service:f,context:h,state:m,nickname:g,name:A,error:k,errorType:v,fixAppUrl:O,setAnonymous:J,allStates:d.current.allStates,isBusy:L,voice:R,html:q,setHtml:j,script:w})),[m,g,A,k,v,q,w,l.isAuthenticated,l.isLoading,S.isRecording,R?.isConnected,O,J,L])};
@@ -1 +1 @@
1
- {"version":3,"file":"useTools.d.ts","sourceRoot":"","sources":["../../../src/hooks/useTools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,UAAU,EAAE,GAAG,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,SAAS,GAAG,cAAc,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzB,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC;AAED,QAAA,MAAM,QAAQ,QACP,eAAe,YACX,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,8BAG7B,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,qBAGhC,gBAAgB,SACf,MAAM,qBACK,MAAM,IAAI,gBAGd,WAAW,WA2mB1B,CAAC;AAEF,eAAe,QAAQ,CAAC"}
1
+ {"version":3,"file":"useTools.d.ts","sourceRoot":"","sources":["../../../src/hooks/useTools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,UAAU,EAAE,GAAG,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,SAAS,GAAG,cAAc,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzB,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC;AAED,QAAA,MAAM,QAAQ,QACP,eAAe,YACX,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,8BAG7B,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,qBAGhC,gBAAgB,SACf,MAAM,qBACK,MAAM,IAAI,gBAGd,WAAW,WAqoB1B,CAAC;AAEF,eAAe,QAAQ,CAAC"}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("../_virtual/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");var s=require("../utils/device.js");exports.default=(a,r=e=>{console.log(e)},i=e=>{console.log(e)},n,o,p=()=>{console.log("stopVoiceSession")},c)=>e.useMemo((()=>{const e=[],d=(t,s)=>{e.push({definition:t,handler:s})},l=async()=>{const e=t.getConfigValue("APP_CONFIG"),s=t.getConfigValue("APP_BUTTONS");return[...s&&e.apps[s]?e.apps[s].tasks:[],...await a.getAppTasks()]};d({name:"stop_voice_session",description:"Stops the voice session.",parameters:{type:"object",properties:{}}},(async()=>(console.log("TOOL: stop_voice_session"),r(void 0),p(),{ok:!0}))),d({name:"inject_script",description:"Injects a script into the html/canvas view.",parameters:{type:"object",properties:{script:{type:"string",description:"The script to inject"}},required:["script"]}},(async({script:e})=>(console.log("TOOL: inject_script",e),i(e),{ok:!0}))),d({name:"post_codicent_message",description:"Posts a message to Codicent, only when requested by the user.",parameters:{type:"object",properties:{content:{type:"string",description:'The codicent message text, e.g. "remember to call Linda"'},parent_id:{type:"string",description:'The parent message id of a previous message that you will add a new revision to, by setting parent_id to the origin message being "edited"'}},required:["content"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"update_codicent_message",description:"Posts an edited message, which replaces the old message.",parameters:{type:"object",properties:{content:{type:"string",description:'The updated codicent message text, e.g. "remember to call Johan", usually including the tags from the original message.'},parent_id:{type:"string",description:"The message id of a previous/old message to be updated."}},required:["content","parent_id"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"get_messages_list",description:"Gets messages tagged with given tag name, optionally limited by num_messages. The messages are listed in chronological order, latest first.",parameters:{type:"object",properties:{num_messages:{type:"integer",description:"The number of matching messages to return"},search_text:{type:"string",description:"Search text to filter messages by"},tag_name:{type:"string",description:"Name of tag to find messages by"},after_timestamp:{type:"string",description:"Only return messages after this timestamp"},before_timestamp:{type:"string",description:"Only return messages before this timestamp"}},required:["num_messages"]}},(async({num_messages:e,search_text:t,tag_name:s,after_timestamp:r,before_timestamp:i})=>{let n=await a.getMessages(s?[s]:[],void 0,e);t&&(n=n.filter((e=>e.content.includes(t)))),r&&(n=n.filter((e=>e.createdAt>r))),i&&(n=n.filter((e=>e.createdAt<i)));const o=n.slice(0,e);return console.log("get_messages_list result:",o),o})),d({name:"chat_with_codicent_ai",description:"Sends a message to Codicent AI and gets a response message back. Remember that you can always ask codicent via this tool to find out more about what you can achieve from chatting with the codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"Text of message to the codicent"}},required:["message"]}},(async({message:e})=>await a.chat(e))),d({name:"create_todo",description:"Saves a todo message in Codicent.",parameters:{type:"object",properties:{text:{type:"string",description:"Text of todo"}},required:["text"]}},(async({text:e})=>await a.sendMessage("#todo "+e))),d({name:"place_order",description:"Places and order with the Codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"The text message of the order as spoken by the user."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#do Jag kommer ge dig en text (nedan) på vad jag ska beställa. Använd bara den text du får av mig, inga tools.\n Du ska skapa en tabell med detaljerad information inklusive lagerstatus \n för varje artikel i beställningen. Svara först när du har all info på plats. Ställ inga frågor på vägen utan använd det du får av mig.\n \n ----\n EXEMPEL PÅ SVAR:\n ----\n Här är en tabell med detaljerad information inklusive lagerstatus för varje artikel i beställningen:\n \n Artikel\tHyresobjekt\tNamn\tLagertyp\tGrupp\tNamn.1\tSRA/SBEF\tLeverantör\tLevnr\tDepå\tLager\tReserverat\tUthyrt nu\tTillgängligt nu\tMärke/typ\tTillverkarnr\tTillv.år\tInköpsdato\tInköpspris\tVikt\n Elverk\t12345\tElverk 1\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör A\t001\tDepå 1\t5\t0\t1\t4\tHonda EU22i\t123456\t2020\t2020-01-01\t10000 SEK\t21 kg\n Elverk\t12345\tElverk 2\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör B\t002\tDepå 2\t3\t0\t1\t2\tYamaha EF2000iS\t654321\t2019\t2019-05-01\t9000 SEK\t20 kg\n Observera att denna tabell är baserad på den information som finns tillgänglig i lagerstatusen. Om du behöver ytterligare detaljer eller om något specifikt saknas, vänligen meddela mig.\n ----\n \n --- här följer texten på vad jag vill beställa ---\n \n \n ${e}`))),d({name:"remember_info",description:"Saves info in your internal memory for future use. Use this tool to save insights on how to perform our conversations and tasks related to them.",parameters:{type:"object",properties:{message:{type:"string",description:"Your insights to improve our future conversations."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#index #insights\n\n${e}`))),d({name:"save_to_crm",description:"Saves CRM related info to your memory (logbook).",parameters:{type:"object",properties:{message:{type:"string",description:"CRM log entry description/contents."},company:{type:"string",description:"Company name for CRM log entry."},contact:{type:"string",description:"Contact name for CRM log entry."}},required:["message","company"]}},(async({message:e,company:t,contact:s})=>await a.sendMessage(`#crm\n\nFöretag: ${t}\n\nInfo: ${e}${s?"\n\nKontakt: "+s:""}`))),d({name:"set_page_html",description:"Sets the innerHtml of the div covering the full app page. You can display any html/javascript/style/mermaid content here for the user to see ;-). This view is usually referred to as the canvas, or tavlan in Swedish.",parameters:{type:"object",properties:{html:{type:"string",description:"The inner html to set the page to."}},required:["html"]}},(async({html:e})=>(r(e),n.play(),{ok:!0}))),d({name:"hide_page_html",description:"Hides the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>(r(void 0),{ok:!0}))),d({name:"get_page_html",description:"Gets the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>({html:o}))),d({name:"get_tasks",description:"Gets the list of possible tasks that can be performed. This lists task names and their id:s. Use get_task to get the task instructions given a task id.",parameters:{type:"object",properties:{},required:[]}},(async e=>(await l()).map((e=>({id:e.id,name:e.title}))))),d({name:"get_task",description:"Gets the task instructions for a given task id. Use get_tasks to get a list of possible tasks (with their id:s).",parameters:{type:"object",properties:{task_id:{type:"string",description:"The task id to get instructions for."}},required:["task_id"]}},(async({task_id:e})=>{const t=(await l()).find((t=>t.id===e));return t?t.content:"Task not found"})),d({name:"get_gps_location",description:"Gets the current GPS location of the device. Returns latitude and longitude coordinates. Use this when the user asks about nearby places, directions, or anything location-dependent.",parameters:{type:"object",properties:{},required:[]}},(async e=>{try{const e=await s.getGpsLocation();return e?{ok:!0,latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy}:{ok:!1,error:"GPS not available"}}catch{return{ok:!1,error:"Failed to get GPS location"}}}));const{additionalTools:g=[],mergeStrategy:m="merge"}=c||{};return"replace"===m?g:"builtin-only"===m?e:[...e,...g]}),[a,r,i,o,n,c]);
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react"),t=require("../config/index.js");require("../utils/MessageContent.js"),require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("../_virtual/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");var s=require("../utils/device.js");exports.default=(a,r=e=>{console.log(e)},i=e=>{console.log(e)},n,o,c=()=>{console.log("stopVoiceSession")},p)=>e.useMemo((()=>{const e=[],d=(t,s)=>{e.push({definition:t,handler:s})},l=async()=>{const e=t.getConfigValue("APP_CONFIG"),s=t.getConfigValue("APP_BUTTONS");return[...s&&e.apps[s]?e.apps[s].tasks:[],...await a.getAppTasks()]};d({name:"stop_voice_session",description:"Stops the voice session.",parameters:{type:"object",properties:{}}},(async()=>(console.log("TOOL: stop_voice_session"),r(void 0),c(),{ok:!0}))),d({name:"inject_script",description:"Injects a script into the html/canvas view.",parameters:{type:"object",properties:{script:{type:"string",description:"The script to inject"}},required:["script"]}},(async({script:e})=>(console.log("TOOL: inject_script",e),i(e),{ok:!0}))),d({name:"post_codicent_message",description:"Posts a message to Codicent, only when requested by the user.",parameters:{type:"object",properties:{content:{type:"string",description:'The codicent message text, e.g. "remember to call Linda"'},parent_id:{type:"string",description:'The parent message id of a previous message that you will add a new revision to, by setting parent_id to the origin message being "edited"'}},required:["content"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"update_codicent_message",description:"Posts an edited message, which replaces the old message.",parameters:{type:"object",properties:{content:{type:"string",description:'The updated codicent message text, e.g. "remember to call Johan", usually including the tags from the original message.'},parent_id:{type:"string",description:"The message id of a previous/old message to be updated."}},required:["content","parent_id"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"get_messages_list",description:"Gets messages tagged with given tag name, optionally limited by num_messages. The messages are listed in chronological order, latest first.",parameters:{type:"object",properties:{num_messages:{type:"integer",description:"The number of matching messages to return"},search_text:{type:"string",description:"Search text to filter messages by"},tag_name:{type:"string",description:"Name of tag to find messages by"},after_timestamp:{type:"string",description:"Only return messages after this timestamp"},before_timestamp:{type:"string",description:"Only return messages before this timestamp"}},required:["num_messages"]}},(async({num_messages:e,search_text:t,tag_name:s,after_timestamp:r,before_timestamp:i})=>{let n=await a.getMessages(s?[s]:[],void 0,e);t&&(n=n.filter((e=>e.content.includes(t)))),r&&(n=n.filter((e=>e.createdAt>r))),i&&(n=n.filter((e=>e.createdAt<i)));const o=n.slice(0,e);return console.log("get_messages_list result:",o),o})),d({name:"chat_with_codicent_ai",description:"Sends a message to Codicent AI and gets a response message back. Remember that you can always ask codicent via this tool to find out more about what you can achieve from chatting with the codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"Text of message to the codicent"}},required:["message"]}},(async({message:e})=>await a.chat(e))),d({name:"create_todo",description:"Saves a todo message in Codicent.",parameters:{type:"object",properties:{text:{type:"string",description:"Text of todo"}},required:["text"]}},(async({text:e})=>await a.sendMessage("#todo "+e))),d({name:"place_order",description:"Places and order with the Codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"The text message of the order as spoken by the user."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#do Jag kommer ge dig en text (nedan) på vad jag ska beställa. Använd bara den text du får av mig, inga tools.\n Du ska skapa en tabell med detaljerad information inklusive lagerstatus \n för varje artikel i beställningen. Svara först när du har all info på plats. Ställ inga frågor på vägen utan använd det du får av mig.\n \n ----\n EXEMPEL PÅ SVAR:\n ----\n Här är en tabell med detaljerad information inklusive lagerstatus för varje artikel i beställningen:\n \n Artikel\tHyresobjekt\tNamn\tLagertyp\tGrupp\tNamn.1\tSRA/SBEF\tLeverantör\tLevnr\tDepå\tLager\tReserverat\tUthyrt nu\tTillgängligt nu\tMärke/typ\tTillverkarnr\tTillv.år\tInköpsdato\tInköpspris\tVikt\n Elverk\t12345\tElverk 1\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör A\t001\tDepå 1\t5\t0\t1\t4\tHonda EU22i\t123456\t2020\t2020-01-01\t10000 SEK\t21 kg\n Elverk\t12345\tElverk 2\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör B\t002\tDepå 2\t3\t0\t1\t2\tYamaha EF2000iS\t654321\t2019\t2019-05-01\t9000 SEK\t20 kg\n Observera att denna tabell är baserad på den information som finns tillgänglig i lagerstatusen. Om du behöver ytterligare detaljer eller om något specifikt saknas, vänligen meddela mig.\n ----\n \n --- här följer texten på vad jag vill beställa ---\n \n \n ${e}`))),d({name:"remember_info",description:"Saves info in your internal memory for future use. Use this tool to save insights on how to perform our conversations and tasks related to them.",parameters:{type:"object",properties:{message:{type:"string",description:"Your insights to improve our future conversations."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#index #insights\n\n${e}`))),d({name:"save_to_crm",description:"Saves CRM related info to your memory (logbook).",parameters:{type:"object",properties:{message:{type:"string",description:"CRM log entry description/contents."},company:{type:"string",description:"Company name for CRM log entry."},contact:{type:"string",description:"Contact name for CRM log entry."}},required:["message","company"]}},(async({message:e,company:t,contact:s})=>await a.sendMessage(`#crm\n\nFöretag: ${t}\n\nInfo: ${e}${s?"\n\nKontakt: "+s:""}`))),d({name:"set_page_html",description:"Sets the innerHtml of the div covering the full app page. You can display any html/javascript/style/mermaid content here for the user to see ;-). This view is usually referred to as the canvas, or tavlan in Swedish.",parameters:{type:"object",properties:{html:{type:"string",description:"The inner html to set the page to."}},required:["html"]}},(async({html:e})=>(r(e),n.play(),{ok:!0}))),d({name:"hide_page_html",description:"Hides the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>(r(void 0),{ok:!0}))),d({name:"get_page_html",description:"Gets the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>({html:o}))),d({name:"get_tasks",description:"Gets the list of possible tasks that can be performed. This lists task names and their id:s. Use get_task to get the task instructions given a task id.",parameters:{type:"object",properties:{},required:[]}},(async e=>(await l()).map((e=>({id:e.id,name:e.title}))))),d({name:"get_task",description:"Gets the task instructions for a given task id. Use get_tasks to get a list of possible tasks (with their id:s).",parameters:{type:"object",properties:{task_id:{type:"string",description:"The task id to get instructions for."}},required:["task_id"]}},(async({task_id:e})=>{const t=(await l()).find((t=>t.id===e));return t?t.content:"Task not found"})),d({name:"get_chat_conversation",description:"Gets a chat conversation (message thread) by message ID. Returns all messages in the conversation thread in chronological order.",parameters:{type:"object",properties:{message_id:{type:"string",description:"The ID of any message in the conversation to retrieve the full thread."}},required:["message_id"]}},(async({message_id:e})=>{try{return{ok:!0,messages:await a.getChatHistory(e)}}catch(e){return{ok:!1,error:e.message||"Failed to get chat conversation"}}})),d({name:"get_gps_location",description:"Gets the current GPS location of the device. Returns latitude and longitude coordinates. Use this when the user asks about nearby places, directions, or anything location-dependent.",parameters:{type:"object",properties:{},required:[]}},(async e=>{try{const e=await s.getGpsLocation();return e?{ok:!0,latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy}:{ok:!1,error:"GPS not available"}}catch{return{ok:!1,error:"Failed to get GPS location"}}}));const{additionalTools:g=[],mergeStrategy:m="merge"}=p||{};return"replace"===m?g:"builtin-only"===m?e:[...e,...g]}),[a,r,i,o,n,p]);
@@ -98,6 +98,8 @@ export declare class CodicentService {
98
98
  getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
99
99
  registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
100
100
  loginUser: (userId: string, accessToken: string) => Promise<string | null>;
101
+ loginMicrosoftUser: (userId: string, idToken: string) => Promise<string | null>;
102
+ registerMicrosoftUser: (nickname: string, email: string, userId: string, idToken: string) => Promise<string>;
101
103
  nicknameExists: (nickname: string) => Promise<boolean>;
102
104
  logout: () => void;
103
105
  isRegistered: () => boolean;
@@ -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,E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EF,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,CA0B7B;CACH"}
@@ -1 +1 @@
1
- "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},i=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=(await t.json()).filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))));return e}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async t=>{const o=await e.loadStripe(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(t),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=t,s(t.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}t=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async e=>{fetch(t.getFileUrl(e.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((t=>{const o=window.URL.createObjectURL(t),a=document.createElement("a");a.style.display="none",a.href=o,a.download=e.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{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(),s=o.content??o.content??"";return{content:s.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}catch(t){return void console.error("Error polling AI chat status:",t)}console.error("Polling timeout reached for AI chat")},c.getTranslations=async(t,e,o="codicent-mini")=>{const s=await fetch(`${a}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${n}`},body:JSON.stringify({project:o,text:t,targetLanguage:e})});if(!s.ok)throw s.status,new Error(`Failed to get translations: ${s.statusText}`);return await s.json()},exports.CodicentService=c,exports.setBaseUrl=s;
1
+ "use strict";var t,e=require("../node_modules/@stripe/stripe-js/dist/index.js"),o=require("../utils/MessageContent.js");require("../node_modules/tinycolor2/esm/tinycolor.js"),require("react/jsx-runtime"),require("react"),require("../_virtual/index.js"),require("../config/index.js"),require("../utils/cacheManager.js"),require("../lib/wavtools/lib/wav_packer.js"),require("../lib/wavtools/lib/analysis/audio_analysis.js"),require("../lib/wavtools/lib/wav_stream_player.js"),require("../lib/wavtools/lib/wav_recorder.js");let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},i=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(t){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const e=new o.default(t.content).content.split("\n"),a=e[0],n=e.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:i,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.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginMicrosoftUser`,{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 Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterMicrosoftUser`,{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"";return await s.text()},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,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{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(),s=o.content??o.content??"";return{content:s.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}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")=>{if(!n||"-"===n)return{translation:t};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,5 +1,5 @@
1
1
  export { default as useStateWithLocalStorage } from "./useStateWithLocalStorage";
2
- export { default as useAuthState, type UseAuthState } from "./useAuthState";
2
+ export { default as useAuthState, type UseAuthState, type AuthStateOptions } from "./useAuthState";
3
3
  export * from "./useChat";
4
4
  export { default as useCodicentState } from "./useCodicentState";
5
5
  export * from "./useAudioRecorder";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,IAAI,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC5E,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACjE,cAAc,oBAAoB,CAAC;AAEnC,O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EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AACrE,cAAc,sBAAsB,CAAC;AACrC,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAC/D,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,YAAY,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,cAAc,CAAC;AACrD,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAC3E,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC"}
@@ -14,6 +14,12 @@ export interface UseAuthState {
14
14
  loginWithRedirect: (options?: RedirectLoginOptions<AppState>) => Promise<void>;
15
15
  loginPasswordless: (email: string) => Promise<void>;
16
16
  }
17
- declare const useAuthState: (auth0: Auth0ContextInterface) => UseAuthState;
17
+ export interface AuthStateOptions {
18
+ /** Override the backend login call. Defaults to Auth0-based LoginAuth0User endpoint. */
19
+ loginFn?: (service: CodicentService, userId: string, accessToken: string) => Promise<string | null | "">;
20
+ /** Override the backend register call. Defaults to Auth0-based RegisterAuth0User endpoint. */
21
+ registerFn?: (service: CodicentService, nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
22
+ }
23
+ declare const useAuthState: (auth0: Auth0ContextInterface, options?: AuthStateOptions) => UseAuthState;
18
24
  export default useAuthState;
19
25
  //# sourceMappingURL=useAuthState.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"useAuthState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAuthState.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC;AAUrC,MAAM,WAAW,YAAY;IAC3B,eAAe,EAAE,OAAO,CAAC;IACzB,YAAY,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IAInB,IAAI,EAAE,GAAG,CAAC;IACV,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/E,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACrD;AAED,QAAA,MAAM,YAAY,UAAW,qBAAqB,KAAG,YAqRpD,CAAC;AAEF,eAAe,YAAY,CAAC"}
1
+ {"version":3,"file":"useAuthState.d.ts","sourceRoot":"","sources":["../../../src/hooks/useAuthState.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,QAAQ,EAAqB,MAAM,oBAAoB,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAC;AAUrC,MAAM,WAAW,YAAY;IAC3B,eAAe,EAAE,OAAO,CAAC;IACzB,YAAY,EAAE,OAAO,GAAG,SAAS,CAAC;IAClC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,OAAO,CAAC;IAInB,IAAI,EAAE,GAAG,CAAC;IACV,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,YAAY,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IACpD,eAAe,EAAE,eAAe,CAAC;IACjC,iBAAiB,EAAE,CAAC,OAAO,CAAC,EAAE,oBAAoB,CAAC,QAAQ,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/E,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACrD;AAED,MAAM,WAAW,gBAAgB;IAC/B,wFAAwF;IACxF,OAAO,CAAC,EAAE,CAAC,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,GAAG,EAAE,CAAC,CAAC;IACzG,8FAA8F;IAC9F,UAAU,CAAC,EAAE,CACX,OAAO,EAAE,eAAe,EACxB,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,KAChB,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB;AAED,QAAA,MAAM,YAAY,UAAW,qBAAqB,YAAY,gBAAgB,KAAG,YAyRhF,CAAC;AAEF,eAAe,YAAY,CAAC"}
@@ -1 +1 @@
1
- import{useState as o,useMemo as e,useEffect as t,useCallback as s}from"react";import{CodicentService as n}from"../services/codicent.js";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"react/jsx-runtime";import"@fluentui/react-components";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import{getConfigValue as i}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./useLocalization.js";import"./useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/Page.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";const r=r=>{const{isAuthenticated:p,getAccessTokenSilently:a,user:m,isLoading:c,logout:l,getAccessTokenWithPopup:g,loginWithRedirect:u,loginWithPopup:j}=r,[E,P]=o(null),[d,_]=o(void 0),[T,C]=o(null),[S,A]=o(""),I=e((()=>new n({API_BASE_URL:i("API_BASE_URL"),APP_LOG_CODICENT:i("APP_LOG_CODICENT"),APP_LOG_TOKEN:i("APP_LOG_TOKEN"),APP_NAME:i("APP_NAME"),APP_PREFIX:i("APP_PREFIX"),APP_TEMPLATE:i("APP_TEMPLATE"),BUTTON_TAG:i("BUTTON_TAG"),STRIPE_PUBLIC_KEY:i("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:i("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:i("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:i("SUBSCRIPTION_NEEDED"),USER_PREFIX:i("USER_PREFIX"),ANONYMOUS_TOKEN:i("ANONYMOUS_TOKEN")})),[]);t((()=>{!c&&p&&(async()=>{try{const o=await a({});console.debug("CODICENT: ACCESS TOKEN",o),P(o)}catch(o){console.debug("CODICENT: Failed to get access token",o);const e=o;if(e&&"object"==typeof e&&"error"in e&&"login_required"===e.error)console.warn("CODICENT: Login required"),O();else if(e&&"object"==typeof e&&"error"in e&&"consent_required"===e.error)try{const o=await g();if(!o)return void C("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),P(o)}catch(o){console.warn("CODICENT: Failed to get access token with popup",o),O()}else C("Failed to get access token: "+(e.message?.toString()||e.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",e)}})().then((()=>{}))}),[p,g,a,u,c]),t((()=>{if(m&&m.sub&&E&&void 0===d){let o=!0;return I.loginUser(m.sub,E).then((e=>{o&&(null===e?_(!1):""===e?C("Kontrollera internetanslutningen och försök igen."):(I.setToken(E),I.getNickname().then(A),_(!0)))})).catch((()=>{o&&(C("Ett fel uppstod. Försök igen senare."),_(!1))})),()=>{o=!1}}}),[m,E,d,I]);const O=s((()=>{I.logout(),P(null),C(null),_(void 0),A(""),l({logoutParams:{returnTo:i("AUTH_REDIRECT_URL")}})}),[I,l]),h=s((async o=>{const e=await I.registerUser(o,m.email,m.sub,E);return e&&(I.setToken(E),_(!0)),e}),[I,m,E]);t((()=>{I.onUnauthorized=O}),[I]);const R=s((async o=>{try{await j({authorizationParams:{connection:"email",login_hint:o}})}catch(o){console.error("Passwordless login failed:",o),C(`Passwordless login failed: ${o}`)}}),[j]);return e((()=>({isAuthenticated:p,isRegistered:d,accessToken:E,authError:T,isLoading:c,user:m,nickname:S,logout:O,registerUser:h,codicentService:I,loginWithRedirect:u,loginPasswordless:R})),[p,d,E,T,c,m,S,O,h,I,u,R])};export{r as default};
1
+ import{useState as o,useMemo as e,useEffect as t,useCallback as s}from"react";import{CodicentService as n}from"../services/codicent.js";import"../components/Markdown.js";import"../components/Textarea.js";import"../components/Button.js";import"../components/CompoundButton.js";import"react/jsx-runtime";import"@fluentui/react-components";import"../components/Spinner.js";import"../components/TextHeader.js";import"../components/TypingIndicator.js";import"../components/Dialog.js";import"../components/ChatInput.js";import"../components/CombinedPlaceholderDialog.js";import"../components/ChatMessage.js";import"../components/Header.js";import"@fluentui/react-icons";import{getConfigValue as i}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"./useLocalization.js";import"./useAppStyles.js";import"../components/FileThumbnail.js";import"../components/MessageInput.js";import"../components/UploadFile.js";import"../components/SnapFooter.js";import"../components/Profile.js";import"../components/MessageItem.js";import"../components/Content.js";import"../components/AiInput.js";import"../components/SearchBox.js";import"../components/HtmlView.js";import"../components/Footer.js";import"../components/Page.js";import"../components/QrCodeDialog.js";import"../components/QrScanner.js";import"../components/OfflineMessage.js";import"../components/LanguageSelector.js";import"../components/ListView.js";import"../components/RecordModal.js";import"../components/BulkUploadDialog.js";import"../components/CookieBanner.js";import"../pages/AppFrame.js";import"../pages/Chat.js";import"../pages/Compose.js";import"../pages/Snap.js";import"../pages/Search.js";import"../pages/Login.js";import"../pages/CrmPage.js";import"../pages/CrmPagePersistent.js";import"../pages/ImageView.js";import"../pages/FormInvite.js";import"../pages/FormAccept.js";import"../pages/Sales.js";import"../pages/Purchase.js";import"../pages/QrScan.js";import"react-dom/client";import"react-router-dom";import"../node_modules/@auth0/auth0-react/dist/auth0-react.esm.js";const r=(r,p)=>{const{isAuthenticated:a,getAccessTokenSilently:m,user:c,isLoading:l,logout:g,getAccessTokenWithPopup:u,loginWithRedirect:j,loginWithPopup:E}=r,[P,d]=o(null),[_,T]=o(void 0),[C,S]=o(null),[A,I]=o(""),O=e((()=>new n({API_BASE_URL:i("API_BASE_URL"),APP_LOG_CODICENT:i("APP_LOG_CODICENT"),APP_LOG_TOKEN:i("APP_LOG_TOKEN"),APP_NAME:i("APP_NAME"),APP_PREFIX:i("APP_PREFIX"),APP_TEMPLATE:i("APP_TEMPLATE"),BUTTON_TAG:i("BUTTON_TAG"),STRIPE_PUBLIC_KEY:i("STRIPE_PUBLIC_KEY"),STRIPE_SOURCE:i("STRIPE_SOURCE"),STRIPE_TRIAL_PERIOD_DAYS:i("STRIPE_TRIAL_PERIOD_DAYS"),SUBSCRIPTION_NEEDED:i("SUBSCRIPTION_NEEDED"),USER_PREFIX:i("USER_PREFIX"),ANONYMOUS_TOKEN:i("ANONYMOUS_TOKEN")})),[]);t((()=>{!l&&a&&(async()=>{try{const o=await m({});console.debug("CODICENT: ACCESS TOKEN",o),d(o)}catch(o){console.debug("CODICENT: Failed to get access token",o);const e=o;if(e&&"object"==typeof e&&"error"in e&&"login_required"===e.error)console.warn("CODICENT: Login required"),h();else if(e&&"object"==typeof e&&"error"in e&&"consent_required"===e.error)try{const o=await u();if(!o)return void S("Failed to get access token: no token from auth0 with popup");console.log("CODICENT: GOT ACCESS TOKEN"),d(o)}catch(o){console.warn("CODICENT: Failed to get access token with popup",o),h()}else S("Failed to get access token: "+(e.message?.toString()||e.toString())),console.log("CODICENT: ACCESS TOKEN ERROR",e)}})().then((()=>{}))}),[a,u,m,j,l]),t((()=>{if(c&&c.sub&&P&&void 0===_){let o=!0;return(p?.loginFn?p.loginFn(O,c.sub,P):O.loginUser(c.sub,P)).then((e=>{o&&(null===e?T(!1):""===e?S("Kontrollera internetanslutningen och försök igen."):(O.setToken(e),O.getNickname().then(I),T(!0)))})).catch((()=>{o&&(S("Ett fel uppstod. Försök igen senare."),T(!1))})),()=>{o=!1}}}),[c,P,_,O]);const h=s((()=>{O.logout(),d(null),S(null),T(void 0),I(""),g({logoutParams:{returnTo:i("AUTH_REDIRECT_URL")}})}),[O,g]),R=s((async o=>{const e=p?.registerFn?await p.registerFn(O,o,c.email,c.sub,P):await O.registerUser(o,c.email,c.sub,P);return e&&(O.setToken(e),T(!0)),e}),[O,c,P]);t((()=>{O.onUnauthorized=h}),[O]);const N=s((async o=>{try{await E({authorizationParams:{connection:"email",login_hint:o}})}catch(o){console.error("Passwordless login failed:",o),S(`Passwordless login failed: ${o}`)}}),[E]);return e((()=>({isAuthenticated:a,isRegistered:_,accessToken:P,authError:C,isLoading:l,user:c,nickname:A,logout:h,registerUser:R,codicentService:O,loginWithRedirect:j,loginPasswordless:N})),[a,_,P,C,l,c,A,h,R,O,j,N])};export{r as default};
@@ -2,7 +2,7 @@ import { Auth0ContextInterface } from "@auth0/auth0-react";
2
2
  import { CodicentService } from "../services";
3
3
  import { AppStateMachine, StateContext, AppStateDefinition } from "../utils";
4
4
  import { AudioRecorderState } from "./useAudioRecorder";
5
- import { UseAuthState } from "./useAuthState";
5
+ import { AuthStateOptions, UseAuthState } from "./useAuthState";
6
6
  import { RealtimeVoice } from "./useRealtimeVoiceAI";
7
7
  import { ToolsConfig } from "./useTools";
8
8
  export interface CodicentAppState {
@@ -29,6 +29,7 @@ export interface CodicentAppState {
29
29
  export interface UseCodicentAppOptions {
30
30
  auth0: Auth0ContextInterface;
31
31
  toolsConfig?: ToolsConfig;
32
+ authOptions?: AuthStateOptions;
32
33
  }
33
- export declare const useCodicentApp: ({ auth0, toolsConfig }: UseCodicentAppOptions) => CodicentAppState;
34
+ export declare const useCodicentApp: ({ auth0, toolsConfig, authOptions }: UseCodicentAppOptions) => CodicentAppState;
34
35
  //# sourceMappingURL=useCodicentApp.d.ts.map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,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,qBAAqB,CAAC;IAC7B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,WAAW,CAAC,EAAE,gBAAgB,CAAC;CAChC;AAED,eAAO,MAAM,cAAc,wCAAyC,qBAAqB,KAgLlF,gBACN,CAAC"}
@@ -1 +1 @@
1
- import{useRef as e,useState as t,useCallback as n,useMemo as r,useEffect as s}from"react";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import{createAppStateMachine as o}from"../utils/appState.js";import"../_virtual/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../utils/cacheManager.js";import{useAudioRecorder as i}from"./useAudioRecorder.js";import c from"./useAuthState.js";import a from"./useRealtimeVoiceAI.js";import u from"./useTools.js";import{getConfigValue as l}from"../config/index.js";const m=({auth0:m,toolsConfig:p})=>{const d=c(m),h=e(o(d.codicentService,(()=>{}))),[g,A]=t(),{service:f,context:v}=h.current,{nickname:k,name:j,error:w,errorType:y,selectedApp:b}=v,x=n(((e,t)=>{const n=e.get("file").name;f.uploadFile(n,e).then((e=>{f.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[f]),C=i(x),[S,T]=t(),[_,I]=t(),[N,R]=t(!1),M=r((()=>new Audio("./notification.mp3")),[]),E=n((()=>R(!0)),[]),O=u(f,T,I,M,S,E,p),J=r((()=>l("REALTIME_VOICE_API_KEY")||""),[]),L=a(f,J,O);s((()=>{N&&(L?.disconnectConversation(),R(!1))}),[N,L]),s((()=>{d.isAuthenticated&&d.user&&d.accessToken&&h.current.updateContext({isAuthenticated:d.isAuthenticated,user:{sub:d.user.sub,email:d.user.email},accessToken:d.accessToken})}),[d.isAuthenticated,d.user,d.accessToken]);const B=e(d.isAuthenticated);s((()=>{const e=!0===B.current,t=!0===d.isAuthenticated;e&&!t&&h.current.logout(),B.current=d.isAuthenticated}),[d.isAuthenticated]),s((()=>h.current.updateContext({nickname:d.nickname})),[d.nickname]),s((()=>{h.current.update();let e,t=h.current.getCurrentStateName();A(h.current.getCurrentStateName()),JSON.stringify(h.current.context);let n=!1;const r=s=>setInterval((()=>{const s=h.current.getCurrentStateName();if("hasAccess"===s&&!n)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),n=!0,clearInterval(e),void(e=r(1e3));if("hasAccess"!==s&&n)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),n=!1,clearInterval(e),void(e=r(200));const o=JSON.stringify(h.current.context);h.current.update();const i=JSON.stringify(h.current.context),c=h.current.getCurrentStateName();c===t&&o===i||(A(c),t=c)}),s);return e=r(200),()=>clearInterval(e)}),[]);const U=n((e=>e.replace("{nickname}",k||"unknown").replace("{token}",encodeURIComponent(d.accessToken||"unknown")).replace("{app}",b||"unknown")),[k,d.accessToken,b]),V=n((e=>{h.current.updateContext({isAnonymous:e})}),[]),$=n((()=>h.current.isBusy()),[]);return r((()=>({audio:C,auth:d,currentStateName:g,stateMachine:h.current,service:f,context:v,state:g,nickname:k,name:j,error:w,errorType:y,fixAppUrl:U,setAnonymous:V,allStates:h.current.allStates,isBusy:$,voice:L,html:S,setHtml:T,script:_})),[g,k,j,w,y,S,_,d.isAuthenticated,d.isLoading,C.isRecording,L?.isConnected,U,V,$])};export{m as useCodicentApp};
1
+ import{useRef as e,useState as t,useCallback as n,useMemo as r,useEffect as s}from"react";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import{createAppStateMachine as o}from"../utils/appState.js";import"../_virtual/index.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import"../utils/cacheManager.js";import{useAudioRecorder as i}from"./useAudioRecorder.js";import c from"./useAuthState.js";import a from"./useRealtimeVoiceAI.js";import u from"./useTools.js";import{getConfigValue as l}from"../config/index.js";const m=({auth0:m,toolsConfig:p,authOptions:d})=>{const h=c(m,d),g=e(o(h.codicentService,(()=>{}))),[A,f]=t(),{service:v,context:k}=g.current,{nickname:j,name:w,error:y,errorType:b,selectedApp:x}=k,C=n(((e,t)=>{const n=e.get("file").name;v.uploadFile(n,e).then((e=>{v.sendMessage(`#transcribe ${""!==t?(t.startsWith("#")?"":"#")+t+" ":""}#file:${e}`).then((()=>{})).catch(console.warn)}))}),[v]),S=i(C),[T,_]=t(),[I,N]=t(),[R,M]=t(!1),O=r((()=>new Audio("./notification.mp3")),[]),E=n((()=>M(!0)),[]),J=u(v,_,N,O,T,E,p),L=r((()=>l("REALTIME_VOICE_API_KEY")||""),[]),B=a(v,L,J);s((()=>{R&&(B?.disconnectConversation(),M(!1))}),[R,B]),s((()=>{h.isAuthenticated&&h.user&&h.accessToken&&g.current.updateContext({isAuthenticated:h.isAuthenticated,user:{sub:h.user.sub,email:h.user.email},accessToken:h.accessToken})}),[h.isAuthenticated,h.user,h.accessToken]);const U=e(h.isAuthenticated);s((()=>{const e=!0===U.current,t=!0===h.isAuthenticated;e&&!t&&g.current.logout(),U.current=h.isAuthenticated}),[h.isAuthenticated]),s((()=>g.current.updateContext({nickname:h.nickname})),[h.nickname]),s((()=>{g.current.update();let e,t=g.current.getCurrentStateName();f(g.current.getCurrentStateName()),JSON.stringify(g.current.context);let n=!1;const r=s=>setInterval((()=>{const s=g.current.getCurrentStateName();if("hasAccess"===s&&!n)return console.log("🎯 Reached stable state - switching to slower polling (1000ms)"),n=!0,clearInterval(e),void(e=r(1e3));if("hasAccess"!==s&&n)return console.log("🚨 Left stable state - switching to fast polling (200ms)"),n=!1,clearInterval(e),void(e=r(200));const o=JSON.stringify(g.current.context);g.current.update();const i=JSON.stringify(g.current.context),c=g.current.getCurrentStateName();c===t&&o===i||(f(c),t=c)}),s);return e=r(200),()=>clearInterval(e)}),[]);const V=n((e=>e.replace("{nickname}",j||"unknown").replace("{token}",encodeURIComponent(h.accessToken||"unknown")).replace("{app}",x||"unknown")),[j,h.accessToken,x]),$=n((e=>{g.current.updateContext({isAnonymous:e})}),[]),F=n((()=>g.current.isBusy()),[]);return r((()=>({audio:S,auth:h,currentStateName:A,stateMachine:g.current,service:v,context:k,state:A,nickname:j,name:w,error:y,errorType:b,fixAppUrl:V,setAnonymous:$,allStates:g.current.allStates,isBusy:F,voice:B,html:T,setHtml:_,script:I})),[A,j,w,y,b,T,I,h.isAuthenticated,h.isLoading,S.isRecording,B?.isConnected,V,$,F])};export{m as useCodicentApp};
@@ -1 +1 @@
1
- {"version":3,"file":"useTools.d.ts","sourceRoot":"","sources":["../../../src/hooks/useTools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,UAAU,EAAE,GAAG,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,SAAS,GAAG,cAAc,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzB,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC;AAED,QAAA,MAAM,QAAQ,QACP,eAAe,YACX,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,8BAG7B,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,qBAGhC,gBAAgB,SACf,MAAM,qBACK,MAAM,IAAI,gBAGd,WAAW,WA2mB1B,CAAC;AAEF,eAAe,QAAQ,CAAC"}
1
+ {"version":3,"file":"useTools.d.ts","sourceRoot":"","sources":["../../../src/hooks/useTools.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;GAEG;AACH,MAAM,WAAW,IAAI;IACnB,UAAU,EAAE,GAAG,CAAC;IAChB,OAAO,EAAE,GAAG,CAAC;CACd;AAED;;;;;GAKG;AACH,MAAM,MAAM,iBAAiB,GAAG,OAAO,GAAG,SAAS,GAAG,cAAc,CAAC;AAErE;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzB,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC;AAED,QAAA,MAAM,QAAQ,QACP,eAAe,YACX,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,8BAG7B,CAAC,MAAM,EAAE,MAAM,KAAK,IAAI,qBAGhC,gBAAgB,SACf,MAAM,qBACK,MAAM,IAAI,gBAGd,WAAW,WAqoB1B,CAAC;AAEF,eAAe,QAAQ,CAAC"}
@@ -1 +1 @@
1
- import{useMemo as e}from"react";import{getConfigValue as t}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import{getGpsLocation as s}from"../utils/device.js";const a=(a,r=e=>{console.log(e)},i=e=>{console.log(e)},n,o,p=()=>{console.log("stopVoiceSession")},c)=>e((()=>{const e=[],d=(t,s)=>{e.push({definition:t,handler:s})},l=async()=>{const e=t("APP_CONFIG"),s=t("APP_BUTTONS");return[...s&&e.apps[s]?e.apps[s].tasks:[],...await a.getAppTasks()]};d({name:"stop_voice_session",description:"Stops the voice session.",parameters:{type:"object",properties:{}}},(async()=>(console.log("TOOL: stop_voice_session"),r(void 0),p(),{ok:!0}))),d({name:"inject_script",description:"Injects a script into the html/canvas view.",parameters:{type:"object",properties:{script:{type:"string",description:"The script to inject"}},required:["script"]}},(async({script:e})=>(console.log("TOOL: inject_script",e),i(e),{ok:!0}))),d({name:"post_codicent_message",description:"Posts a message to Codicent, only when requested by the user.",parameters:{type:"object",properties:{content:{type:"string",description:'The codicent message text, e.g. "remember to call Linda"'},parent_id:{type:"string",description:'The parent message id of a previous message that you will add a new revision to, by setting parent_id to the origin message being "edited"'}},required:["content"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"update_codicent_message",description:"Posts an edited message, which replaces the old message.",parameters:{type:"object",properties:{content:{type:"string",description:'The updated codicent message text, e.g. "remember to call Johan", usually including the tags from the original message.'},parent_id:{type:"string",description:"The message id of a previous/old message to be updated."}},required:["content","parent_id"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"get_messages_list",description:"Gets messages tagged with given tag name, optionally limited by num_messages. The messages are listed in chronological order, latest first.",parameters:{type:"object",properties:{num_messages:{type:"integer",description:"The number of matching messages to return"},search_text:{type:"string",description:"Search text to filter messages by"},tag_name:{type:"string",description:"Name of tag to find messages by"},after_timestamp:{type:"string",description:"Only return messages after this timestamp"},before_timestamp:{type:"string",description:"Only return messages before this timestamp"}},required:["num_messages"]}},(async({num_messages:e,search_text:t,tag_name:s,after_timestamp:r,before_timestamp:i})=>{let n=await a.getMessages(s?[s]:[],void 0,e);t&&(n=n.filter((e=>e.content.includes(t)))),r&&(n=n.filter((e=>e.createdAt>r))),i&&(n=n.filter((e=>e.createdAt<i)));const o=n.slice(0,e);return console.log("get_messages_list result:",o),o})),d({name:"chat_with_codicent_ai",description:"Sends a message to Codicent AI and gets a response message back. Remember that you can always ask codicent via this tool to find out more about what you can achieve from chatting with the codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"Text of message to the codicent"}},required:["message"]}},(async({message:e})=>await a.chat(e))),d({name:"create_todo",description:"Saves a todo message in Codicent.",parameters:{type:"object",properties:{text:{type:"string",description:"Text of todo"}},required:["text"]}},(async({text:e})=>await a.sendMessage("#todo "+e))),d({name:"place_order",description:"Places and order with the Codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"The text message of the order as spoken by the user."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#do Jag kommer ge dig en text (nedan) på vad jag ska beställa. Använd bara den text du får av mig, inga tools.\n Du ska skapa en tabell med detaljerad information inklusive lagerstatus \n för varje artikel i beställningen. Svara först när du har all info på plats. Ställ inga frågor på vägen utan använd det du får av mig.\n \n ----\n EXEMPEL PÅ SVAR:\n ----\n Här är en tabell med detaljerad information inklusive lagerstatus för varje artikel i beställningen:\n \n Artikel\tHyresobjekt\tNamn\tLagertyp\tGrupp\tNamn.1\tSRA/SBEF\tLeverantör\tLevnr\tDepå\tLager\tReserverat\tUthyrt nu\tTillgängligt nu\tMärke/typ\tTillverkarnr\tTillv.år\tInköpsdato\tInköpspris\tVikt\n Elverk\t12345\tElverk 1\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör A\t001\tDepå 1\t5\t0\t1\t4\tHonda EU22i\t123456\t2020\t2020-01-01\t10000 SEK\t21 kg\n Elverk\t12345\tElverk 2\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör B\t002\tDepå 2\t3\t0\t1\t2\tYamaha EF2000iS\t654321\t2019\t2019-05-01\t9000 SEK\t20 kg\n Observera att denna tabell är baserad på den information som finns tillgänglig i lagerstatusen. Om du behöver ytterligare detaljer eller om något specifikt saknas, vänligen meddela mig.\n ----\n \n --- här följer texten på vad jag vill beställa ---\n \n \n ${e}`))),d({name:"remember_info",description:"Saves info in your internal memory for future use. Use this tool to save insights on how to perform our conversations and tasks related to them.",parameters:{type:"object",properties:{message:{type:"string",description:"Your insights to improve our future conversations."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#index #insights\n\n${e}`))),d({name:"save_to_crm",description:"Saves CRM related info to your memory (logbook).",parameters:{type:"object",properties:{message:{type:"string",description:"CRM log entry description/contents."},company:{type:"string",description:"Company name for CRM log entry."},contact:{type:"string",description:"Contact name for CRM log entry."}},required:["message","company"]}},(async({message:e,company:t,contact:s})=>await a.sendMessage(`#crm\n\nFöretag: ${t}\n\nInfo: ${e}${s?"\n\nKontakt: "+s:""}`))),d({name:"set_page_html",description:"Sets the innerHtml of the div covering the full app page. You can display any html/javascript/style/mermaid content here for the user to see ;-). This view is usually referred to as the canvas, or tavlan in Swedish.",parameters:{type:"object",properties:{html:{type:"string",description:"The inner html to set the page to."}},required:["html"]}},(async({html:e})=>(r(e),n.play(),{ok:!0}))),d({name:"hide_page_html",description:"Hides the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>(r(void 0),{ok:!0}))),d({name:"get_page_html",description:"Gets the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>({html:o}))),d({name:"get_tasks",description:"Gets the list of possible tasks that can be performed. This lists task names and their id:s. Use get_task to get the task instructions given a task id.",parameters:{type:"object",properties:{},required:[]}},(async e=>(await l()).map((e=>({id:e.id,name:e.title}))))),d({name:"get_task",description:"Gets the task instructions for a given task id. Use get_tasks to get a list of possible tasks (with their id:s).",parameters:{type:"object",properties:{task_id:{type:"string",description:"The task id to get instructions for."}},required:["task_id"]}},(async({task_id:e})=>{const t=(await l()).find((t=>t.id===e));return t?t.content:"Task not found"})),d({name:"get_gps_location",description:"Gets the current GPS location of the device. Returns latitude and longitude coordinates. Use this when the user asks about nearby places, directions, or anything location-dependent.",parameters:{type:"object",properties:{},required:[]}},(async e=>{try{const e=await s();return e?{ok:!0,latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy}:{ok:!1,error:"GPS not available"}}catch{return{ok:!1,error:"Failed to get GPS location"}}}));const{additionalTools:m=[],mergeStrategy:g="merge"}=c||{};return"replace"===g?m:"builtin-only"===g?e:[...e,...m]}),[a,r,i,o,n,c]);export{a as default};
1
+ import{useMemo as e}from"react";import{getConfigValue as t}from"../config/index.js";import"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"../_virtual/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";import{getGpsLocation as s}from"../utils/device.js";const a=(a,r=e=>{console.log(e)},i=e=>{console.log(e)},n,o,p=()=>{console.log("stopVoiceSession")},c)=>e((()=>{const e=[],d=(t,s)=>{e.push({definition:t,handler:s})},m=async()=>{const e=t("APP_CONFIG"),s=t("APP_BUTTONS");return[...s&&e.apps[s]?e.apps[s].tasks:[],...await a.getAppTasks()]};d({name:"stop_voice_session",description:"Stops the voice session.",parameters:{type:"object",properties:{}}},(async()=>(console.log("TOOL: stop_voice_session"),r(void 0),p(),{ok:!0}))),d({name:"inject_script",description:"Injects a script into the html/canvas view.",parameters:{type:"object",properties:{script:{type:"string",description:"The script to inject"}},required:["script"]}},(async({script:e})=>(console.log("TOOL: inject_script",e),i(e),{ok:!0}))),d({name:"post_codicent_message",description:"Posts a message to Codicent, only when requested by the user.",parameters:{type:"object",properties:{content:{type:"string",description:'The codicent message text, e.g. "remember to call Linda"'},parent_id:{type:"string",description:'The parent message id of a previous message that you will add a new revision to, by setting parent_id to the origin message being "edited"'}},required:["content"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"update_codicent_message",description:"Posts an edited message, which replaces the old message.",parameters:{type:"object",properties:{content:{type:"string",description:'The updated codicent message text, e.g. "remember to call Johan", usually including the tags from the original message.'},parent_id:{type:"string",description:"The message id of a previous/old message to be updated."}},required:["content","parent_id"]}},(async({content:e,parent_id:t})=>await a.sendMessage(e,t))),d({name:"get_messages_list",description:"Gets messages tagged with given tag name, optionally limited by num_messages. The messages are listed in chronological order, latest first.",parameters:{type:"object",properties:{num_messages:{type:"integer",description:"The number of matching messages to return"},search_text:{type:"string",description:"Search text to filter messages by"},tag_name:{type:"string",description:"Name of tag to find messages by"},after_timestamp:{type:"string",description:"Only return messages after this timestamp"},before_timestamp:{type:"string",description:"Only return messages before this timestamp"}},required:["num_messages"]}},(async({num_messages:e,search_text:t,tag_name:s,after_timestamp:r,before_timestamp:i})=>{let n=await a.getMessages(s?[s]:[],void 0,e);t&&(n=n.filter((e=>e.content.includes(t)))),r&&(n=n.filter((e=>e.createdAt>r))),i&&(n=n.filter((e=>e.createdAt<i)));const o=n.slice(0,e);return console.log("get_messages_list result:",o),o})),d({name:"chat_with_codicent_ai",description:"Sends a message to Codicent AI and gets a response message back. Remember that you can always ask codicent via this tool to find out more about what you can achieve from chatting with the codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"Text of message to the codicent"}},required:["message"]}},(async({message:e})=>await a.chat(e))),d({name:"create_todo",description:"Saves a todo message in Codicent.",parameters:{type:"object",properties:{text:{type:"string",description:"Text of todo"}},required:["text"]}},(async({text:e})=>await a.sendMessage("#todo "+e))),d({name:"place_order",description:"Places and order with the Codicent AI.",parameters:{type:"object",properties:{message:{type:"string",description:"The text message of the order as spoken by the user."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#do Jag kommer ge dig en text (nedan) på vad jag ska beställa. Använd bara den text du får av mig, inga tools.\n Du ska skapa en tabell med detaljerad information inklusive lagerstatus \n för varje artikel i beställningen. Svara först när du har all info på plats. Ställ inga frågor på vägen utan använd det du får av mig.\n \n ----\n EXEMPEL PÅ SVAR:\n ----\n Här är en tabell med detaljerad information inklusive lagerstatus för varje artikel i beställningen:\n \n Artikel\tHyresobjekt\tNamn\tLagertyp\tGrupp\tNamn.1\tSRA/SBEF\tLeverantör\tLevnr\tDepå\tLager\tReserverat\tUthyrt nu\tTillgängligt nu\tMärke/typ\tTillverkarnr\tTillv.år\tInköpsdato\tInköpspris\tVikt\n Elverk\t12345\tElverk 1\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör A\t001\tDepå 1\t5\t0\t1\t4\tHonda EU22i\t123456\t2020\t2020-01-01\t10000 SEK\t21 kg\n Elverk\t12345\tElverk 2\tHyresobjekt\tMaskiner\tElverk\tSRA\tLeverantör B\t002\tDepå 2\t3\t0\t1\t2\tYamaha EF2000iS\t654321\t2019\t2019-05-01\t9000 SEK\t20 kg\n Observera att denna tabell är baserad på den information som finns tillgänglig i lagerstatusen. Om du behöver ytterligare detaljer eller om något specifikt saknas, vänligen meddela mig.\n ----\n \n --- här följer texten på vad jag vill beställa ---\n \n \n ${e}`))),d({name:"remember_info",description:"Saves info in your internal memory for future use. Use this tool to save insights on how to perform our conversations and tasks related to them.",parameters:{type:"object",properties:{message:{type:"string",description:"Your insights to improve our future conversations."}},required:["message"]}},(async({message:e})=>await a.sendMessage(`#index #insights\n\n${e}`))),d({name:"save_to_crm",description:"Saves CRM related info to your memory (logbook).",parameters:{type:"object",properties:{message:{type:"string",description:"CRM log entry description/contents."},company:{type:"string",description:"Company name for CRM log entry."},contact:{type:"string",description:"Contact name for CRM log entry."}},required:["message","company"]}},(async({message:e,company:t,contact:s})=>await a.sendMessage(`#crm\n\nFöretag: ${t}\n\nInfo: ${e}${s?"\n\nKontakt: "+s:""}`))),d({name:"set_page_html",description:"Sets the innerHtml of the div covering the full app page. You can display any html/javascript/style/mermaid content here for the user to see ;-). This view is usually referred to as the canvas, or tavlan in Swedish.",parameters:{type:"object",properties:{html:{type:"string",description:"The inner html to set the page to."}},required:["html"]}},(async({html:e})=>(r(e),n.play(),{ok:!0}))),d({name:"hide_page_html",description:"Hides the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>(r(void 0),{ok:!0}))),d({name:"get_page_html",description:"Gets the inner html of the page.",parameters:{type:"object",properties:{}}},(async()=>({html:o}))),d({name:"get_tasks",description:"Gets the list of possible tasks that can be performed. This lists task names and their id:s. Use get_task to get the task instructions given a task id.",parameters:{type:"object",properties:{},required:[]}},(async e=>(await m()).map((e=>({id:e.id,name:e.title}))))),d({name:"get_task",description:"Gets the task instructions for a given task id. Use get_tasks to get a list of possible tasks (with their id:s).",parameters:{type:"object",properties:{task_id:{type:"string",description:"The task id to get instructions for."}},required:["task_id"]}},(async({task_id:e})=>{const t=(await m()).find((t=>t.id===e));return t?t.content:"Task not found"})),d({name:"get_chat_conversation",description:"Gets a chat conversation (message thread) by message ID. Returns all messages in the conversation thread in chronological order.",parameters:{type:"object",properties:{message_id:{type:"string",description:"The ID of any message in the conversation to retrieve the full thread."}},required:["message_id"]}},(async({message_id:e})=>{try{return{ok:!0,messages:await a.getChatHistory(e)}}catch(e){return{ok:!1,error:e.message||"Failed to get chat conversation"}}})),d({name:"get_gps_location",description:"Gets the current GPS location of the device. Returns latitude and longitude coordinates. Use this when the user asks about nearby places, directions, or anything location-dependent.",parameters:{type:"object",properties:{},required:[]}},(async e=>{try{const e=await s();return e?{ok:!0,latitude:e.coords.latitude,longitude:e.coords.longitude,accuracy:e.coords.accuracy}:{ok:!1,error:"GPS not available"}}catch{return{ok:!1,error:"Failed to get GPS location"}}}));const{additionalTools:l=[],mergeStrategy:g="merge"}=c||{};return"replace"===g?l:"builtin-only"===g?e:[...e,...l]}),[a,r,i,o,n,c]);export{a as default};
@@ -98,6 +98,8 @@ export declare class CodicentService {
98
98
  getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
99
99
  registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
100
100
  loginUser: (userId: string, accessToken: string) => Promise<string | null>;
101
+ loginMicrosoftUser: (userId: string, idToken: string) => Promise<string | null>;
102
+ registerMicrosoftUser: (nickname: string, email: string, userId: string, idToken: string) => Promise<string>;
101
103
  nicknameExists: (nickname: string) => Promise<boolean>;
102
104
  logout: () => void;
103
105
  isRegistered: () => boolean;
@@ -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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,CAAC,CAqF9D;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,CA0B7B;CACH"}
@@ -1 +1 @@
1
- import{loadStripe as t}from"../node_modules/@stripe/stripe-js/dist/index.js";import e from"../utils/MessageContent.js";import"../node_modules/tinycolor2/esm/tinycolor.js";import"react/jsx-runtime";import"react";import"../_virtual/index.js";import"../config/index.js";import"../utils/cacheManager.js";import"../lib/wavtools/lib/wav_packer.js";import"../lib/wavtools/lib/analysis/audio_analysis.js";import"../lib/wavtools/lib/wav_stream_player.js";import"../lib/wavtools/lib/wav_recorder.js";var o;let a="https://codicent.com/",n="-";const s=t=>{t&&"string"==typeof t?(a=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:n,baseUrl:a})):console.warn("Invalid base URL provided, using default")},i=()=>void 0!==window.Codicent&&(window.Codicent.handleMessage=function(t){const e=new CustomEvent("codicent-log",{detail:{message:t}});window.dispatchEvent(e)},window.Codicent.init({token:n,baseUrl:a}),!0);let r=i();if(!r){const t=setInterval((()=>{r=i(),r&&clearInterval(t)}),100)}class c{constructor(o){this.createDataMessage=async(t,e,o)=>await window.Codicent.data.create({codicent:o||this.codicent,tag:t,data:e}),this.readDataMessages=async(t,e,o,a,n,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:a,length:n,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),a=o[0],n=o.slice(1).join("\n");return{id:t.id,title:a,content:n}})),this.getAppPrompts=async()=>(await window.Codicent.getDataMessages({tags:["chatprompt"],codicent:this.codicent})).map((t=>t.data)).map((({title:t,prompt:e})=>({title:t,prompt:e}))),this.uploadFile=async(t,e)=>await window.Codicent.upload(e,t),this.getFileInfo=async t=>await window.Codicent.getFileInfo(t),this.generateApiToken=async(t,e)=>{const o=await fetch(`${a}api/GenerateApiToken?project=${this.codicent}${t?`&expires=${t.toISOString()}`:""}${e?`&forUserNickname=${e}`:""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);return await o.text()},this.sendMessage=(t,e,o)=>window.Codicent.postMessage({message:`@${o||this.codicent} ${t}`,type:"text",parentId:e}),this.chat=(t,e,o)=>window.Codicent.getChatReply4({message:t,codicent:o||this.codicent,messageId:e}),this.getMessagesFast=async(t,e,o=100,n=void 0,s,i=0)=>{const r=await this.request(`${a}app/AppGetMessages`,"POST",{headers:[["Authorization",`Bearer ${this.getToken()}`],["Content-Type","application/json; charset=utf-8"]],body:JSON.stringify({tags:t,codicent:s||this.codicent,search:e,start:i,length:o})});let c=await r.json();if(c.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),n){const t=await this.getPublicFlow(n);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let a=[];const n=t.map((async t=>{const e=await window.Codicent.getMessages({search:`@${this.codicent} #${t}`,length:o});return"chat"===t&&e.forEach((t=>t.content=`#chat\n${t.content}`)),e}));if((await Promise.all(n)).forEach((t=>{a=a.concat(t)})),e)try{const t=await this.getPublicFlow(e);a=a.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return a=a.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),a.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),a},this.registerUser=async(t,e,o,n)=>{const s=await fetch(`${a}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:n,baseUrl:a}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${a}app/LoginAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${e}`]],body:JSON.stringify({userId:t})});if(!o.ok)return 404===o.status||400===o.status?null:401===o.status?(this.handleUnauthorized(),null):"";const n=await o.text();return this.setToken(n),n}catch(t){return console.warn("Error logging in user:",t),""}},this.nicknameExists=async t=>{const e=await fetch(`${a}app/NicknameExists?nickname=${encodeURIComponent(t)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"]]});if(!e.ok)return!1;return await e.json()},this.logout=()=>{this.setToken("")},this.isRegistered=()=>null!==localStorage.getItem("codicent_nickname"),this.getApps=async()=>{try{const t=await fetch(`${a}app/AppGetApps`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw t.status,new Error(`${t.statusText}`);const e=await t.json();return e.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id))&&(this.options.APP_NAME||t.id.startsWith(this.options.APP_PREFIX))))}catch(t){return console.warn("Error fetching apps:",t),null}},this.addFollower=async(t,e)=>{const o=await fetch(`${a}app/AddFollower?nickname=${t}&followerNickname=${e}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText||"Failed to add follower!"}`);return await o.json()},this.cloneProject=async(t,e)=>{const o=await fetch(`${a}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let n=await o.json();if(n){const t='#data #app-theme \n{\n "textcolor": "#212121",\n "backgroundcolor": "#273044",\n "color": "#ffffff",\n "logo": "https://codicent.com/logo512.png",\n "title": "",\n "themeColor": "#581d71",\n "buttonColor": "#c0c0c0",\n "buttonTextColor": "#000000",\n "font": "Montserrat",\n "welcome": "Hej {{username}}!",\n "chatPlaceholder": "Tjena, Loociz här! Vad vill du?",\n "textPlaceholder": "Skriv det du vill spara, så tar jag (Loociz alltså) hand om det!",\n "transcriptionInstructions": "Tryck på knappen för att start och sedan stoppa ljudinspelning."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}if(n){const t='#data #app-button\n{\n "title": "Ta fram företagsinfo",\n "url": "/#/chat?text=Hej!%20Jag%20vill%20spara%20f%C3%B6retagsinfo.%20Guida%20mig%20steg%20f%C3%B6r%20steg%2C%20ett%20i%20taget%2C%20tills%20vi%20har%20all%20info%20om%20mitt%20f%C3%B6retag.%20Exempel%20p%C3%A5%20data%3A%20f%C3%B6retagsnamn%20eller%20id%C3%A9namn%2C%20org.nr.%2C%20%C3%A4gare%2C%20kontaktinformation%2C%20vision%2C%20aff%C3%A4rsid%C3%A9%2C%20mm."\n}';try{await window.Codicent.postMessage({message:`@${e} ${t}`,type:"text"})||(n=!1)}catch{n=!1}}}return n},this.getNickname=async()=>{try{const t=n.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${a}app/GetNickname?userId=${s}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!i.ok)throw 401===i.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${i.statusText}`);return await i.text()}catch{return""}},this.getChatInstructions=async()=>{try{const t=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:1});if(t.length>0)return t[0].content}catch{console.warn("Error fetching chat instructions")}return""},this.updateChatInstructions=async t=>{try{const e=await window.Codicent.getMessages({search:`@${this.codicent} #instructions`,length:100}),o=`@${this.codicent} #instructions\n${t}`;e.length>0?e[0].content!==o&&(console.log("updating instructions",o),await window.Codicent.postMessage({message:o,type:"text",parentId:e[0].id})):(console.log("new instructions",o),await window.Codicent.postMessage({message:o,type:"text"}))}catch{console.warn("Error updating chat instructions")}},this.getUserInfo=async(t,e=!1)=>{const o=await fetch(`${a}app/GetUserInfo?nickname=${t}${e?"&t="+Date.now():""}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);const n=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=n;return{nickname:t,email:s,name:r,picture:i,followers:c,properties:h,owner:d}},this.updateUserInfo=async({nickname:t,email:e,name:o,picture:n})=>{const s=await fetch(`${a}app/AddOrUpdateUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify({nickname:t,email:e,name:o,picture:n,description:""})});if(!s.ok)throw s.status,new Error(`${s.statusText}`);return await this.getUserInfo(t,!0)},this.requestInvite=async(t,e)=>{const o=await fetch(`${a}app/CreateInvitationOrRequest?forUserNickname=${t}&toProjectNickname=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`requestInvite() => ${o.statusText}`),!1)},this.getProjectInfo=this.getUserInfo,this.updateMembersAccess=async(t,e)=>{const o=await fetch(`${a}app/AddOrUpdateProjectProperty?project=${t}&key=APP_EDITORS&value=${e.join(",")}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return!!o.ok||(console.warn(`updateMembersAccess() => ${o.statusText}`),!1)},this.getMembersAccess=async t=>{const e=(await this.getProjectInfo(t,!0)).properties.find((t=>"APP_EDITORS"===t.name));return e&&e.value?e.value.split(","):[]},this.getMemberInfo=async(t,e)=>{const o=await fetch(`${a}app/GetMemberInfo?projectNickname=${encodeURIComponent(t)}&memberNickname=${encodeURIComponent(e)}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw 401===o.status?(this.handleUnauthorized(),new Error("Unauthorized")):new Error(`${o.statusText}`);return await o.json()},this.setToken=t=>{n=t,n&&window.Codicent.init({token:n,baseUrl:a})},this.getToken=()=>n,this.checkPurchaseStatus=async()=>{const t=await fetch(`${a}payments/GetPaymentStatus`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(!t.ok)throw new Error("Failed to check purchase status");const{isPaid:e}=await t.json();return e},this.checkSubscriptionStatus=async()=>{if(!this.options.SUBSCRIPTION_NEEDED)return"active";const t=await fetch(`${a}payments/GetSubscriptionStatus?t=${Date.now()}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`],["Cache-Control","no-cache, no-store, must-revalidate"],["Pragma","no-cache"],["Expires","0"]]});if(!t.ok)throw new Error("Failed to check subscription status");const{status:e}=await t.json();return e},this.createCheckoutSession=async t=>{const e=this.options.STRIPE_SOURCE,o=this.options.STRIPE_TRIAL_PERIOD_DAYS,n={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(n.source=e),o&&o>0&&(n.trialPeriodDays=o);const s=await fetch(`${a}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(n)});if(!s.ok)throw new Error("Failed to create checkout session");const{id:i}=await s.json();return i},this.redirectToCheckout=async e=>{const o=await t(this.options.STRIPE_PUBLIC_KEY);if(!o)throw new Error("Stripe failed to load");const a=await this.createCheckoutSession(e),{error:n}=await o.redirectToCheckout({sessionId:a});if(n)throw new Error(n.message)},this.getChatHistory=async t=>{const e=await fetch(`${a}api/GetMessageHistory?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get chat history");let o=await e.json();return o=o.filter((t=>!t.content.includes("#function_result")&&!t.content.includes("#finish_reason_function_call"))),o},this.getPublicFlow=async t=>{const e=await fetch(`${a}app/GetPublicFlow?codicent=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!e.ok)throw new Error("Failed to get public flow");const o=await e.json();return o.forEach((t=>{t.createdAt=new Date(Date.parse(t.createdAt))})),o},this.getMessageContent=async t=>{const e=await fetch(`${a}app/GetMessageContent?id=${t}`,{method:"GET",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]]});if(e.ok){const t=await e.json();return{content:t.content,url:t.url}}return{content:"",url:""}},this.logAction=async(t,e)=>{if(!this.options.APP_LOG_CODICENT)return"";const o={content:`@${this.options.APP_LOG_CODICENT} #debug #${e}\n${t}`,type:"text"},n=await fetch(`${a}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!n.ok)throw new Error(`${n.statusText||"Failed to post log message!"}`);return(await n.json()).id},this.createApp=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.APP_PREFIX}${t}`;if(!await this.nicknameExists(e)){if(await this.cloneProject(this.options.APP_TEMPLATE,e)){if(this.options.ANONYMOUS_TOKEN)try{const t=this.options.ANONYMOUS_TOKEN.split(".")[1],o=atob(t),a=JSON.parse(o).nickname;if(!await this.addFollower(e,a))throw new Error("Failed to add follower: "+a)}catch(t){console.error("Error extracting adding anonymous follower:",t)}return e}}}}catch(t){console.error("Error creating app:",t)}return null},this.findUsername=async()=>{try{for(let t=0;t<50;t++){const t=Math.floor(99999*Math.random())+1,e=`${this.options.USER_PREFIX}${t}`;if(!await this.nicknameExists(e))return e}}catch(t){console.warn("Error finding username:",t)}return null},this.getForms=async()=>{const t=await this.request(`${a}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${a}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${a}app/GetTodoStatus?messageId=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return e.ok?await e.text():(e.status,console.warn(`getTodoStatus() => ${e.statusText}`),"unknown")},this.updateTodoStatus=async(t,e)=>{const o=await fetch(`${a}app/UpdateTodoStatus?messageId=${t}&status=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)return console.warn(`updateTodoStatus() => ${o.statusText}`),!1;return await o.json()},this.codicent="",this.options=o,s(o.API_BASE_URL)}async request(t,e,o={}){const a={};o.headers&&o.headers.forEach((([t,e])=>{a[t]=e}));const n=await fetch(t,{...o,method:e,headers:a});if(!n.ok)throw 401===n.status&&this.handleUnauthorized(),new Error(`${n.statusText}`);return n}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${a}realtime/session?voice=${t}&provider=${e}`,n=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!n.ok)throw new Error(`Failed to fetch session token: ${n.statusText}`);const s=await n.json(),i=s.client_secret?.value;if(!i)throw new Error("No ephemeral key returned from session endpoint");return i}async getRealtimeConfig(t="openai"){try{const e=`${a}realtime/config?provider=${t}`,o=await fetch(e,{method:"GET",headers:{Authorization:`Bearer ${this.getToken()}`}});return o.ok?await o.json():null}catch(t){return console.warn("Failed to fetch realtime config:",t),null}}}o=c,c.getImageUrl=(t,e)=>`${a}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${a}app/DownloadFile?fileId=${t}${e?`&extension=${e}`:""}`,c.downloadFile=async t=>{fetch(o.getFileUrl(t.id)).then((t=>{if(t.headers.forEach(((t,e)=>{console.log(`${e}: ${t}`)})),t.ok)return t.blob();throw new Error("Network response was not ok.")})).then((e=>{const o=window.URL.createObjectURL(e),a=document.createElement("a");a.style.display="none",a.href=o,a.download=t.filename,document.body.appendChild(a),a.click(),window.URL.revokeObjectURL(o)})).catch((t=>{console.error("There was a problem with the fetch operation:",t)}))},c.getMiniChatReplyOld=async(t,e="codicent-mini",o)=>{let s={project:e,message:t};o&&(s.messageId=o);const i=await fetch(`${a}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(s)});if(!i.ok)return void i.status;return(await i.json()).content.replace("@codicent-mini","").trim()},c.getMiniChatReply=async(t,e="codicent-mini",o,s=3e5,i=2e3,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${a}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${n}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<s;)try{const t=await fetch(`${a}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{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(),s=o.content??o.content??"";return{content:s.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}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 n="https://codicent.com/",a="-";const s=t=>{t&&"string"==typeof t?(n=t.endsWith("/")?t:t+"/","undefined"!=typeof window&&void 0!==window.Codicent&&"function"==typeof window.Codicent.init&&window.Codicent.init({token:a,baseUrl:n})):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:a,baseUrl:n}),!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,n,a,s,i,r)=>await window.Codicent.data.read({codicent:o||this.codicent,tag:t,search:e,start:n,length:a,afterTimestamp:s,beforeTimestamp:i,dataFilters:r}),this.readOneDataMessage=async t=>await window.Codicent.data.readOne(t),this.updateDataMessage=async(t,e,o)=>await window.Codicent.data.update({id:t,data:e,codicent:o||this.codicent}),this.deleteDataMessage=async(t,e)=>await window.Codicent.data.delete({id:t,codicent:e||this.codicent}),this.getSchema=async(t,e)=>{try{const e=await fetch(`${this.options.API_BASE_URL}api/GetSchema/${t}`,{method:"GET",headers:{Authorization:`Bearer ${this.options.APP_LOG_TOKEN}`,"Content-Type":"application/json"}});if(!e.ok){if(404===e.status)return null;throw new Error(`Failed to fetch schema: ${e.statusText}`)}const o=await e.text();return JSON.parse(o)}catch(e){return console.error(`Error fetching schema for tag ${t}:`,e),null}},this.getAppTheme=async()=>{try{const t=await window.Codicent.getDataMessages({tags:["app-theme"],codicent:this.codicent});return t.length>0?t[0].data:null}catch(t){return console.error("Error fetching app theme:",t),null}},this.getAppButtons=async()=>{const t=(await window.Codicent.getDataMessages({tags:[this.options.BUTTON_TAG],codicent:this.codicent})).map((t=>t.data));return t.sort(((t,e)=>t.title>e.title?1:-1)),t},this.getAppTasks=async()=>(await window.Codicent.getMessages({search:`@${this.codicent} #app-task`,length:50})).map((t=>{const o=new e(t.content).content.split("\n"),n=o[0],a=o.slice(1).join("\n");return{id:t.id,title:n,content:a}})),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(`${n}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,a=void 0,s,i=0)=>{const r=await this.request(`${n}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))})),a){const t=await this.getPublicFlow(a);c=c.concat(t),c.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime()))}return c},this.getMessages=async(t,e,o=10)=>{let n=[];const a=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(a)).forEach((t=>{n=n.concat(t)})),e)try{const t=await this.getPublicFlow(e);n=n.concat(t)}catch(t){console.warn("Error fetching public flow, PUBLIC_TAG missing in codicent?",t)}return n=n.filter(((t,e,o)=>e===o.findIndex((e=>e.id===t.id)))),n.sort(((t,e)=>e.createdAt.getTime()-t.createdAt.getTime())),n},this.registerUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterAuth0User`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";const i=await s.text();return window.Codicent.init({token:i,baseUrl:n}),i},this.loginUser=async(t,e)=>{try{const o=await fetch(`${n}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 a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in user:",t),""}},this.loginMicrosoftUser=async(t,e)=>{try{const o=await fetch(`${n}app/LoginMicrosoftUser`,{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 a=await o.text();return this.setToken(a),a}catch(t){return console.warn("Error logging in Microsoft user:",t),""}},this.registerMicrosoftUser=async(t,e,o,a)=>{const s=await fetch(`${n}app/RegisterMicrosoftUser`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify({nickname:t,email:e,userId:o})});if(!s.ok)return"";return await s.text()},this.nicknameExists=async t=>{const e=await fetch(`${n}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(`${n}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(`${n}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(`${n}app/CloneProject?project=${t}&newProject=${e}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});if(!o.ok)throw o.status,new Error(`${o.statusText}`);let a=await o.json();if(a){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"})||(a=!1)}catch{a=!1}if(a){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"})||(a=!1)}catch{a=!1}}}return a},this.getNickname=async()=>{try{const t=a.split(".")[1],e=atob(t),o=JSON.parse(e),s=o.sub||o.userId,i=await fetch(`${n}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(`${n}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 a=await o.json(),{email:s,picture:i,description:r,followers:c,properties:h,owner:d}=a;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:a})=>{const s=await fetch(`${n}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:a,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(`${n}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(`${n}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(`${n}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=>{a=t,a&&window.Codicent.init({token:a,baseUrl:n})},this.getToken=()=>a,this.checkPurchaseStatus=async()=>{const t=await fetch(`${n}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(`${n}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,a={priceId:t,successUrl:window.location.href,cancelUrl:window.location.href};e&&(a.source=e),o&&o>0&&(a.trialPeriodDays=o);const s=await fetch(`${n}payments/CreateCheckoutSession`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.getToken()}`]],body:JSON.stringify(a)});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 n=await this.createCheckoutSession(e),{error:a}=await o.redirectToCheckout({sessionId:n});if(a)throw new Error(a.message)},this.getChatHistory=async t=>{const e=await fetch(`${n}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(`${n}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(`${n}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"},a=await fetch(`${n}app/AddChatMessage`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${this.options.APP_LOG_TOKEN}`]],body:JSON.stringify(o)});if(!a.ok)throw new Error(`${a.statusText||"Failed to post log message!"}`);return(await a.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),n=JSON.parse(o).nickname;if(!await this.addFollower(e,n))throw new Error("Failed to add follower: "+n)}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(`${n}app/GetForms?codicent=${this.codicent}`,"GET",{headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await t.json()},this.getFormById=async t=>{const e=await fetch(`${n}app/GetFormById?id=${t}`,{method:"GET",headers:[["Authorization",`Bearer ${this.getToken()}`]]});return await e.json()},this.getTodoStatus=async t=>{const e=await fetch(`${n}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(`${n}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 n={};o.headers&&o.headers.forEach((([t,e])=>{n[t]=e}));const a=await fetch(t,{...o,method:e,headers:n});if(!a.ok)throw 401===a.status&&this.handleUnauthorized(),new Error(`${a.statusText}`);return a}handleUnauthorized(){this.onUnauthorized&&this.onUnauthorized()}async getRealtimeSessionToken(t="alloy",e="openai"){const o=`${n}realtime/session?voice=${t}&provider=${e}`,a=await fetch(o,{headers:{Authorization:`Bearer ${this.getToken()}`}});if(!a.ok)throw new Error(`Failed to fetch session token: ${a.statusText}`);const s=await a.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=`${n}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)=>`${n}app/GetImage?fileId=${t}&width=${e}`,c.getFileUrl=(t,e)=>`${n}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),n=document.createElement("a");n.style.display="none",n.href=o,n.download=t.filename,document.body.appendChild(n),n.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(`${n}app/GetAi2ChatReply`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],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,r)=>{const c={project:e,message:t};let h;o&&(c.messageId=o),r&&(c.previousResponseId=r);try{const t=await fetch(`${n}app/StartAi2ChatAsync`,{method:"POST",headers:[["Content-Type","application/json; charset=utf-8"],["Authorization",`Bearer ${a}`]],body:JSON.stringify(c)});if(!t.ok)return t.status,void console.error(`Failed to start AI chat: ${t.status}`);if(h=(await t.json()).promptMessageId,!h)return void console.error("No promptMessageId returned from server")}catch(t){return void console.error("Error starting AI chat:",t)}const d=Date.now();for(;Date.now()-d<s;)try{const t=await fetch(`${n}app/GetAi2ChatReplyStatus?promptMessageId=${h}`,{method:"GET",headers:[["Authorization",`Bearer ${a}`]]});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(),s=o.content??o.content??"";return{content:s.replace(`@${e}`,"").replace("@codicent-mini","").trim(),responseId:o.responseId??void 0}}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")=>{if(!a||"-"===a)return{translation:t};const s=await fetch(`${n}app/GetTranslations`,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8",Authorization:`Bearer ${a}`},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
@@ -111,6 +111,8 @@ declare class CodicentService {
111
111
  getMessages: (tags: string[], codicent?: string, length?: number) => Promise<Message[]>;
112
112
  registerUser: (nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
113
113
  loginUser: (userId: string, accessToken: string) => Promise<string | null>;
114
+ loginMicrosoftUser: (userId: string, idToken: string) => Promise<string | null>;
115
+ registerMicrosoftUser: (nickname: string, email: string, userId: string, idToken: string) => Promise<string>;
114
116
  nicknameExists: (nickname: string) => Promise<boolean>;
115
117
  logout: () => void;
116
118
  isRegistered: () => boolean;
@@ -334,7 +336,13 @@ interface UseAuthState {
334
336
  loginWithRedirect: (options?: RedirectLoginOptions<AppState>) => Promise<void>;
335
337
  loginPasswordless: (email: string) => Promise<void>;
336
338
  }
337
- declare const useAuthState: (auth0: Auth0ContextInterface) => UseAuthState;
339
+ interface AuthStateOptions {
340
+ /** Override the backend login call. Defaults to Auth0-based LoginAuth0User endpoint. */
341
+ loginFn?: (service: CodicentService, userId: string, accessToken: string) => Promise<string | null | "">;
342
+ /** Override the backend register call. Defaults to Auth0-based RegisterAuth0User endpoint. */
343
+ registerFn?: (service: CodicentService, nickname: string, email: string, userId: string, accessToken: string) => Promise<string>;
344
+ }
345
+ declare const useAuthState: (auth0: Auth0ContextInterface, options?: AuthStateOptions) => UseAuthState;
338
346
 
339
347
  declare class Content$1 {
340
348
  mentions: string[];
@@ -762,8 +770,9 @@ interface CodicentAppState {
762
770
  interface UseCodicentAppOptions {
763
771
  auth0: Auth0ContextInterface;
764
772
  toolsConfig?: ToolsConfig;
773
+ authOptions?: AuthStateOptions;
765
774
  }
766
- declare const useCodicentApp: ({ auth0, toolsConfig }: UseCodicentAppOptions) => CodicentAppState;
775
+ declare const useCodicentApp: ({ auth0, toolsConfig, authOptions }: UseCodicentAppOptions) => CodicentAppState;
767
776
 
768
777
  declare const useAppStyles: () => Record<"button" | "pointer" | "roundButton" | "menuButton", string>;
769
778
 
@@ -1688,4 +1697,4 @@ interface CodicentApp {
1688
1697
  */
1689
1698
  declare function createCodicentApp(config: CreateAppConfig): CodicentApp;
1690
1699
 
1691
- export { AiInput, AppButtonsConfig, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, BulkUploadDialog, Button, ButtonConfig, CacheEntry, CacheManager, CachedUserSession, Chat, ChatInput, ChatInstructions, ChatMessage, ChatProps, CodicentApp, CodicentAppState, CodicentMessage, CodicentService, CodicentServiceOptions, ColorPicker, ColumnAction, ColumnDefinition, CombinedPlaceholderDialog, Compose, CompoundButton, Content, CookieBanner, CookieBannerProps, CreateAppConfig, CrmPage, CrmPagePersistent, DataMessage$1 as DataMessage, DataSchemas, DatePicker, Debug, ErrorBoundary, FileInfo$1 as FileInfo, FilePlaceholder, FileThumbnail, Footer, Form$1 as Form, FormAccept, FormInvite, Form as FormPage, GenericJsonRenderer, Header, Help, HtmlView, HtmlViewer, ImageViewer as ImageView, Input, ItemType, Label, LanguageSelector, ListDefinitions, _default as ListView, ListViewProps, Login, Logout, Markdown, MemberInfo, Message$2 as Message, Content$1 as MessageContent, MessageInput, MessageItem, ModuleFlags, OfflineMessage, Page, Profile, Prompt, Purchase, QrCodeDialog, QrScan, QrScanner, RealtimeVoice, RecordModal, RecordModalProps, Sales, Schema, SchemaDefinition, SchemaEditor, SchemaItem, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, Tool, ToolMergeStrategy, ToolsConfig, TranslationDictionary, TranslationResponse, Translations, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UseCodicentAppOptions, UserInfo, VoiceIcon, VoiceIconProps, WavRecorder, WavStreamPlayer, createAppStateMachine, createCodicentApp, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, setBaseUrl, stateMachineCacheManager, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useDebugLogs, useLocalization, useObserveDataSchemas, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
1700
+ export { AiInput, AppButtonsConfig, AppConfig, AppConfigOptions, AppFrame, AppInfo, AppStateDefinition, AppStateMachine, AudioIcon, AudioRecorder, AudioRecorderState, AuthStateOptions, BulkUploadDialog, Button, ButtonConfig, CacheEntry, CacheManager, CachedUserSession, Chat, ChatInput, ChatInstructions, ChatMessage, ChatProps, CodicentApp, CodicentAppState, CodicentMessage, CodicentService, CodicentServiceOptions, ColorPicker, ColumnAction, ColumnDefinition, CombinedPlaceholderDialog, Compose, CompoundButton, Content, CookieBanner, CookieBannerProps, CreateAppConfig, CrmPage, CrmPagePersistent, DataMessage$1 as DataMessage, DataSchemas, DatePicker, Debug, ErrorBoundary, FileInfo$1 as FileInfo, FilePlaceholder, FileThumbnail, Footer, Form$1 as Form, FormAccept, FormInvite, Form as FormPage, GenericJsonRenderer, Header, Help, HtmlView, HtmlViewer, ImageViewer as ImageView, Input, ItemType, Label, LanguageSelector, ListDefinitions, _default as ListView, ListViewProps, Login, Logout, Markdown, MemberInfo, Message$2 as Message, Content$1 as MessageContent, MessageInput, MessageItem, ModuleFlags, OfflineMessage, Page, Profile, Prompt, Purchase, QrCodeDialog, QrScan, QrScanner, RealtimeVoice, RecordModal, RecordModalProps, Sales, Schema, SchemaDefinition, SchemaEditor, SchemaItem, Search, SearchBox, Snap, SnapFooter, Spinner, StateContext, TemplateVariable, Text, TextHeader, Textarea, TimePicker, Title, Tool, ToolMergeStrategy, ToolsConfig, TranslationDictionary, TranslationResponse, Translations, TypingIndicator, UploadFile, UploadFileProps, UploadFileRef, UrlProcessor, UseAuthState, UseCodicentAppOptions, UserInfo, VoiceIcon, VoiceIconProps, WavRecorder, WavStreamPlayer, createAppStateMachine, createCodicentApp, generateBrandVariants, getConfigValue, getGpsLocation, getTimeString, initCodicentApp, isMobileDevice, log, setBaseUrl, stateMachineCacheManager, useAppStyles, useAudioRecorder, useAuthState, useChat, useCodicentApp, useCodicentState, useDebugLogs, useLocalization, useObserveDataSchemas, useRealtimeVoiceAI, useStateWithLocalStorage, useTemplateVariables, useToaster, useTools, withWakeLock };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codicent-app-sdk",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "SDK for building AI-powered applications with Codicent",
5
5
  "type": "module",
6
6
  "main": "dist/cjs/index.js",