@promte/app-library 0.1.0

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.
@@ -0,0 +1,64 @@
1
+ import { default as default_2 } from 'react';
2
+ import { JSX as JSX_2 } from 'react/jsx-runtime';
3
+
4
+ export declare type ChatCompletionsRequest = {
5
+ model: string;
6
+ messages: ChatMessage[];
7
+ stream?: false;
8
+ temperature?: number;
9
+ };
10
+
11
+ export declare type ChatCompletionsResponse = any;
12
+
13
+ export declare type ChatMessage = {
14
+ role: "system" | "user" | "assistant" | "tool";
15
+ content: string;
16
+ };
17
+
18
+ export declare function PromteAppProvider({ children, expectedParentOrigin, initTargetOrigin, retryInit, }: PromteAppProviderProps): JSX_2.Element;
19
+
20
+ export declare type PromteAppProviderProps = {
21
+ children: default_2.ReactNode;
22
+ expectedParentOrigin?: string;
23
+ initTargetOrigin?: string;
24
+ retryInit?: {
25
+ enabled: boolean;
26
+ intervalMs?: number;
27
+ maxAttempts?: number;
28
+ };
29
+ };
30
+
31
+ export declare type PromteClient = {
32
+ isReady(): boolean;
33
+ getBackendUrl(): string | null;
34
+ chatCompletions(req: ChatCompletionsRequest): Promise<ChatCompletionsResponse>;
35
+ chatText(req: ChatCompletionsRequest): Promise<string>;
36
+ };
37
+
38
+ declare type PromteCtxValue = {
39
+ settings: PromteSettings | null;
40
+ token: string | null;
41
+ ready: boolean;
42
+ state: PromteHandshakeState;
43
+ error: string | null;
44
+ client: PromteClient;
45
+ };
46
+
47
+ export declare type PromteHandshakeState = "booting" | "waiting_for_settings" | "waiting_for_token" | "ready";
48
+
49
+ export declare type PromteSettings = {
50
+ workspaceId: string;
51
+ version: number;
52
+ backendUrl: string;
53
+ parentOrigin?: string;
54
+ };
55
+
56
+ export declare function usePromte(): PromteCtxValue;
57
+
58
+ export declare function usePromteClient(): PromteClient;
59
+
60
+ export declare function usePromteSettings(): PromteSettings;
61
+
62
+ export declare function usePromteToken(): string;
63
+
64
+ export { }
package/dist/index.mjs ADDED
@@ -0,0 +1,136 @@
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 }
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;
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");
17
+ }
18
+ }, [b]);
19
+ g(() => {
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);
28
+ return;
29
+ }
30
+ if (s += 1, s > o) {
31
+ window.clearInterval(a);
32
+ return;
33
+ }
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)
45
+ return;
46
+ c(a), p(null);
47
+ return;
48
+ }
49
+ if (s.type === "set-token" && typeof s.value == "string") {
50
+ i(s.value), p(null);
51
+ return;
52
+ }
53
+ }
54
+ };
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(
61
+ () => ({
62
+ settings: t,
63
+ token: e,
64
+ ready: k,
65
+ state: h,
66
+ error: m,
67
+ client: C
68
+ }),
69
+ [t, e, k, h, m, C]
70
+ );
71
+ return /* @__PURE__ */ A(E.Provider, { value: P, children: u });
72
+ }
73
+ function y() {
74
+ const u = U(E);
75
+ if (!u)
76
+ throw new Error("usePromte must be used inside <PromteAppProvider>");
77
+ return u;
78
+ }
79
+ function L() {
80
+ return y().settings;
81
+ }
82
+ function R() {
83
+ return y().token;
84
+ }
85
+ function B() {
86
+ return y().client;
87
+ }
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,
96
+ headers: {
97
+ ...t.headers || {},
98
+ Authorization: `Bearer ${e}`
99
+ }
100
+ });
101
+ }
102
+ return {
103
+ isReady() {
104
+ return !!u() && !!r();
105
+ },
106
+ getBackendUrl() {
107
+ var n;
108
+ return ((n = u()) == null ? void 0 : n.backendUrl) ?? null;
109
+ },
110
+ async chatCompletions(n) {
111
+ var i;
112
+ const t = await f("/openai/chat/completions", {
113
+ method: "POST",
114
+ 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)
118
+ throw new Error(
119
+ typeof e == "string" ? e : ((i = e == null ? void 0 : e.error) == null ? void 0 : i.message) || `Request failed (${t.status})`
120
+ );
121
+ return e;
122
+ },
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) ?? "";
127
+ }
128
+ };
129
+ }
130
+ export {
131
+ _ as PromteAppProvider,
132
+ y as usePromte,
133
+ B as usePromteClient,
134
+ L as usePromteSettings,
135
+ R as usePromteToken
136
+ };
@@ -0,0 +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"})});
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@promte/app-library",
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "./dist/index.umd.cjs",
10
+ "module": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.mjs",
16
+ "require": "./dist/index.umd.cjs"
17
+ }
18
+ },
19
+ "scripts": {
20
+ "build": "tsc && vite build"
21
+ },
22
+ "peerDependencies": {
23
+ "react": "^18.2.0",
24
+ "react-dom": "^18.2.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/react": "^18.0.28",
28
+ "@types/react-dom": "^18.0.11",
29
+ "typescript": "^5.0.2",
30
+ "vite": "^5.4.10",
31
+ "vite-plugin-dts": "^3.7.1"
32
+ }
33
+ }