@promte/app-library 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,69 @@
1
1
  import { default as default_2 } from 'react';
2
2
  import { JSX as JSX_2 } from 'react/jsx-runtime';
3
3
 
4
+ export declare type AppDataRef = {
5
+ get(): Promise<any>;
6
+ set(value: any): Promise<any>;
7
+ update(updates: AppDataUpdateMap): Promise<any>;
8
+ remove(): Promise<any>;
9
+ push(value: any): Promise<any>;
10
+ ref(path: string): AppDataRef;
11
+ };
12
+
13
+ export declare type AppDataScope = "private" | "public";
14
+
15
+ export declare type AppDataUpdateMap = Record<string, any>;
16
+
17
+ export declare type AudioSttRequest = {
18
+ file: File | Blob;
19
+ language?: string;
20
+ prompt?: string;
21
+ ext?: string;
22
+ };
23
+
24
+ export declare type AudioSttResponse = {
25
+ text: string;
26
+ raw: any;
27
+ };
28
+
29
+ export declare type AudioTtsRequest = {
30
+ text: string;
31
+ voice?: string;
32
+ lang?: string;
33
+ };
34
+
35
+ export declare type AudioTtsResponse = {
36
+ audio: ArrayBuffer;
37
+ contentType: string | null;
38
+ };
39
+
40
+ export declare type AudioVoiceInfo = {
41
+ short_name?: string;
42
+ locale?: string;
43
+ local_name?: string;
44
+ locale_english_name?: string;
45
+ locale_native_name?: string;
46
+ gender?: string;
47
+ voice_type?: string;
48
+ name?: string;
49
+ display_name?: string;
50
+ style_list?: string[];
51
+ sample_rate_hertz?: string;
52
+ status?: string;
53
+ words_per_minute?: string;
54
+ };
55
+
56
+ export declare type AudioVoicesRequest = {
57
+ locale?: string;
58
+ };
59
+
4
60
  export declare type ChatCompletionsRequest = {
5
61
  model: string;
6
62
  messages: ChatMessage[];
7
63
  stream?: false;
8
64
  temperature?: number;
65
+ reasoningEffort?: ReasoningEffort;
66
+ reasoning_effort?: ReasoningEffort;
9
67
  };
10
68
 
11
69
  export declare type ChatCompletionsResponse = any;
@@ -33,11 +91,19 @@ export declare type PromteClient = {
33
91
  getBackendUrl(): string | null;
34
92
  chatCompletions(req: ChatCompletionsRequest): Promise<ChatCompletionsResponse>;
35
93
  chatText(req: ChatCompletionsRequest): Promise<string>;
94
+ audio: {
95
+ tts(req: AudioTtsRequest): Promise<AudioTtsResponse>;
96
+ stt(req: AudioSttRequest): Promise<AudioSttResponse>;
97
+ voices(req?: AudioVoicesRequest): Promise<AudioVoiceInfo[]>;
98
+ };
99
+ data(scope?: AppDataScope): AppDataRef;
36
100
  };
37
101
 
38
102
  declare type PromteCtxValue = {
39
103
  settings: PromteSettings | null;
40
104
  token: string | null;
105
+ isDarkMode: boolean | null;
106
+ user: PromteUser | null;
41
107
  ready: boolean;
42
108
  state: PromteHandshakeState;
43
109
  error: string | null;
@@ -51,14 +117,28 @@ export declare type PromteSettings = {
51
117
  version: number;
52
118
  backendUrl: string;
53
119
  parentOrigin?: string;
120
+ user?: PromteUser;
54
121
  };
55
122
 
123
+ export declare type PromteUser = {
124
+ email?: string;
125
+ isAdmin?: boolean;
126
+ role?: string;
127
+ workspaceId?: string;
128
+ };
129
+
130
+ export declare type ReasoningEffort = "minimal" | "low" | "medium" | "high";
131
+
56
132
  export declare function usePromte(): PromteCtxValue;
57
133
 
58
134
  export declare function usePromteClient(): PromteClient;
59
135
 
136
+ export declare function usePromteDarkMode(): boolean;
137
+
60
138
  export declare function usePromteSettings(): PromteSettings;
61
139
 
62
140
  export declare function usePromteToken(): string;
63
141
 
142
+ export declare function usePromteUser(): PromteUser;
143
+
64
144
  export { }
package/dist/index.mjs CHANGED
@@ -1,136 +1,298 @@
1
- import { jsx as A } from "react/jsx-runtime";
2
- import { createContext as M, useState as v, useMemo as w, useCallback as T, useEffect as g, useContext as U } from "react";
3
- const E = M(null);
4
- function _({
5
- children: u,
6
- expectedParentOrigin: r,
7
- initTargetOrigin: f,
8
- retryInit: n = { enabled: !0, intervalMs: 500, maxAttempts: 20 }
1
+ import { jsx as M } from "react/jsx-runtime";
2
+ import { createContext as A, useState as E, useMemo as j, useCallback as D, useEffect as R, useContext as L } from "react";
3
+ const U = A(null);
4
+ function z({
5
+ children: y,
6
+ expectedParentOrigin: h,
7
+ initTargetOrigin: v,
8
+ retryInit: f = { enabled: !0, intervalMs: 500, maxAttempts: 20 }
9
9
  }) {
10
- const [t, c] = v(null), [e, i] = v(null), [m, p] = v(null), h = w(() => m ? "booting" : t ? e ? "ready" : "waiting_for_token" : "waiting_for_settings", [t, e, m]), k = h === "ready", b = w(() => f || r || "*", [f, r]), d = T(() => {
11
- var l;
10
+ const [u, P] = E(null), [p, x] = E(null), [k, e] = E(null), [r, n] = E(null), [t, o] = E(null), i = j(() => t ? "booting" : u ? p ? "ready" : "waiting_for_token" : "waiting_for_settings", [u, p, t]), l = i === "ready", w = j(() => v || h || "*", [v, h]), d = D(() => {
11
+ var g;
12
12
  try {
13
- const o = { type: "init" };
14
- (l = window.parent) == null || l.postMessage(o, b);
15
- } catch (o) {
16
- p((o == null ? void 0 : o.message) || "Failed to post init");
13
+ const m = { type: "init" };
14
+ (g = window.parent) == null || g.postMessage(m, w);
15
+ } catch (m) {
16
+ o((m == null ? void 0 : m.message) || "Failed to post init");
17
17
  }
18
- }, [b]);
19
- g(() => {
18
+ }, [w]);
19
+ R(() => {
20
20
  d();
21
- }, [d]), g(() => {
22
- if (!(n != null && n.enabled) || t) return;
23
- const l = n.intervalMs ?? 500, o = n.maxAttempts ?? 20;
24
- let s = 0;
25
- const a = window.setInterval(() => {
26
- if (t) {
27
- window.clearInterval(a);
21
+ }, [d]), R(() => {
22
+ if (!(f != null && f.enabled) || u) return;
23
+ const g = f.intervalMs ?? 500, m = f.maxAttempts ?? 20;
24
+ let a = 0;
25
+ const c = window.setInterval(() => {
26
+ if (u) {
27
+ window.clearInterval(c);
28
28
  return;
29
29
  }
30
- if (s += 1, s > o) {
31
- window.clearInterval(a);
30
+ if (a += 1, a > m) {
31
+ window.clearInterval(c);
32
32
  return;
33
33
  }
34
34
  d();
35
- }, l);
36
- return () => window.clearInterval(a);
37
- }, [n, t, d]), g(() => {
38
- const l = (o) => {
39
- if (r && o.origin !== r) return;
40
- const s = o.data;
41
- if (!(!s || typeof s != "object")) {
42
- if (s.type === "set-settings") {
43
- const a = s.value;
44
- if (!(a != null && a.backendUrl) || a.parentOrigin && r && a.parentOrigin !== r)
35
+ }, g);
36
+ return () => window.clearInterval(c);
37
+ }, [f, u, d]), R(() => {
38
+ const g = (m) => {
39
+ if (h && m.origin !== h) return;
40
+ const a = m.data;
41
+ if (!(!a || typeof a != "object")) {
42
+ if (a.type === "set-settings") {
43
+ const c = a.value;
44
+ if (!(c != null && c.backendUrl) || c.parentOrigin && h && c.parentOrigin !== h)
45
45
  return;
46
- c(a), p(null);
46
+ P(c), c != null && c.user && n(c.user), o(null);
47
47
  return;
48
48
  }
49
- if (s.type === "set-token" && typeof s.value == "string") {
50
- i(s.value), p(null);
49
+ if (a.type === "set-token" && typeof a.value == "string") {
50
+ x(a.value), o(null);
51
+ return;
52
+ }
53
+ if (a.type === "set-dark-mode" && typeof a.value == "boolean") {
54
+ e(a.value);
55
+ return;
56
+ }
57
+ if (a.type === "set-user" && typeof a.value == "object") {
58
+ n(a.value);
51
59
  return;
52
60
  }
53
61
  }
54
62
  };
55
- return window.addEventListener("message", l), () => window.removeEventListener("message", l);
56
- }, [r]);
57
- const C = w(() => j(
58
- () => t,
59
- () => e
60
- ), [t, e]), P = w(
63
+ return window.addEventListener("message", g), () => window.removeEventListener("message", g);
64
+ }, [h]);
65
+ const s = j(() => F(
66
+ () => u,
67
+ () => p
68
+ ), [u, p]), T = j(
61
69
  () => ({
62
- settings: t,
63
- token: e,
64
- ready: k,
65
- state: h,
66
- error: m,
67
- client: C
70
+ settings: u,
71
+ token: p,
72
+ isDarkMode: k,
73
+ user: r,
74
+ ready: l,
75
+ state: i,
76
+ error: t,
77
+ client: s
68
78
  }),
69
- [t, e, k, h, m, C]
79
+ [u, p, k, r, l, i, t, s]
70
80
  );
71
- return /* @__PURE__ */ A(E.Provider, { value: P, children: u });
81
+ return /* @__PURE__ */ M(U.Provider, { value: T, children: y });
72
82
  }
73
- function y() {
74
- const u = U(E);
75
- if (!u)
83
+ function b() {
84
+ const y = L(U);
85
+ if (!y)
76
86
  throw new Error("usePromte must be used inside <PromteAppProvider>");
77
- return u;
87
+ return y;
78
88
  }
79
- function L() {
80
- return y().settings;
89
+ function G() {
90
+ return b().settings;
81
91
  }
82
- function R() {
83
- return y().token;
92
+ function J() {
93
+ return b().token;
84
94
  }
85
- function B() {
86
- return y().client;
95
+ function N() {
96
+ return b().isDarkMode;
87
97
  }
88
- function j(u, r) {
89
- async function f(n, t) {
90
- const c = u(), e = r();
91
- if (!c) throw new Error("Promte settings not received yet");
92
- if (!e) throw new Error("Promte token not received yet");
93
- const i = new URL(c.backendUrl + "/" + n).toString();
94
- return await fetch(i, {
95
- ...t,
98
+ function O() {
99
+ return b().user;
100
+ }
101
+ function I() {
102
+ return b().client;
103
+ }
104
+ function F(y, h) {
105
+ const v = (e) => typeof e == "string" && e.startsWith("gpt-5");
106
+ async function f(e, r) {
107
+ const n = y(), t = h();
108
+ if (!n) throw new Error("Promte settings not received yet");
109
+ if (!t) throw new Error("Promte token not received yet");
110
+ const o = new URL(n.backendUrl + "/" + e).toString();
111
+ return await fetch(o, {
112
+ ...r,
96
113
  headers: {
97
- ...t.headers || {},
98
- Authorization: `Bearer ${e}`
114
+ ...r.headers || {},
115
+ Authorization: `Bearer ${t}`
99
116
  }
100
117
  });
101
118
  }
119
+ async function u(e, r) {
120
+ const n = await f(`/app-api/data/${e}`, {
121
+ method: "POST",
122
+ headers: { "Content-Type": "application/json" },
123
+ body: JSON.stringify(r)
124
+ }), t = await n.json().catch(() => ({}));
125
+ if (!n.ok)
126
+ throw new Error(
127
+ (t == null ? void 0 : t.error) || `Request failed (${n.status})`
128
+ );
129
+ return t == null ? void 0 : t.value;
130
+ }
131
+ async function P(e) {
132
+ const r = new URLSearchParams();
133
+ e.scope && r.set("scope", e.scope), e.path && r.set("path", e.path);
134
+ const n = await f(`/app-api/data?${r.toString()}`, {
135
+ method: "GET"
136
+ }), t = await n.json().catch(() => ({}));
137
+ if (!n.ok)
138
+ throw new Error((t == null ? void 0 : t.error) || `Request failed (${n.status})`);
139
+ return t == null ? void 0 : t.value;
140
+ }
141
+ const p = (e) => e ? e.split("/").map((r) => r.trim()).filter(Boolean).join("/") : "", x = (e, r) => {
142
+ const n = p(e), t = p(r);
143
+ return n ? t ? `${n}/${t}` : n : t;
144
+ }, k = (e, r) => {
145
+ const n = { scope: e };
146
+ return {
147
+ async get() {
148
+ const t = p(r);
149
+ return P({ ...n, path: t || void 0 });
150
+ },
151
+ async set(t) {
152
+ const o = p(r);
153
+ return u("set", {
154
+ ...n,
155
+ path: o || void 0,
156
+ value: t
157
+ });
158
+ },
159
+ async update(t) {
160
+ if (!t || typeof t != "object")
161
+ throw new Error("update requires an object");
162
+ const o = {};
163
+ for (const [i, l] of Object.entries(t)) {
164
+ const w = x(r, i);
165
+ if (!w)
166
+ throw new Error("update paths must be non-empty");
167
+ o[w] = l;
168
+ }
169
+ return u("update", { ...n, updates: o });
170
+ },
171
+ async remove() {
172
+ const t = p(r);
173
+ return u("remove", { ...n, path: t || void 0 });
174
+ },
175
+ async push(t) {
176
+ const o = p(r);
177
+ if (!o) throw new Error("push requires a path");
178
+ return u("array-push", { ...n, path: o, value: t });
179
+ },
180
+ ref(t) {
181
+ const o = x(r, t);
182
+ if (!o) throw new Error("ref requires a path");
183
+ return k(e, o);
184
+ }
185
+ };
186
+ };
102
187
  return {
103
188
  isReady() {
104
- return !!u() && !!r();
189
+ return !!y() && !!h();
105
190
  },
106
191
  getBackendUrl() {
107
- var n;
108
- return ((n = u()) == null ? void 0 : n.backendUrl) ?? null;
192
+ var e;
193
+ return ((e = y()) == null ? void 0 : e.backendUrl) ?? null;
109
194
  },
110
- async chatCompletions(n) {
111
- var i;
112
- const t = await f("/openai/chat/completions", {
195
+ async chatCompletions(e) {
196
+ var s;
197
+ const {
198
+ reasoningEffort: r,
199
+ reasoning_effort: n,
200
+ ...t
201
+ } = e, o = r ?? n, i = {
202
+ ...t,
203
+ stream: !1
204
+ };
205
+ o && v(e.model) && (i.reasoning_effort = o);
206
+ const l = await f("/openai/chat/completions", {
113
207
  method: "POST",
114
208
  headers: { "Content-Type": "application/json" },
115
- body: JSON.stringify({ ...n, stream: !1 })
116
- }), e = (t.headers.get("content-type") || "").includes("application/json") ? await t.json() : await t.text();
117
- if (!t.ok)
209
+ body: JSON.stringify(i)
210
+ }), d = (l.headers.get("content-type") || "").includes("application/json") ? await l.json() : await l.text();
211
+ if (!l.ok)
118
212
  throw new Error(
119
- typeof e == "string" ? e : ((i = e == null ? void 0 : e.error) == null ? void 0 : i.message) || `Request failed (${t.status})`
213
+ typeof d == "string" ? d : ((s = d == null ? void 0 : d.error) == null ? void 0 : s.message) || `Request failed (${l.status})`
120
214
  );
121
- return e;
215
+ return d;
216
+ },
217
+ async chatText(e) {
218
+ var n, t, o;
219
+ const r = await this.chatCompletions(e);
220
+ return ((o = (t = (n = r == null ? void 0 : r.choices) == null ? void 0 : n[0]) == null ? void 0 : t.message) == null ? void 0 : o.content) ?? "";
221
+ },
222
+ audio: {
223
+ async tts(e) {
224
+ var o;
225
+ const r = (o = e == null ? void 0 : e.text) == null ? void 0 : o.trim();
226
+ if (!r) throw new Error("audio.tts requires non-empty text");
227
+ const n = await f("/app-api/audio/tts", {
228
+ method: "POST",
229
+ headers: { "Content-Type": "application/json" },
230
+ body: JSON.stringify({
231
+ text: r,
232
+ voice: e.voice,
233
+ lang: e.lang
234
+ })
235
+ });
236
+ if (!n.ok) {
237
+ const i = await n.text();
238
+ throw new Error(i || `Request failed (${n.status})`);
239
+ }
240
+ return {
241
+ audio: await n.arrayBuffer(),
242
+ contentType: n.headers.get("content-type")
243
+ };
244
+ },
245
+ async stt(e) {
246
+ var g, m, a;
247
+ if (!(e != null && e.file)) throw new Error("audio.stt requires a file");
248
+ const r = (c) => {
249
+ if (!c) return;
250
+ const $ = c.trim();
251
+ if (!$) return;
252
+ const C = $.toLowerCase(), S = C.split("-")[0];
253
+ return S.length === 2 ? S : C;
254
+ }, n = typeof File < "u" && e.file instanceof File, t = n && e.file.name.split(".").pop() || "webm", o = e.ext || t, i = new FormData();
255
+ n ? i.set("file", e.file) : i.set("file", e.file, `audio.${o}`);
256
+ const l = r(e.language);
257
+ l && i.set("language", l), e.prompt && i.set("prompt", e.prompt);
258
+ const w = await f(
259
+ `/app-api/audio/stt?ext=${encodeURIComponent(o)}`,
260
+ {
261
+ method: "POST",
262
+ body: i
263
+ }
264
+ ), s = (w.headers.get("content-type") || "").includes("application/json") ? await w.json() : await w.text();
265
+ if (!w.ok)
266
+ throw new Error(
267
+ typeof s == "string" ? s : ((g = s == null ? void 0 : s.error) == null ? void 0 : g.message) || `Request failed (${w.status})`
268
+ );
269
+ return { text: typeof s == "string" ? s : (s == null ? void 0 : s.text) || (s == null ? void 0 : s.original) || ((a = (m = s == null ? void 0 : s.results) == null ? void 0 : m[0]) == null ? void 0 : a.text) || "", raw: s };
270
+ },
271
+ async voices(e) {
272
+ const r = new URLSearchParams();
273
+ e != null && e.locale && r.set("locale", e.locale);
274
+ const n = await f(
275
+ `/app-api/audio/tts/voices${r.toString() ? `?${r}` : ""}`,
276
+ { method: "GET" }
277
+ ), t = await n.json().catch(() => []);
278
+ if (!n.ok)
279
+ throw new Error(
280
+ (t == null ? void 0 : t.error) || `Request failed (${n.status})`
281
+ );
282
+ return Array.isArray(t) ? t : (t == null ? void 0 : t.voices) || [];
283
+ }
122
284
  },
123
- async chatText(n) {
124
- var c, e, i;
125
- const t = await this.chatCompletions(n);
126
- return ((i = (e = (c = t == null ? void 0 : t.choices) == null ? void 0 : c[0]) == null ? void 0 : e.message) == null ? void 0 : i.content) ?? "";
285
+ data(e = "private") {
286
+ return k(e, "");
127
287
  }
128
288
  };
129
289
  }
130
290
  export {
131
- _ as PromteAppProvider,
132
- y as usePromte,
133
- B as usePromteClient,
134
- L as usePromteSettings,
135
- R as usePromteToken
291
+ z as PromteAppProvider,
292
+ b as usePromte,
293
+ I as usePromteClient,
294
+ N as usePromteDarkMode,
295
+ G as usePromteSettings,
296
+ J as usePromteToken,
297
+ O as usePromteUser
136
298
  };
@@ -1 +1 @@
1
- (function(o,d){typeof exports=="object"&&typeof module<"u"?d(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],d):(o=typeof globalThis<"u"?globalThis:o||self,d(o.PromteAppLibrary={},o.jsxRuntime,o.react))})(this,function(o,d,r){"use strict";const g=r.createContext(null);function E({children:f,expectedParentOrigin:s,initTargetOrigin:p,retryInit:n={enabled:!0,intervalMs:500,maxAttempts:20}}){const[e,l]=r.useState(null),[t,c]=r.useState(null),[w,y]=r.useState(null),P=r.useMemo(()=>w?"booting":e?t?"ready":"waiting_for_token":"waiting_for_settings",[e,t,w]),k=P==="ready",b=r.useMemo(()=>p||s||"*",[p,s]),v=r.useCallback(()=>{var m;try{const u={type:"init"};(m=window.parent)==null||m.postMessage(u,b)}catch(u){y((u==null?void 0:u.message)||"Failed to post init")}},[b]);r.useEffect(()=>{v()},[v]),r.useEffect(()=>{if(!(n!=null&&n.enabled)||e)return;const m=n.intervalMs??500,u=n.maxAttempts??20;let i=0;const a=window.setInterval(()=>{if(e){window.clearInterval(a);return}if(i+=1,i>u){window.clearInterval(a);return}v()},m);return()=>window.clearInterval(a)},[n,e,v]),r.useEffect(()=>{const m=u=>{if(s&&u.origin!==s)return;const i=u.data;if(!(!i||typeof i!="object")){if(i.type==="set-settings"){const a=i.value;if(!(a!=null&&a.backendUrl)||a.parentOrigin&&s&&a.parentOrigin!==s)return;l(a),y(null);return}if(i.type==="set-token"&&typeof i.value=="string"){c(i.value),y(null);return}}};return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[s]);const C=r.useMemo(()=>T(()=>e,()=>t),[e,t]),A=r.useMemo(()=>({settings:e,token:t,ready:k,state:P,error:w,client:C}),[e,t,k,P,w,C]);return d.jsx(g.Provider,{value:A,children:f})}function h(){const f=r.useContext(g);if(!f)throw new Error("usePromte must be used inside <PromteAppProvider>");return f}function M(){return h().settings}function j(){return h().token}function S(){return h().client}function T(f,s){async function p(n,e){const l=f(),t=s();if(!l)throw new Error("Promte settings not received yet");if(!t)throw new Error("Promte token not received yet");const c=new URL(l.backendUrl+"/"+n).toString();return await fetch(c,{...e,headers:{...e.headers||{},Authorization:`Bearer ${t}`}})}return{isReady(){return!!f()&&!!s()},getBackendUrl(){var n;return((n=f())==null?void 0:n.backendUrl)??null},async chatCompletions(n){var c;const e=await p("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,stream:!1})}),t=(e.headers.get("content-type")||"").includes("application/json")?await e.json():await e.text();if(!e.ok)throw new Error(typeof t=="string"?t:((c=t==null?void 0:t.error)==null?void 0:c.message)||`Request failed (${e.status})`);return t},async chatText(n){var l,t,c;const e=await this.chatCompletions(n);return((c=(t=(l=e==null?void 0:e.choices)==null?void 0:l[0])==null?void 0:t.message)==null?void 0:c.content)??""}}}o.PromteAppProvider=E,o.usePromte=h,o.usePromteClient=S,o.usePromteSettings=M,o.usePromteToken=j,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
1
+ (function(f,P){typeof exports=="object"&&typeof module<"u"?P(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],P):(f=typeof globalThis<"u"?globalThis:f||self,P(f.PromteAppLibrary={},f.jsxRuntime,f.react))})(this,function(f,P,c){"use strict";const x=c.createContext(null);function U({children:k,expectedParentOrigin:y,initTargetOrigin:j,retryInit:l={enabled:!0,intervalMs:500,maxAttempts:20}}){const[p,T]=c.useState(null),[m,S]=c.useState(null),[b,e]=c.useState(null),[o,n]=c.useState(null),[t,r]=c.useState(null),a=c.useMemo(()=>t?"booting":p?m?"ready":"waiting_for_token":"waiting_for_settings",[p,m,t]),d=a==="ready",h=c.useMemo(()=>j||y||"*",[j,y]),g=c.useCallback(()=>{var v;try{const w={type:"init"};(v=window.parent)==null||v.postMessage(w,h)}catch(w){r((w==null?void 0:w.message)||"Failed to post init")}},[h]);c.useEffect(()=>{g()},[g]),c.useEffect(()=>{if(!(l!=null&&l.enabled)||p)return;const v=l.intervalMs??500,w=l.maxAttempts??20;let i=0;const u=window.setInterval(()=>{if(p){window.clearInterval(u);return}if(i+=1,i>w){window.clearInterval(u);return}g()},v);return()=>window.clearInterval(u)},[l,p,g]),c.useEffect(()=>{const v=w=>{if(y&&w.origin!==y)return;const i=w.data;if(!(!i||typeof i!="object")){if(i.type==="set-settings"){const u=i.value;if(!(u!=null&&u.backendUrl)||u.parentOrigin&&y&&u.parentOrigin!==y)return;T(u),u!=null&&u.user&&n(u.user),r(null);return}if(i.type==="set-token"&&typeof i.value=="string"){S(i.value),r(null);return}if(i.type==="set-dark-mode"&&typeof i.value=="boolean"){e(i.value);return}if(i.type==="set-user"&&typeof i.value=="object"){n(i.value);return}}};return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[y]);const s=c.useMemo(()=>B(()=>p,()=>m),[p,m]),R=c.useMemo(()=>({settings:p,token:m,isDarkMode:b,user:o,ready:d,state:a,error:t,client:s}),[p,m,b,o,d,a,t,s]);return P.jsx(x.Provider,{value:R,children:k})}function E(){const k=c.useContext(x);if(!k)throw new Error("usePromte must be used inside <PromteAppProvider>");return k}function A(){return E().settings}function D(){return E().token}function L(){return E().isDarkMode}function F(){return E().user}function _(){return E().client}function B(k,y){const j=e=>typeof e=="string"&&e.startsWith("gpt-5");async function l(e,o){const n=k(),t=y();if(!n)throw new Error("Promte settings not received yet");if(!t)throw new Error("Promte token not received yet");const r=new URL(n.backendUrl+"/"+e).toString();return await fetch(r,{...o,headers:{...o.headers||{},Authorization:`Bearer ${t}`}})}async function p(e,o){const n=await l(`/app-api/data/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),t=await n.json().catch(()=>({}));if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return t==null?void 0:t.value}async function T(e){const o=new URLSearchParams;e.scope&&o.set("scope",e.scope),e.path&&o.set("path",e.path);const n=await l(`/app-api/data?${o.toString()}`,{method:"GET"}),t=await n.json().catch(()=>({}));if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return t==null?void 0:t.value}const m=e=>e?e.split("/").map(o=>o.trim()).filter(Boolean).join("/"):"",S=(e,o)=>{const n=m(e),t=m(o);return n?t?`${n}/${t}`:n:t},b=(e,o)=>{const n={scope:e};return{async get(){const t=m(o);return T({...n,path:t||void 0})},async set(t){const r=m(o);return p("set",{...n,path:r||void 0,value:t})},async update(t){if(!t||typeof t!="object")throw new Error("update requires an object");const r={};for(const[a,d]of Object.entries(t)){const h=S(o,a);if(!h)throw new Error("update paths must be non-empty");r[h]=d}return p("update",{...n,updates:r})},async remove(){const t=m(o);return p("remove",{...n,path:t||void 0})},async push(t){const r=m(o);if(!r)throw new Error("push requires a path");return p("array-push",{...n,path:r,value:t})},ref(t){const r=S(o,t);if(!r)throw new Error("ref requires a path");return b(e,r)}}};return{isReady(){return!!k()&&!!y()},getBackendUrl(){var e;return((e=k())==null?void 0:e.backendUrl)??null},async chatCompletions(e){var s;const{reasoningEffort:o,reasoning_effort:n,...t}=e,r=o??n,a={...t,stream:!1};r&&j(e.model)&&(a.reasoning_effort=r);const d=await l("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),g=(d.headers.get("content-type")||"").includes("application/json")?await d.json():await d.text();if(!d.ok)throw new Error(typeof g=="string"?g:((s=g==null?void 0:g.error)==null?void 0:s.message)||`Request failed (${d.status})`);return g},async chatText(e){var n,t,r;const o=await this.chatCompletions(e);return((r=(t=(n=o==null?void 0:o.choices)==null?void 0:n[0])==null?void 0:t.message)==null?void 0:r.content)??""},audio:{async tts(e){var r;const o=(r=e==null?void 0:e.text)==null?void 0:r.trim();if(!o)throw new Error("audio.tts requires non-empty text");const n=await l("/app-api/audio/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:o,voice:e.voice,lang:e.lang})});if(!n.ok){const a=await n.text();throw new Error(a||`Request failed (${n.status})`)}return{audio:await n.arrayBuffer(),contentType:n.headers.get("content-type")}},async stt(e){var v,w,i;if(!(e!=null&&e.file))throw new Error("audio.stt requires a file");const o=u=>{if(!u)return;const C=u.trim();if(!C)return;const M=C.toLowerCase(),$=M.split("-")[0];return $.length===2?$:M},n=typeof File<"u"&&e.file instanceof File,t=n&&e.file.name.split(".").pop()||"webm",r=e.ext||t,a=new FormData;n?a.set("file",e.file):a.set("file",e.file,`audio.${r}`);const d=o(e.language);d&&a.set("language",d),e.prompt&&a.set("prompt",e.prompt);const h=await l(`/app-api/audio/stt?ext=${encodeURIComponent(r)}`,{method:"POST",body:a}),s=(h.headers.get("content-type")||"").includes("application/json")?await h.json():await h.text();if(!h.ok)throw new Error(typeof s=="string"?s:((v=s==null?void 0:s.error)==null?void 0:v.message)||`Request failed (${h.status})`);return{text:typeof s=="string"?s:(s==null?void 0:s.text)||(s==null?void 0:s.original)||((i=(w=s==null?void 0:s.results)==null?void 0:w[0])==null?void 0:i.text)||"",raw:s}},async voices(e){const o=new URLSearchParams;e!=null&&e.locale&&o.set("locale",e.locale);const n=await l(`/app-api/audio/tts/voices${o.toString()?`?${o}`:""}`,{method:"GET"}),t=await n.json().catch(()=>[]);if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return Array.isArray(t)?t:(t==null?void 0:t.voices)||[]}},data(e="private"){return b(e,"")}}}f.PromteAppProvider=U,f.usePromte=E,f.usePromteClient=_,f.usePromteDarkMode=L,f.usePromteSettings=A,f.usePromteToken=D,f.usePromteUser=F,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promte/app-library",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "files": [