@bty/feed_app-runtime-sdk 0.0.8 → 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.
package/README.md CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  Runtime SDK for Feed-App pages.
4
4
 
5
- It provides a small set of browser-safe APIs for reading host user context and
6
- calling the Feed-App AI gateway. The package has no root entry; import from the
7
- capability sub-entries directly.
5
+ It provides a small set of browser-safe APIs for reading host user context,
6
+ calling the Feed-App AI gateway, and reaching native device capabilities. The
7
+ package has no root entry; import from the capability sub-entries directly
8
+ (`/user`, `/ai`, `/react`, `/device`).
8
9
 
9
10
  ## Install
10
11
 
@@ -12,6 +13,23 @@ capability sub-entries directly.
12
13
  pnpm add @bty/feed_app-runtime-sdk
13
14
  ```
14
15
 
16
+ ## Failure conventions
17
+
18
+ Two failure styles, split by sub-entry — know which you're calling:
19
+
20
+ | Sub-entry | On failure | Why |
21
+ |---|---|---|
22
+ | `/ai` | **throws** a typed `AiError` subclass | callers must distinguish 401 / 402 / 429 / 4xx / 5xx to react correctly |
23
+ | `/user`, `/device` | **returns an empty value** (never throws) | "no host / denied / cancelled" is a normal runtime state, not an exception — branch on the value |
24
+
25
+ Empty value = `""` for the one string API (`getAuthTokenAsync`), `null`
26
+ everywhere else (`getUserInfoAsync`, every `/device` call). `saveFile` is the
27
+ one richer case — it resolves to `"saved" | "cancelled" | "failed"` so an
28
+ export button can tell a real save from a dismissed dialog.
29
+
30
+ Rule of thumb: wrap `/ai` calls in `try/catch`; branch on the return value for
31
+ `/user` and `/device`.
32
+
15
33
  ## User
16
34
 
17
35
  ```ts
@@ -64,6 +82,14 @@ The AI entry supports:
64
82
  - `AbortSignal` cancellation
65
83
  - Structured AI errors
66
84
 
85
+ > **Media payloads are pass-through.** `images.generate` / `audio.speech.create`
86
+ > / `video.generations.create` forward the body verbatim to the upstream
87
+ > provider — there is no client-side reshaping, and each model has its own
88
+ > shape. The param types only require `model`; build the rest of the body from
89
+ > the model's `parameters.shape` in the runtime model catalog, not from generic
90
+ > OpenAI SDK fields (`quality: 'standard'`, `style: 'vivid'`, … may be ignored
91
+ > or rejected by the target model).
92
+
67
93
  ```ts
68
94
  import {
69
95
  AuthRequiredError,
@@ -109,6 +135,49 @@ varies enough that a generic hook tends to leak abstractions.
109
135
  React is an optional peer dependency. Projects that do not import the `/react`
110
136
  entry do not need to install React.
111
137
 
138
+ ## Device
139
+
140
+ Five host-bridged capabilities, each with a three-layer fallback: native App
141
+ bridge → browser Web API → safe default. Import the `device` namespace, or the
142
+ individual capabilities for tree-shaking.
143
+
144
+ ```ts
145
+ import {
146
+ haptics,
147
+ geolocation,
148
+ sensors,
149
+ camera,
150
+ files,
151
+ } from '@bty/feed_app-runtime-sdk/device'
152
+
153
+ await haptics.impact('medium')
154
+ const pos = await geolocation.getCurrentPosition() // PositionSample | null
155
+ const stop = sensors.watchMotion((s) => console.log(s.accelerationWithGravity))
156
+ const photo = await camera.capturePhoto({ camera: 'back' }) // CapturedPhoto | null
157
+ const picked = await files.pickFiles({ accept: ['image/*'], multiple: true })
158
+ const result = await files.saveFile(blob, 'export.json') // "saved" | "cancelled" | "failed"
159
+ stop() // dispose the motion subscription
160
+ ```
161
+
162
+ Every call returns the safe default (`null`, or `false` for `haptics`) on
163
+ denial / cancel / unavailability — none of them throw. `pickFiles` resolves to
164
+ `{ files: { file, path? }[] }` (path present only on the native bridge),
165
+ `saveFile` to a `FileSaveResult`.
166
+
167
+ Capability detection (synchronous, cheap — gate UI ahead of a call):
168
+
169
+ | Capability | Probe |
170
+ |---|---|
171
+ | Haptics | `haptics.isSupported()` |
172
+ | Geolocation | `geolocation.isSupported()` |
173
+ | Camera | `camera.isSupported()` |
174
+ | Sensors | `sensors.isMotionSupported()` / `sensors.isOrientationSupported()` |
175
+ | Files | `files.isPickerSupported()` (the *modern* picker; plain pick always works) |
176
+
177
+ `requestMotionPermission()`, `capturePhoto()`, `saveFile()`, and `pickFiles()`
178
+ must be called from inside a user-gesture handler (tap / click) — browsers
179
+ silently deny these outside a gesture.
180
+
112
181
  ## Published Files
113
182
 
114
183
  The npm package publishes only built output and this README:
@@ -99,13 +99,9 @@ interface ChatCompletionChunk {
99
99
  [key: string]: unknown;
100
100
  }
101
101
  interface ImageGenerateParams extends ApiRequestOptions {
102
- prompt: string;
103
- model?: string;
104
- n?: number;
105
- size?: string;
106
- quality?: "standard" | "hd";
107
- style?: "vivid" | "natural";
108
- response_format?: "url" | "b64_json";
102
+ /** Required. A concrete backend-allowlisted image model id. */
103
+ model: string;
104
+ /** Provider-shape fields — copy keys from the model's `parameters.shape`. */
109
105
  [key: string]: unknown;
110
106
  }
111
107
  interface ImageGenerateResponse {
@@ -115,20 +111,18 @@ interface ImageGenerateResponse {
115
111
  b64_json?: string;
116
112
  revised_prompt?: string;
117
113
  }[];
114
+ [key: string]: unknown;
118
115
  }
119
116
  interface AudioSpeechCreateParams extends ApiRequestOptions {
117
+ /** Required. A concrete backend-allowlisted TTS model id. */
120
118
  model: string;
121
- input: string;
122
- voice: string;
123
- response_format?: "mp3" | "opus" | "aac" | "flac" | "wav" | "pcm";
124
- speed?: number;
119
+ /** Provider-shape fields — copy keys from the model's `parameters.shape`. */
125
120
  [key: string]: unknown;
126
121
  }
127
122
  interface VideoGenerateParams extends ApiRequestOptions {
128
- prompt: string;
129
- model?: string;
130
- duration?: number;
131
- size?: string;
123
+ /** Required. A concrete backend-allowlisted video model id. */
124
+ model: string;
125
+ /** Provider-shape fields — copy keys from the model's `parameters.shape`. */
132
126
  [key: string]: unknown;
133
127
  }
134
128
  interface VideoGenerateResponse {
package/dist/ai/index.js CHANGED
@@ -1,3 +1,2 @@
1
- import {c as c$1,a,b as b$1}from'../chunk-IOHVFMVA.js';var M={version:"0.0.8"};var f="/v1/feed-app/runtime/ai",w=`${f}/chat/completions`,P=`${f}/messages`,D=`${f}/images/generations`,U=`${f}/audio/speech`,j=`${f}/video/generations`,G="Authorization",q="x-bty-extend",J="x-bty-app",V=M.version;var Z=/\r\n|\r|\n/,ee=(()=>{let e=new TextDecoder;return (t,r)=>e.decode(t,{stream:r})})();async function*L(e){let t=e.getReader(),r="",n="",o=[],a=()=>{if(o.length===0&&!n)return null;let m={event:n||"message",data:o.join(`
2
- `)};return n="",o=[],m};try{for(;;){let{done:m,value:h}=await t.read();if(m){let i=a();i&&(yield i);return}for(r+=ee(h,!0);;){let i=Z.exec(r);if(!i)break;let p=r.slice(0,i.index);if(r=r.slice(i.index+i[0].length),p===""){let v=a();v&&(yield v);continue}if(p.startsWith(":"))continue;let y=p.indexOf(":"),I=y===-1?p:p.slice(0,y),l=y===-1?"":p.slice(y+1);l.startsWith(" ")&&(l=l.slice(1)),I==="event"?n=l:I==="data"&&o.push(l);}}}finally{t.releaseLock();}}async function*$(e){for await(let t of L(e)){if(t.data==="[DONE]")return;t.data&&(yield JSON.parse(t.data));}}async function*F(e){for await(let t of L(e))t.data&&(yield JSON.parse(t.data));}var te="https://reactus-api.betteryeah.com",Y=e=>{try{let t=e();if(typeof t=="string"&&t.length>0)return t}catch{}},re=()=>Y(()=>typeof __BTY_RUNTIME_API_BASE_URL__=="string"?__BTY_RUNTIME_API_BASE_URL__:void 0),ne=()=>Y(()=>typeof __BTY_RUNTIME_PROJECT_ID__=="string"?__BTY_RUNTIME_PROJECT_ID__:void 0),S={apiBaseUrl:(re()??te).replace(/\/+$/,""),projectId:ne()??""},oe=e=>{S={...S,...e,...e.apiBaseUrl?{apiBaseUrl:e.apiBaseUrl.replace(/\/+$/,"")}:{}};},A=()=>S;var s=class extends Error{status;code;body;constructor(t,r,n,o=null){super(t),this.name="AiError",this.code=r,this.status=n,this.body=o;}},c=class extends s{constructor(t="Auth required",r=null){super(t,"auth_required",401,r),this.name="AuthRequiredError";}},R=class extends s{constructor(t="Rate limit exceeded",r=null){super(t,"rate_limit",429,r),this.name="RateLimitError";}},C=class extends s{constructor(t="Quota exceeded",r=null){super(t,"quota_exceeded",402,r),this.name="QuotaExceededError";}},E=class extends s{constructor(t,r=400,n=null){super(t,"bad_input",r,n),this.name="BadInputError";}},x=class extends s{constructor(t,r=500,n=null){super(t,"server",r,n),this.name="ServerError";}},d=class extends s{constructor(t="Network error",r){super(t,"network",-1,r),this.name="NetworkError";}},g=class extends s{constructor(t="Request aborted"){super(t,"aborted",-1,null),this.name="AbortedError";}},K=e=>typeof e=="object"&&e!==null,se=(e,t)=>{if(typeof e=="string")return e||t;if(!K(e))return t;let r=e.message;if(typeof r=="string"&&r.length>0)return r;let n=e.error;if(typeof n=="string"&&n.length>0)return n;if(K(n)&&typeof n.message=="string"&&n.message.length>0)return n.message;let o=e.detail;return typeof o=="string"&&o.length>0?o:t},b=(e,t)=>{let r=se(t,`HTTP ${e}`);return e===401||e===403?new c(r,t):e===402?new C(r,t):e===429?new R(r,t):e>=400&&e<500?new E(r,e,t):e>=500?new x(r,e,t):new s(r,"unknown",e,t)};var ae=e=>JSON.stringify({"sdk-version":V,...e}),Q=async(e={})=>{let t=await b$1(),r=new Headers;t&&r.set(G,`Bearer ${t}`),r.set(q,ae(e.extend));let{projectId:n}=A();if(n&&r.set(J,n),e.contentType&&r.set("Content-Type",e.contentType),e.accept&&r.set("Accept",e.accept),e.extra)for(let[o,a]of Object.entries(e.extra))r.set(o,a);return r};var ie="feed-app-runtime-sdk:auth-required",k=e=>{a()&&window.dispatchEvent(new CustomEvent(ie,{detail:e}));};var ce=e=>e instanceof DOMException&&e.name==="AbortError",pe=async e=>{let t=e.headers.get("content-type")??"";try{return t.includes("application/json")?await e.json():await e.text()}catch{return null}},de=e=>typeof e=="object"&&e!==null,ue=(e,t)=>{if(!de(e)||typeof e.success!="boolean")return e;if(e.success)return e.data;let r=typeof e.code=="number"?e.code:t;throw b(r,e)},W=async(e,t)=>{let{apiBaseUrl:r}=A(),n=`${r}${e}`,o=await Q(t),a;try{a=await fetch(n,{method:t.method??"POST",headers:o,body:t.body,signal:t.signal});}catch(h){throw ce(h)?new g:new d("Failed to reach AI backend",h)}if(a.ok)return a;let m=await pe(a);throw b(a.status,m)},O=async(e,t={})=>{try{return await W(e,t)}catch(r){if(r instanceof c&&!t.skipAuthRetry&&!t.signal?.aborted){if(!await c$1())throw k({reason:"refresh_failed",error:r}),r;try{return await W(e,{...t,skipAuthRetry:!0})}catch(o){throw o instanceof c&&k({reason:"retry_rejected",error:o}),o}}throw r}},u=async(e,t,r={})=>{let n=await O(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)});return ue(await n.json(),n.status)};var _=async(e,t,r={})=>{let n=await O(e,{...r,method:"POST",contentType:"application/json",accept:"text/event-stream",body:JSON.stringify(t)});if(!n.body)throw new d("Streaming response has no body");return n.body},X=async(e,t,r={})=>await(await O(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)})).blob();var T=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},me=(async e=>{let{transport:t,payload:r}=T(e);if(e.stream){let n=await _(w,r,t);return $(n)}return await u(w,r,t)}),le={create:me},fe={async generate(e){let{transport:t,payload:r}=T(e);return u(D,r,t)}},ge={speech:{async create(e){let{transport:t,payload:r}=T(e);return X(U,r,t)}}},he={generations:{async create(e){let{transport:t,payload:r}=T(e);return u(j,r,t)}}},ye={chat:{completions:le},images:fe,audio:ge,video:he};var Ae=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},Re=(async e=>{let{transport:t,payload:r}=Ae(e);if(e.stream){let n=await _(P,r,t);return F(n)}return await u(P,r,t)}),Ce={messages:{create:Re}};
3
- export{g as AbortedError,s as AiError,c as AuthRequiredError,E as BadInputError,d as NetworkError,C as QuotaExceededError,R as RateLimitError,x as ServerError,Ce as anthropic,oe as configureRuntime,ye as openai};
1
+ import {d as d$1,c}from'../chunk-AKZVV563.js';import {a}from'../chunk-ALNJCFV4.js';import {createParser}from'eventsource-parser';var O={version:"0.1.0"};var m="/v1/feed-app/runtime/ai",E=`${m}/chat/completions`,_=`${m}/messages`,v=`${m}/images/generations`,I=`${m}/audio/speech`,B=`${m}/video/generations`,M="Authorization",H="x-bty-extend",N="x-bty-app",D=O.version;var j=()=>{};async function*U(e){let t=e.getReader(),r=new TextDecoder,n=[],s=createParser({onEvent(c){n.push({event:c.event||"message",data:c.data});},onRetry:j,onComment:j}),a=false;try{for(;;){let{done:c,value:u}=await t.read();for(u&&s.feed(r.decode(u,{stream:!0}));n.length>0;)yield n.shift();if(c){for(s.reset({consume:!0});n.length>0;)yield n.shift();a=!0;return}}}finally{if(!a)try{await t.cancel();}catch{}t.releaseLock();}}async function*G(e){for await(let t of U(e)){if(t.data==="[DONE]")return;t.data&&(yield JSON.parse(t.data));}}async function*q(e){for await(let t of U(e))t.data&&(yield JSON.parse(t.data));}var Q="https://reactus-api.happyseeds.ai",J=e=>{try{let t=e();if(typeof t=="string"&&t.length>0)return t}catch{}},X=()=>J(()=>typeof __BTY_RUNTIME_API_BASE_URL__=="string"?__BTY_RUNTIME_API_BASE_URL__:void 0),z=()=>J(()=>typeof __BTY_RUNTIME_PROJECT_ID__=="string"?__BTY_RUNTIME_PROJECT_ID__:void 0),T={apiBaseUrl:(X()??Q).replace(/\/+$/,""),projectId:z()??""},W=e=>{T={...T,...e,...e.apiBaseUrl?{apiBaseUrl:e.apiBaseUrl.replace(/\/+$/,"")}:{}};},f=()=>T;var o=class extends Error{status;code;body;constructor(t,r,n,s=null){super(t),this.name="AiError",this.code=r,this.status=n,this.body=s;}},i=class extends o{constructor(t="Auth required",r=null){super(t,"auth_required",401,r),this.name="AuthRequiredError";}},h=class extends o{constructor(t="Rate limit exceeded",r=null){super(t,"rate_limit",429,r),this.name="RateLimitError";}},g=class extends o{constructor(t="Quota exceeded",r=null){super(t,"quota_exceeded",402,r),this.name="QuotaExceededError";}},y=class extends o{constructor(t,r=400,n=null){super(t,"bad_input",r,n),this.name="BadInputError";}},A=class extends o{constructor(t,r=500,n=null){super(t,"server",r,n),this.name="ServerError";}},p=class extends o{constructor(t="Network error",r){super(t,"network",-1,r),this.name="NetworkError";}},l=class extends o{constructor(t="Request aborted"){super(t,"aborted",-1,null),this.name="AbortedError";}},V=e=>typeof e=="object"&&e!==null,Z=(e,t)=>{if(typeof e=="string")return e||t;if(!V(e))return t;let r=e.message;if(typeof r=="string"&&r.length>0)return r;let n=e.error;if(typeof n=="string"&&n.length>0)return n;if(V(n)&&typeof n.message=="string"&&n.message.length>0)return n.message;let s=e.detail;return typeof s=="string"&&s.length>0?s:t},x=(e,t)=>{let r=Z(t,`HTTP ${e}`);return e===401||e===403?new i(r,t):e===402?new g(r,t):e===429?new h(r,t):e>=400&&e<500?new y(r,e,t):e>=500?new A(r,e,t):new o(r,"unknown",e,t)};var ee=e=>JSON.stringify({"sdk-version":D,...e}),$=async(e={})=>{let t=await c(),r=new Headers;t&&r.set(M,`Bearer ${t}`),r.set(H,ee(e.extend));let{projectId:n}=f();if(n&&r.set(N,n),e.contentType&&r.set("Content-Type",e.contentType),e.accept&&r.set("Accept",e.accept),e.extra)for(let[s,a]of Object.entries(e.extra))r.set(s,a);return r};var te="feed-app-runtime-sdk:auth-required",w=e=>{a()&&window.dispatchEvent(new CustomEvent(te,{detail:e}));};var re=e=>e instanceof DOMException&&e.name==="AbortError",ne=async e=>{let t=e.headers.get("content-type")??"";try{return t.includes("application/json")?await e.json():await e.text()}catch{return null}},se=e=>typeof e=="object"&&e!==null,oe=(e,t)=>{if(!se(e)||typeof e.success!="boolean")return e;if(e.success)return e.data;let r=typeof e.code=="number"?e.code:t;throw x(r,e)},L=async(e,t)=>{let{apiBaseUrl:r}=f(),n=`${r}${e}`,s=await $(t),a;try{a=await fetch(n,{method:t.method??"POST",headers:s,body:t.body,signal:t.signal});}catch(u){throw re(u)?new l:new p("Failed to reach AI backend",u)}if(a.ok)return a;let c=await ne(a);throw x(a.status,c)},P=async(e,t={})=>{try{return await L(e,t)}catch(r){if(r instanceof i&&!t.skipAuthRetry&&!t.signal?.aborted){if(!await d$1())throw w({reason:"refresh_failed",error:r}),r;try{return await L(e,{...t,skipAuthRetry:!0})}catch(s){throw s instanceof i&&w({reason:"retry_rejected",error:s}),s}}throw r}},d=async(e,t,r={})=>{let n=await P(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)});return oe(await n.json(),n.status)};var C=async(e,t,r={})=>{let n=await P(e,{...r,method:"POST",contentType:"application/json",accept:"text/event-stream",body:JSON.stringify(t)});if(!n.body)throw new p("Streaming response has no body");return n.body},F=async(e,t,r={})=>await(await P(e,{...r,method:"POST",contentType:"application/json",body:JSON.stringify(t)})).blob();var R=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},ae=(async e=>{let{transport:t,payload:r}=R(e);if(e.stream){let n=await C(E,r,t);return G(n)}return await d(E,r,t)}),ie={create:ae},ce={async generate(e){let{transport:t,payload:r}=R(e);return d(v,r,t)}},pe={speech:{async create(e){let{transport:t,payload:r}=R(e);return F(I,r,t)}}},de={generations:{async create(e){let{transport:t,payload:r}=R(e);return d(B,r,t)}}},ue={chat:{completions:ie},images:ce,audio:pe,video:de};var me=e=>{let{signal:t,headers:r,...n}=e;return {transport:{signal:t,extra:r},payload:n}},le=(async e=>{let{transport:t,payload:r}=me(e);if(e.stream){let n=await C(_,r,t);return q(n)}return await d(_,r,t)}),fe={messages:{create:le}};
2
+ export{l as AbortedError,o as AiError,i as AuthRequiredError,y as BadInputError,p as NetworkError,g as QuotaExceededError,h as RateLimitError,A as ServerError,fe as anthropic,W as configureRuntime,ue as openai};
@@ -0,0 +1 @@
1
+ import {a as a$1,b,j as j$1,d,f,g,k,o,m,v,q,x,e,s,r,w,c as c$1,p,l,n,h,i}from'./chunk-ALNJCFV4.js';var E=e=>typeof e=="object"&&e!==null,a=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0)return r}},$=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0||typeof r=="number"&&Number.isFinite(r))return r}},u=e=>{if(!E(e))return null;let n=E(e.credentials)?e.credentials:void 0,t=E(e.user)?e.user:void 0,r=a(e,["uid","userId","id"])??a(n,["uid","userId","id"])??a(t,["uid","userId","id"]),o=a(e,["token","authToken"])??a(n,["token","authToken"]);return !r||!o?null:{uid:r,token:o}},c=e=>{if(!E(e))return null;let n=E(e.data)?e.data:e,t=$(n,["userId","id","uid"]);if(t===void 0)return null;let r=a(n,["username","nickname","nickName","name"]),o=a(n,["nickname","nickName","username"]);return {...n,userId:t,...r?{username:r}:{},...o?{nickname:o}:{}}};var ee=e=>typeof e!="object"||e===null?false:typeof Reflect.get(e,"type")=="string",H=false,V=()=>{!a$1()||H||(H=true,d(),Reflect.set(window,f,e=>{u(e)&&b.emit(j$1,e);}),Reflect.set(window,g,e=>{c(e)&&b.emit(k,e);}),window.addEventListener("message",e=>{let n=e.data;if(ee(n))switch(n.type){case m:b.emit("iframe.credentials",n);break;case o:b.emit("iframe.userinfo",n);break}}));};var j=(e,n,t)=>new Promise(r=>{let o=false,f=i=>{o||(o=true,y(),clearTimeout(T),r(i));},y=b.on(n,i=>{let g=t(i);g&&f(g);}),T=setTimeout(()=>f(null),q);try{window.parent.postMessage({type:e,timestamp:Date.now()},"*");}catch{f(null);}}),G=()=>j(l,"iframe.credentials",u),Q=()=>j(n,"iframe.userinfo",c);var J=async(e$1,n,t,r$1)=>{let o=e$1.platform==="Android"?await x(e,{pollIntervalMs:r,timeoutMs:s}):w(e);if(!o)return null;let f=c$1(t);return new Promise(y=>{let T=false,i=d=>{T||(T=true,g(),Y(),clearTimeout(Z),y(d));},g=b.on(f,d=>{let p=r$1(d);p&&i(p);}),Y=b.on(t,d=>{let p=r$1(d);p&&i(p);}),Z=setTimeout(()=>i(null),p);try{o.postMessage({command:n,parameters:JSON.stringify({timestamp:Date.now(),endpoint:f})});}catch{i(null);}})},z=e=>J(e,h,j$1,u),K=e=>J(e,i,k,c);V();var C=null,I=null,R=new Set,ne=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?z(e):Promise.resolve(null);case "iframe":return G();case "web":return Promise.resolve(null)}},re=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?K(e):Promise.resolve(null);case "iframe":return Q();case "web":return Promise.resolve(null)}},W=e=>{let n=C?.token??"",t=e?.token??"";if(C=e,n!==t)for(let r of R)try{r();}catch{}},Ne=()=>C?.token??"",ve=e=>(R.add(e),()=>{R.delete(e);}),X=()=>I||(I=ne(v()).then(e=>(e&&W(e),e)).finally(()=>{I=null;}),I);a$1()&&b.on(j$1,e=>{let n=u(e);n&&W(n);});var te=async()=>a$1()?C?C.token:(await X())?.token??"":"",Pe=async()=>a$1()?(await X())?.token??"":"",se=async()=>a$1()?re(v()):null;export{Ne as a,ve as b,te as c,Pe as d,se as e};
@@ -0,0 +1 @@
1
+ var o=()=>typeof window<"u"&&typeof document<"u";var _="hostRuntime",p=class{listeners=new Map;on(e,t){let s=this.listeners.get(e),r=s??new Set;return s||this.listeners.set(e,r),r.add(t),()=>{r.delete(t),r.size===0&&this.listeners.delete(e);}}emit(e,t){let s=this.listeners.get(e);if(s)for(let r of s)r(t);}},R=new p,a=0,A=n=>(a+=1,`${n}.${a}`),l=false,I=()=>{if(!o()||l)return;l=true,Reflect.set(window,_,{receiveMessage(e){if(!e)return;let t=e.endpoint;t&&R.emit(t,e.data??e);}});};var E="HostApp",v="hostListener";var O="processUserCredentials",L="processUserInfo",H="user.getCredentials",b="user.getUserInfo",P="user.credentials",U="user.info",k="user-credentials-request",y="user-credentials-response",F="user-info-request",h="user-info-response",f={iOS:[1,6,7],Android:[1,1,8]},C=3e3,D=500,V=50,B=1500;var d=n=>{let e=n.split(".").map(t=>Number.parseInt(t,10));return [e[0]??0,e[1]??0,e[2]??0]},m=(n,e)=>{for(let t=0;t<3;t++){if(n[t]>e[t])return true;if(n[t]<e[t])return false}return true};var N=new RegExp(`${E}\\/(\\d+\\.\\d+\\.\\d+)\\/(\\d+)\\/(iOS|Android)`),g=n=>{let e=n.match(N);if(!e)return null;let[,t,s,r]=e;if(!t||!s||r!=="iOS"&&r!=="Android")return null;let i=m(d(t),f[r]);return {type:"native_app",platform:r,appVersion:t,buildNumber:s,meetsMinVersion:i}},Q=()=>{if(!o())return {type:"web",meetsMinVersion:false};let n=g(navigator.userAgent??"");return n||(window.parent!==window?{type:"iframe",meetsMinVersion:false}:{type:"web",meetsMinVersion:false})};var S=n=>typeof n!="object"||n===null?false:typeof Reflect.get(n,"postMessage")=="function",T=n=>{let e=Reflect.get(window,"webkit");if(typeof e=="object"&&e!==null){let s=Reflect.get(e,"messageHandlers");if(typeof s=="object"&&s!==null){let r=Reflect.get(s,n);if(S(r))return r}}let t=Reflect.get(window,n);return S(t)?t:null},X=(n,e={})=>{let{pollIntervalMs:t=50,timeoutMs:s=1500}=e;return new Promise(r=>{let i=Date.now(),u=()=>{let c=T(n);if(c){r(c);return}if(Date.now()-i>=s){r(null);return}setTimeout(u,t);};u();})};export{o as a,R as b,A as c,I as d,v as e,O as f,L as g,H as h,b as i,P as j,U as k,k as l,y as m,F as n,h as o,C as p,D as q,V as r,B as s,d as t,m as u,Q as v,T as w,X as x};
@@ -0,0 +1,270 @@
1
+ import { A as AppEnvironment } from '../types-DryABknE.js';
2
+
3
+ type HapticImpactStrength = "light" | "medium" | "heavy" | "soft" | "rigid";
4
+ type HapticNotificationKind = "success" | "warning" | "error";
5
+ interface PositionRequestOptions {
6
+ enableHighAccuracy?: boolean;
7
+ timeoutMs?: number;
8
+ maximumAgeMs?: number;
9
+ }
10
+ interface PositionSample {
11
+ latitude: number;
12
+ longitude: number;
13
+ accuracyMeters: number;
14
+ altitudeMeters?: number;
15
+ altitudeAccuracyMeters?: number;
16
+ headingDegrees?: number;
17
+ speedMetersPerSecond?: number;
18
+ timestamp: number;
19
+ }
20
+ interface Vector3 {
21
+ x: number;
22
+ y: number;
23
+ z: number;
24
+ }
25
+ interface MotionSample {
26
+ acceleration?: Vector3;
27
+ accelerationWithGravity: Vector3;
28
+ rotationRate: {
29
+ alpha: number;
30
+ beta: number;
31
+ gamma: number;
32
+ };
33
+ attitude?: {
34
+ yaw: number;
35
+ pitch: number;
36
+ roll: number;
37
+ };
38
+ timestamp: number;
39
+ }
40
+ interface OrientationSample {
41
+ alpha: number;
42
+ beta: number;
43
+ gamma: number;
44
+ timestamp: number;
45
+ }
46
+ interface MotionWatchOptions {
47
+ autoRequestPermission?: boolean;
48
+ }
49
+ type CameraFacing = "front" | "back";
50
+ type PhotoQuality = "low" | "medium" | "high";
51
+ type PhotoFormat = "jpeg" | "png" | "webp";
52
+ interface PhotoCaptureOptions {
53
+ quality?: PhotoQuality;
54
+ format?: PhotoFormat;
55
+ width?: number;
56
+ height?: number;
57
+ camera?: CameraFacing;
58
+ }
59
+ interface CapturedPhoto {
60
+ blob: Blob;
61
+ dataUrl: string;
62
+ width: number;
63
+ height: number;
64
+ }
65
+ interface StreamOptions {
66
+ camera?: CameraFacing;
67
+ width?: number;
68
+ height?: number;
69
+ }
70
+ interface PickFilesOptions {
71
+ accept?: string[];
72
+ multiple?: boolean;
73
+ directory?: boolean;
74
+ }
75
+ interface PickedFile {
76
+ file: File;
77
+ path?: string;
78
+ }
79
+ interface PickedFiles {
80
+ files: PickedFile[];
81
+ }
82
+ type FileSaveResult = "saved" | "cancelled" | "failed";
83
+
84
+ declare const camera: {
85
+ isSupported(): boolean;
86
+ /**
87
+ * Open the camera, capture one photo, close the stream. The native bridge
88
+ * variant runs the host App's full-screen capture UI (better quality, save
89
+ * to gallery, etc.); the web fallback does a headless `getUserMedia +
90
+ * canvas` shot. Returns null on permission denial, hardware absence, or
91
+ * any failure on either path.
92
+ *
93
+ * Must be called inside a user-gesture handler to satisfy autoplay /
94
+ * permission requirements on iOS Safari and modern Android browsers.
95
+ */
96
+ capturePhoto(opts?: PhotoCaptureOptions): Promise<CapturedPhoto | null>;
97
+ /**
98
+ * Open a live MediaStream — for QR scanning, AR overlays, or any case
99
+ * where a single still photo is not enough. Web-only by design: streaming
100
+ * raw video frames through a JS bridge is impractical, and host Apps that
101
+ * need camera access usually push it through capturePhoto's full-screen UI
102
+ * instead.
103
+ *
104
+ * Returns null when getUserMedia is unavailable or the user denies access.
105
+ * Caller must invoke `camera.stopStream(stream)` when done.
106
+ */
107
+ openStream(opts?: StreamOptions): Promise<MediaStream | null>;
108
+ stopStream(stream: MediaStream): void;
109
+ };
110
+
111
+ declare const files: {
112
+ /**
113
+ * Whether the modern picker (File System Access API or native bridge) is
114
+ * available. False does not mean files cannot be picked — `<input
115
+ * type=file>` still works in any browser via the lib's legacy fallback; it
116
+ * just lacks path / write-back.
117
+ */
118
+ isPickerSupported(): boolean;
119
+ /**
120
+ * Pick one or more files. Returns null on user cancel or unavailability.
121
+ * Each entry is a `{ file, path? }` — `path` is set only when the native
122
+ * bridge serves the request; web fallbacks have no path concept and omit
123
+ * it. Pairing path with its file avoids the index drift a separate
124
+ * `paths[]` array invites.
125
+ */
126
+ pickFiles(opts?: PickFilesOptions): Promise<PickedFiles | null>;
127
+ /**
128
+ * Save a Blob to a file the user nominates. Native handler can prompt for
129
+ * a directory and write in place; web fallback uses the File System Access
130
+ * save dialog when available, otherwise triggers an anchor download.
131
+ *
132
+ * Resolves to a `FileSaveResult` — `"saved"` on success, `"cancelled"` when
133
+ * the user dismisses the dialog, `"failed"` on any error or unavailable
134
+ * environment. Never throws, so a "Export" button can branch on the outcome
135
+ * (toast on saved, stay quiet on cancelled, error hint on failed) instead of
136
+ * assuming success. There is no progress callback — web Blobs write
137
+ * atomically.
138
+ */
139
+ saveFile(blob: Blob, filename: string): Promise<FileSaveResult>;
140
+ /**
141
+ * Read the contents of a File / Blob as a UTF-8 string. Pure web — does
142
+ * not consult the native bridge. The blob already lives in the page's
143
+ * memory by the time this is called.
144
+ */
145
+ readAsText(file: File | Blob): Promise<string>;
146
+ /**
147
+ * Read the contents of a File / Blob as a base64 data URL — useful for
148
+ * `<img src>` previews. Pure web.
149
+ */
150
+ readAsDataUrl(file: File | Blob): Promise<string>;
151
+ };
152
+
153
+ declare const geolocation: {
154
+ isSupported(): boolean;
155
+ /**
156
+ * Single position read. Returns null on permission denial, timeout, or
157
+ * absence of geolocation hardware. Default timeout is the browser/native
158
+ * default; pass `timeoutMs` to override.
159
+ */
160
+ getCurrentPosition(opts?: PositionRequestOptions): Promise<PositionSample | null>;
161
+ /**
162
+ * Continuous position updates. Returns a synchronous cleanup function —
163
+ * native subscription may be still warming up; cleanup is safe to call
164
+ * before that resolves, the subscription will be torn down as soon as it
165
+ * is installed.
166
+ */
167
+ watchPosition(onSample: (sample: PositionSample) => void, opts?: PositionRequestOptions): () => void;
168
+ };
169
+
170
+ declare const haptics: {
171
+ /**
172
+ * Whether at least one path can fire haptics in the current environment.
173
+ * Conservative — returns true if `navigator.vibrate` exists OR we're inside
174
+ * a native_app host. Does not guarantee any specific call will succeed
175
+ * (permissions, hardware capabilities, native version, ...).
176
+ */
177
+ isSupported(): boolean;
178
+ /**
179
+ * Tactile "tap" feedback. Maps to UIImpactFeedbackGenerator on iOS and
180
+ * VibrationEffect.EFFECT_CLICK / EFFECT_HEAVY_CLICK on Android (native
181
+ * bridge); a short navigator.vibrate pulse on the web. Default `medium`.
182
+ */
183
+ impact(strength?: HapticImpactStrength): Promise<void>;
184
+ /**
185
+ * "Tick" feedback for changing a selected item (segmented control, picker).
186
+ * Maps to UISelectionFeedbackGenerator on iOS; a very short pulse on web.
187
+ */
188
+ selection(): Promise<void>;
189
+ /**
190
+ * Status feedback after a discrete action (form submit, transaction).
191
+ * Maps to UINotificationFeedbackGenerator on iOS; a small multi-segment
192
+ * pattern on web.
193
+ */
194
+ notification(kind: HapticNotificationKind): Promise<void>;
195
+ /**
196
+ * Low-level Android-style pattern. Number = single pulse in ms; array =
197
+ * alternating vibrate/pause durations. Native bridge forwards verbatim;
198
+ * iOS handler may approximate by mapping pattern length/intensity to its
199
+ * Impact generator.
200
+ */
201
+ vibrate(pattern: number | number[]): Promise<void>;
202
+ };
203
+
204
+ declare const sensors: {
205
+ isMotionSupported(): boolean;
206
+ isOrientationSupported(): boolean;
207
+ /**
208
+ * Ask the host (native App or iOS Safari) for permission to read motion
209
+ * data. **Must be called inside a user-gesture handler on iOS Safari** —
210
+ * a non-gesture invocation silently resolves to false. The native-bridge
211
+ * variant has no such gesture requirement because the App's own iOS
212
+ * permission prompt is independent of the web view's gesture stack.
213
+ */
214
+ requestMotionPermission(): Promise<boolean>;
215
+ /**
216
+ * Subscribe to device motion samples. Native handler streams sensor-rate
217
+ * data through the bridge; web fallback uses the `devicemotion` event.
218
+ *
219
+ * iOS Safari requires a permission grant before the event fires. Pass
220
+ * `autoRequestPermission: true` from inside a click handler if you want
221
+ * the subscription to also request permission as part of setup.
222
+ */
223
+ watchMotion(onSample: (s: MotionSample) => void, opts?: MotionWatchOptions): () => void;
224
+ /**
225
+ * Subscribe to device orientation samples. Mirrors watchMotion but uses
226
+ * the `deviceorientation` event on the web fallback path.
227
+ */
228
+ watchOrientation(onSample: (s: OrientationSample) => void): () => void;
229
+ };
230
+
231
+ type DeviceFeature = "haptics" | "geolocation" | "sensors" | "camera" | "files";
232
+
233
+ declare const meetsFeatureMinVersion: (feature: DeviceFeature, env: AppEnvironment) => boolean;
234
+
235
+ declare const device: {
236
+ readonly haptics: {
237
+ isSupported(): boolean;
238
+ impact(strength?: HapticImpactStrength): Promise<void>;
239
+ selection(): Promise<void>;
240
+ notification(kind: HapticNotificationKind): Promise<void>;
241
+ vibrate(pattern: number | number[]): Promise<void>;
242
+ };
243
+ readonly geolocation: {
244
+ isSupported(): boolean;
245
+ getCurrentPosition(opts?: PositionRequestOptions): Promise<PositionSample | null>;
246
+ watchPosition(onSample: (sample: PositionSample) => void, opts?: PositionRequestOptions): () => void;
247
+ };
248
+ readonly sensors: {
249
+ isMotionSupported(): boolean;
250
+ isOrientationSupported(): boolean;
251
+ requestMotionPermission(): Promise<boolean>;
252
+ watchMotion(onSample: (s: MotionSample) => void, opts?: MotionWatchOptions): () => void;
253
+ watchOrientation(onSample: (s: OrientationSample) => void): () => void;
254
+ };
255
+ readonly camera: {
256
+ isSupported(): boolean;
257
+ capturePhoto(opts?: PhotoCaptureOptions): Promise<CapturedPhoto | null>;
258
+ openStream(opts?: StreamOptions): Promise<MediaStream | null>;
259
+ stopStream(stream: MediaStream): void;
260
+ };
261
+ readonly files: {
262
+ isPickerSupported(): boolean;
263
+ pickFiles(opts?: PickFilesOptions): Promise<PickedFiles | null>;
264
+ saveFile(blob: Blob, filename: string): Promise<FileSaveResult>;
265
+ readAsText(file: File | Blob): Promise<string>;
266
+ readAsDataUrl(file: File | Blob): Promise<string>;
267
+ };
268
+ };
269
+
270
+ export { type CameraFacing, type CapturedPhoto, type DeviceFeature, type HapticImpactStrength, type HapticNotificationKind, type MotionSample, type MotionWatchOptions, type OrientationSample, type PhotoCaptureOptions, type PhotoFormat, type PhotoQuality, type PickFilesOptions, type PickedFiles, type PositionRequestOptions, type PositionSample, type StreamOptions, type Vector3, camera, device, files, geolocation, haptics, meetsFeatureMinVersion, sensors };
@@ -0,0 +1 @@
1
+ import {a,d as d$1,u,t,v,c,b,x,e,s,r,w}from'../chunk-ALNJCFV4.js';import {fileSave,directoryOpen,fileOpen}from'browser-fs-access';var L=false,S=()=>{!a()||L||(L=true,d$1());};var B="device.haptics",M="device.geolocation",H="device.sensors.motion",V="device.sensors.orientation",W="device.sensors.permission",G="device.camera",R="device.files",q="device.haptics.impact",j="device.haptics.selection",z="device.haptics.notification",K="device.haptics.vibrate",Q="device.geolocation.get",J="device.geolocation.watch.start",Y="device.geolocation.watch.stop",$="device.sensors.motion.start",X="device.sensors.motion.stop",Z="device.sensors.orientation.start",ee="device.sensors.orientation.stop",te="device.sensors.requestPermission",ne="device.camera.capture",oe="device.files.pick",ie="device.files.save";var re={haptics:{iOS:null,Android:null},geolocation:{iOS:null,Android:null},sensors:{iOS:null,Android:null},camera:{iOS:null,Android:null},files:{iOS:null,Android:null}};var C=(e,t$1)=>{if(t$1.type!=="native_app"||!t$1.platform||!t$1.appVersion)return false;let n=re[e][t$1.platform];return n?u(t(t$1.appVersion),n):false},I=e=>JSON.stringify(e),ae=(e,t)=>{if(typeof e!="object"||e===null||Reflect.get(e,"ok")!==true)return null;let o=Reflect.get(e,"result");return t(o)},se=async e$1=>e$1.platform==="Android"?x(e,{pollIntervalMs:r,timeoutMs:s}):w(e),d=async e=>{if(!a())return null;S();let t=v();if(!C(e.feature,t))return null;let n=await se(t);if(!n)return null;let o=c(e.endpointPrefix),i=e.timeoutMs??3e3;return new Promise(r=>{let a=false,l=v=>{a||(a=true,c(),clearTimeout(u),r(v));},c=b.on(o,v=>{let P=ae(v,e.parseResult);l(P);}),u=setTimeout(()=>l(null),i);try{n.postMessage({command:e.command,parameters:I({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{l(null);}})},E=async e=>{if(!a())return null;S();let t=v();if(!C(e.feature,t))return null;let n=await se(t);if(!n)return null;let o=c(e.endpointPrefix),i=b.on(o,r=>{let a=ae(r,e.parseEvent);a&&e.onEvent(a);});try{n.postMessage({command:e.startCommand,parameters:I({endpoint:o,timestamp:Date.now(),payload:e.payload})});}catch{return i(),null}return ()=>{i();try{n.postMessage({command:e.stopCommand,parameters:I({endpoint:o,timestamp:Date.now(),payload:null})});}catch{}}};var p=async e=>{if(!a())return e.safeDefault;let t=await e.native();if(t!==null)return t;try{let n=await e.web();if(n!==null)return n}catch{}return e.safeDefault};var le=e=>e==="front"?"user":"environment",be={low:.5,medium:.8,high:.95},Me=e=>{let t=e.indexOf(",");if(t<0)return null;let n=e.slice(5,t),o=e.slice(t+1),r=/^([^;]+)/.exec(n)?.[1]??"application/octet-stream";try{if(/;base64/.test(n)){let l=atob(o),c=new Uint8Array(l.length);for(let u=0;u<l.length;u++)c[u]=l.charCodeAt(u);return new Blob([c],{type:r})}return new Blob([decodeURIComponent(o)],{type:r})}catch{return null}},Re=e=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"dataUrl"),n=Reflect.get(e,"width"),o=Reflect.get(e,"height");if(typeof t!="string"||t.length===0||typeof n!="number"||typeof o!="number")return null;let i=Me(t);return i?{blob:i,dataUrl:t,width:n,height:o}:null},Ie=async e=>{if(!a()||!navigator.mediaDevices?.getUserMedia)return null;let t=null;try{t=await navigator.mediaDevices.getUserMedia({video:{facingMode:le(e?.camera),width:e?.width,height:e?.height}});let n=document.createElement("video");n.srcObject=t,n.muted=!0,n.playsInline=!0,await n.play(),await new Promise(y=>{requestAnimationFrame(()=>y());});let o=e?.width??n.videoWidth??640,i=e?.height??n.videoHeight??480,r=document.createElement("canvas");r.width=o,r.height=i;let a=r.getContext("2d");if(!a)return null;a.drawImage(n,0,0,o,i);let c=`image/${e?.format??"jpeg"}`,u=be[e?.quality??"medium"],v=r.toDataURL(c,u),P=await new Promise(y=>{r.toBlob(_e=>y(_e),c,u);});return P?{blob:P,dataUrl:v,width:o,height:i}:null}catch{return null}finally{if(t)for(let n of t.getTracks())n.stop();}},ce={isSupported(){return a()?!!navigator.mediaDevices?.getUserMedia:false},capturePhoto(e){return p({native:()=>d({feature:"camera",command:ne,endpointPrefix:G,payload:e??{},parseResult:Re,timeoutMs:6e4}),web:()=>Ie(e),safeDefault:null})},async openStream(e){if(!a()||!navigator.mediaDevices?.getUserMedia)return null;try{return await navigator.mediaDevices.getUserMedia({video:{facingMode:le(e?.camera),width:e?.width,height:e?.height}})}catch{return null}},stopStream(e){try{for(let t of e.getTracks())t.stop();}catch{}}};var me=(e,t)=>{let n=atob(e),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);return new Blob([o],{type:t})},Ne=e=>{let t=null;if(e.dataUrl){let n=e.dataUrl.indexOf(",");if(n>0){let o=e.dataUrl.slice(5,n),i=e.dataUrl.slice(n+1),r=/^([^;]+)/.exec(o)?.[1]??"application/octet-stream";try{t=/;base64/.test(o)?me(i,r):new Blob([decodeURIComponent(i)],{type:r});}catch{t=null;}}}else e.base64&&(t=me(e.base64,e.mime??"application/octet-stream"));return t?new File([t],e.name,{type:e.mime??t.type,lastModified:Date.now()}):null},De=e=>{if(typeof e!="object"||e===null)return null;let t=Reflect.get(e,"files");if(!Array.isArray(t))return null;let n=Reflect.get(e,"paths"),o=r=>{if(!Array.isArray(n))return;let a=n[r];return typeof a=="string"?a:void 0},i=[];for(let r=0;r<t.length;r++){let a=t[r];if(typeof a!="object"||a===null)continue;let l=a,c=Ne(l);if(!c)continue;let u=typeof l.path=="string"?l.path:o(r);i.push(u!==void 0?{file:c,path:u}:{file:c});}return i.length===0?null:{files:i}},we=e=>{let t=[],n=[];if(!e)return {mimeTypes:t,extensions:n};for(let o of e)for(let i of o.split(",")){let r=i.trim();r&&(r.startsWith(".")?n.push(r):t.push(r));}return {mimeTypes:t,extensions:n}},pe=e=>e instanceof DOMException&&e.name==="AbortError",de=e=>e.length>0?{files:e.map(t=>({file:t}))}:null,xe=async e=>{if(!a())return null;try{if(e?.directory){let i=await directoryOpen({recursive:!0});return de(i)}let{mimeTypes:t,extensions:n}=we(e?.accept);if(e?.multiple){let i=await fileOpen({mimeTypes:t,extensions:n,multiple:!0});return de(i)}return {files:[{file:await fileOpen({mimeTypes:t,extensions:n})}]}}catch(t){return pe(t),null}},Fe=async(e,t)=>{if(!a())return "failed";try{return await fileSave(e,{fileName:t}),"saved"}catch(n){return pe(n)?"cancelled":"failed"}},fe={isPickerSupported(){return a()?typeof window.showOpenFilePicker=="function":false},pickFiles(e){return p({native:()=>d({feature:"files",command:oe,endpointPrefix:R,payload:e??{},parseResult:De,timeoutMs:6e4}),web:()=>xe(e),safeDefault:null})},async saveFile(e,t){return a()?await d({feature:"files",command:ie,endpointPrefix:R,payload:{filename:t,mime:e.type,size:e.size},parseResult:()=>true,timeoutMs:6e4})?"saved":Fe(e,t):"failed"},readAsText(e){return typeof e.text=="function"?e.text():new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{t(typeof o.result=="string"?o.result:"");},o.onerror=()=>n(o.error),o.readAsText(e);})},readAsDataUrl(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{t(typeof o.result=="string"?o.result:"");},o.onerror=()=>n(o.error),o.readAsDataURL(e);})}};var f=(e,...t)=>{for(let n of t){let o=Reflect.get(e,n);if(typeof o=="number"&&!Number.isNaN(o))return o}},ve=e=>{if(typeof e!="object"||e===null)return null;let t=f(e,"latitude"),n=f(e,"longitude"),o=f(e,"accuracyMeters","accuracy");if(t===void 0||n===void 0||o===void 0)return null;let i={latitude:t,longitude:n,accuracyMeters:o,timestamp:f(e,"timestamp")??Date.now()},r=f(e,"altitudeMeters","altitude");r!==void 0&&(i.altitudeMeters=r);let a=f(e,"altitudeAccuracyMeters","altitudeAccuracy");a!==void 0&&(i.altitudeAccuracyMeters=a);let l=f(e,"headingDegrees","heading");l!==void 0&&(i.headingDegrees=l);let c=f(e,"speedMetersPerSecond","speed");return c!==void 0&&(i.speedMetersPerSecond=c),i},Se=e=>({latitude:e.coords.latitude,longitude:e.coords.longitude,accuracyMeters:e.coords.accuracy,altitudeMeters:e.coords.altitude??void 0,altitudeAccuracyMeters:e.coords.altitudeAccuracy??void 0,headingDegrees:e.coords.heading??void 0,speedMetersPerSecond:e.coords.speed??void 0,timestamp:e.timestamp}),Ee=e=>e?{enableHighAccuracy:e.enableHighAccuracy,timeout:e.timeoutMs,maximumAge:e.maximumAgeMs}:void 0,ke=e=>!a()||!navigator.geolocation?Promise.resolve(null):new Promise(t=>{navigator.geolocation.getCurrentPosition(n=>t(Se(n)),()=>t(null),Ee(e));}),Pe={isSupported(){return a()?!!navigator.geolocation:false},getCurrentPosition(e){return p({native:()=>d({feature:"geolocation",command:Q,endpointPrefix:M,payload:e??{},parseResult:ve,timeoutMs:e?.timeoutMs}),web:()=>ke(e),safeDefault:null})},watchPosition(e,t){let n=false,o=null,i=null;return E({feature:"geolocation",startCommand:J,stopCommand:Y,endpointPrefix:M,payload:t??{},parseEvent:ve,onEvent:r=>{n||e(r);}}).then(r=>{if(n){r?.();return}if(r){o=r;return}if(!(!a()||!navigator.geolocation))try{i=navigator.geolocation.watchPosition(a=>{n||e(Se(a));},()=>{},Ee(t));}catch{}}),()=>{if(n=true,o&&o(),i!==null&&a()&&navigator.geolocation)try{navigator.geolocation.clearWatch(i);}catch{}}}};var Ue={light:10,medium:20,heavy:40,soft:15,rigid:30},Le={success:[20,60,20],warning:[40,40,40],error:[50,30,100]},Be=e=>{if(typeof navigator>"u"||typeof navigator.vibrate!="function")return false;try{return navigator.vibrate(e)}catch{return false}},O=(e,t,n)=>p({native:()=>d({feature:"haptics",command:e,endpointPrefix:B,payload:t,parseResult:()=>true}),web:async()=>Be(n),safeDefault:false}),ge={isSupported(){return a()?typeof navigator<"u"&&"vibrate"in navigator:false},async impact(e="medium"){await O(q,{strength:e},Ue[e]);},async selection(){await O(j,{},8);},async notification(e){await O(z,{kind:e},Le[e]);},async vibrate(e){await O(K,{pattern:e},e);}};var ye=()=>typeof DeviceMotionEvent>"u"?false:typeof DeviceMotionEvent.requestPermission=="function",Oe=async()=>{if(!ye())return true;try{let e=DeviceMotionEvent.requestPermission;return e?await e()==="granted":!0}catch{return false}},m=(e,...t)=>{for(let n of t){let o=Reflect.get(e,n);if(typeof o=="number"&&!Number.isNaN(o))return o}},A=(e,t)=>{let n=Reflect.get(e,t);if(typeof n!="object"||n===null)return;let o=m(n,"x"),i=m(n,"y"),r=m(n,"z");if(!(o===void 0||i===void 0||r===void 0))return {x:o,y:i,z:r}},He=e=>{if(typeof e!="object"||e===null)return null;let t=A(e,"accelerationWithGravity")??A(e,"accelerationIncludingGravity");if(!t)return null;let n=Reflect.get(e,"rotationRate"),o={alpha:0,beta:0,gamma:0};typeof n=="object"&&n!==null&&(o={alpha:m(n,"alpha")??0,beta:m(n,"beta")??0,gamma:m(n,"gamma")??0});let i={accelerationWithGravity:t,rotationRate:o,timestamp:m(e,"timestamp")??Date.now()},r=A(e,"acceleration");r&&(i.acceleration=r);let a=Reflect.get(e,"attitude");if(typeof a=="object"&&a!==null){let l=m(a,"yaw"),c=m(a,"pitch"),u=m(a,"roll");l!==void 0&&c!==void 0&&u!==void 0&&(i.attitude={yaw:l,pitch:c,roll:u});}return i},Ve=e=>{if(typeof e!="object"||e===null)return null;let t=m(e,"alpha"),n=m(e,"beta"),o=m(e,"gamma");return t===void 0||n===void 0||o===void 0?null:{alpha:t,beta:n,gamma:o,timestamp:m(e,"timestamp")??Date.now()}},We=e=>{let t=e.accelerationIncludingGravity,n=e.acceleration,o=e.rotationRate,i={accelerationWithGravity:{x:t?.x??0,y:t?.y??0,z:t?.z??0},rotationRate:{alpha:o?.alpha??0,beta:o?.beta??0,gamma:o?.gamma??0},timestamp:e.timeStamp||Date.now()};return n&&(n.x!==null||n.y!==null||n.z!==null)&&(i.acceleration={x:n.x??0,y:n.y??0,z:n.z??0}),i},Ge=e=>({alpha:e.alpha??0,beta:e.beta??0,gamma:e.gamma??0,timestamp:e.timeStamp||Date.now()}),he={isMotionSupported(){return a()?typeof DeviceMotionEvent<"u":false},isOrientationSupported(){return a()?typeof DeviceOrientationEvent<"u":false},async requestMotionPermission(){if(!a())return false;let e=await d({feature:"sensors",command:te,endpointPrefix:W,payload:{},parseResult:t=>{if(typeof t=="boolean")return t;if(typeof t=="object"&&t!==null){let n=Reflect.get(t,"granted");if(typeof n=="boolean")return n}return null}});return e!==null?e:Oe()},watchMotion(e,t){let n=false,o=null,i=null,r=()=>{if(n||!a())return;let l=c=>{n||e(We(c));};window.addEventListener("devicemotion",l),i=l;};return (async()=>{let l=await E({feature:"sensors",startCommand:$,stopCommand:X,endpointPrefix:H,payload:t??{},parseEvent:He,onEvent:c=>{n||e(c);}});if(n){l?.();return}if(l){o=l;return}t?.autoRequestPermission&&ye()&&(!await Oe()||n)||r();})(),()=>{n=true,o&&o(),i&&a()&&(window.removeEventListener("devicemotion",i),i=null);}},watchOrientation(e){let t=false,n=null,o=null,i=()=>{if(t||!a())return;let a$1=l=>{t||e(Ge(l));};window.addEventListener("deviceorientation",a$1),o=a$1;};return (async()=>{let a=await E({feature:"sensors",startCommand:Z,stopCommand:ee,endpointPrefix:V,payload:{},parseEvent:Ve,onEvent:l=>{t||e(l);}});if(t){a?.();return}if(a){n=a;return}i();})(),()=>{t=true,n&&n(),o&&a()&&(window.removeEventListener("deviceorientation",o),o=null);}}};S();var At={haptics:ge,geolocation:Pe,sensors:he,camera:ce,files:fe};export{ce as camera,At as device,fe as files,Pe as geolocation,ge as haptics,C as meetsFeatureMinVersion,he as sensors};
@@ -1,15 +1,22 @@
1
- import { U as UserInfo } from '../types-CLujY9ck.js';
1
+ import { U as UserInfo } from '../types-DryABknE.js';
2
2
 
3
3
  interface UseAuthTokenResult {
4
4
  token: string;
5
5
  /** 首次 fetch 或主动 refetch 未完成期间为 true。 */
6
6
  loading: boolean;
7
- /** 主动重新拉取;命中 SDK 凭证缓存时不会重复访问宿主。 */
8
- refetch: () => void;
7
+ /**
8
+ * 主动重新拉取;命中 SDK 凭证缓存时不会重复访问宿主。返回的 Promise 在
9
+ * 本次拉取完成后 resolve,便于业务 `await refetch()` 后再做后续动作。
10
+ */
11
+ refetch: () => Promise<void>;
9
12
  }
10
13
  /**
11
14
  * 鉴权 token。挂载时拉一次,业务需要刷新时调用 refetch。
12
15
  *
16
+ * Token 通过 `useSyncExternalStore` 订阅 SDK 内部凭证缓存——宿主通过桥
17
+ * (EP_CREDENTIALS) 推送新 token、或 AI 模块 401 自动 refresh 后,组件会
18
+ * 自动 re-render,业务不必手动 refetch。
19
+ *
13
20
  * 注意:token 是字符串,不是 Credentials。如果你需要 userId,配合
14
21
  * `useUserInfo()` 用。
15
22
  */
@@ -18,7 +25,8 @@ declare const useAuthToken: () => UseAuthTokenResult;
18
25
  interface UseUserInfoResult {
19
26
  user: UserInfo | null;
20
27
  loading: boolean;
21
- refetch: () => void;
28
+ /** 主动重新拉取。返回的 Promise 在拉取完成后 resolve。 */
29
+ refetch: () => Promise<void>;
22
30
  }
23
31
  /**
24
32
  * 用户信息。同 useAuthToken:挂载拉一次,业务需要刷新时调用 refetch。
@@ -1 +1 @@
1
- import {b,d as d$1}from'../chunk-IOHVFMVA.js';import {useState,useCallback,useEffect}from'react';var U=()=>{let[s,o]=useState(""),[r,t]=useState(true),n=useCallback(()=>{t(true),b().then(e=>{o(e),t(false);});},[]);return useEffect(()=>{let e=true;return b().then(u=>{e&&(o(u),t(false));}),()=>{e=false;}},[]),{token:s,loading:r,refetch:n}};var d=()=>{let[s,o]=useState(null),[r,t]=useState(true),n=useCallback(()=>{t(true),d$1().then(e=>{o(e),t(false);});},[]);return useEffect(()=>{let e=true;return d$1().then(u=>{e&&(o(u),t(false));}),()=>{e=false;}},[]),{user:s,loading:r,refetch:n}};export{U as useAuthToken,d as useUserInfo};
1
+ import {b,a,c,e}from'../chunk-AKZVV563.js';import'../chunk-ALNJCFV4.js';import {useSyncExternalStore,useState,useCallback,useEffect}from'react';var k="",d=()=>{let u=useSyncExternalStore(b,a,()=>k),[s,e]=useState(()=>a()===""),t=useCallback(async()=>{e(true),await c(),e(false);},[]);return useEffect(()=>{if(a()!==""){e(false);return}let o=true;return c().then(()=>{o&&e(false);}),()=>{o=false;}},[]),{token:u,loading:s,refetch:t}};var I=()=>{let[u,s]=useState(null),[e$1,t]=useState(true),o=useCallback(async()=>{t(true);let r=await e();s(r),t(false);},[]);return useEffect(()=>{let r=true;return e().then(c=>{r&&(s(c),t(false));}),()=>{r=false;}},[]),{user:u,loading:e$1,refetch:o}};export{d as useAuthToken,I as useUserInfo};
@@ -0,0 +1,23 @@
1
+ interface Credentials {
2
+ uid: string;
3
+ token: string;
4
+ }
5
+ interface UserInfo {
6
+ userId: string | number;
7
+ username?: string;
8
+ nickname?: string;
9
+ avatar?: string | null;
10
+ phone?: string | null;
11
+ email?: string;
12
+ [key: string]: unknown;
13
+ }
14
+ type AppEnvironmentType = "native_app" | "iframe" | "web";
15
+ interface AppEnvironment {
16
+ type: AppEnvironmentType;
17
+ platform?: "iOS" | "Android";
18
+ appVersion?: string;
19
+ buildNumber?: string;
20
+ meetsMinVersion: boolean;
21
+ }
22
+
23
+ export type { AppEnvironment as A, Credentials as C, UserInfo as U };
@@ -1,5 +1,5 @@
1
- import { U as UserInfo } from '../types-CLujY9ck.js';
2
- export { C as Credentials } from '../types-CLujY9ck.js';
1
+ import { U as UserInfo } from '../types-DryABknE.js';
2
+ export { C as Credentials } from '../types-DryABknE.js';
3
3
 
4
4
  declare const getAuthTokenAsync: () => Promise<string>;
5
5
  declare const getUserInfoAsync: () => Promise<UserInfo | null>;
@@ -1 +1 @@
1
- export{b as getAuthTokenAsync,d as getUserInfoAsync}from'../chunk-IOHVFMVA.js';
1
+ export{c as getAuthTokenAsync,e as getUserInfoAsync}from'../chunk-AKZVV563.js';import'../chunk-ALNJCFV4.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bty/feed_app-runtime-sdk",
3
- "version": "0.0.8",
3
+ "version": "0.1.0",
4
4
  "type": "module",
5
5
  "browser": true,
6
6
  "description": "Runtime SDK for feed-app template: auth / AI capabilities, multi-environment bridge (native App / iframe / web).",
@@ -21,6 +21,10 @@
21
21
  "types": "./dist/react/index.d.ts",
22
22
  "import": "./dist/react/index.js"
23
23
  },
24
+ "./device": {
25
+ "types": "./dist/device/index.d.ts",
26
+ "import": "./dist/device/index.js"
27
+ },
24
28
  "./package.json": "./package.json"
25
29
  },
26
30
  "publishConfig": {
@@ -52,5 +56,9 @@
52
56
  "typescript": "catalog:",
53
57
  "vite": "catalog:",
54
58
  "vitest": "^2.1.8"
59
+ },
60
+ "dependencies": {
61
+ "browser-fs-access": "^0.38.0",
62
+ "eventsource-parser": "^3.1.0"
55
63
  }
56
64
  }
@@ -1 +0,0 @@
1
- var i=()=>typeof window<"u"&&typeof document<"u";var se="hostRuntime",g=class{listeners=new Map;on(n,t){let r=this.listeners.get(n),s=r??new Set;return r||this.listeners.set(n,s),s.add(t),()=>{s.delete(t),s.size===0&&this.listeners.delete(n);}}emit(n,t){let r=this.listeners.get(n);if(r)for(let s of r)s(t);}},o=new g,y=0,N=e=>(y+=1,`${e}.${y}`),k=false,v=()=>{if(!i()||k)return;k=true,Reflect.set(window,se,{receiveMessage(n){if(!n)return;let t=n.endpoint;t&&o.emit(t,n.data??n);}});};var _=e=>typeof e=="object"&&e!==null,f=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0)return r}},oe=(e,n)=>{if(e)for(let t of n){let r=e[t];if(typeof r=="string"&&r.length>0||typeof r=="number"&&Number.isFinite(r))return r}},a=e=>{if(!_(e))return null;let n=_(e.credentials)?e.credentials:void 0,t=_(e.user)?e.user:void 0,r=f(e,["uid","userId","id"])??f(n,["uid","userId","id"])??f(t,["uid","userId","id"]),s=f(e,["token","authToken"])??f(n,["token","authToken"]);return !r||!s?null:{uid:r,token:s}},m=e=>{if(!_(e))return null;let n=_(e.data)?e.data:e,t=oe(n,["userId","id","uid"]);if(t===void 0)return null;let r=f(n,["username","nickname","nickName","name"]),s=f(n,["nickname","nickName","username"]);return {...n,userId:t,...r?{username:r}:{},...s?{nickname:s}:{}}};var O="HostApp",A="hostListener";var U="processUserCredentials",P="processUserInfo",x="user.getCredentials",L="user.getUserInfo",d="user.credentials",R="user.info",h="user-credentials-request",b="user-credentials-response",F="user-info-request",H="user-info-response",D={iOS:[1,6,7],Android:[1,1,8]},q=3e3,B=500,V=50,j=1500;var ie=e=>typeof e!="object"||e===null?false:typeof Reflect.get(e,"type")=="string",G=false,Q=()=>{!i()||G||(G=true,v(),Reflect.set(window,U,e=>{a(e)&&o.emit(d,e);}),Reflect.set(window,P,e=>{m(e)&&o.emit(R,e);}),window.addEventListener("message",e=>{let n=e.data;if(ie(n))switch(n.type){case b:o.emit("iframe.credentials",n);break;case H:o.emit("iframe.userinfo",n);break}}));};var ue=new RegExp(`${O}\\/(\\d+\\.\\d+\\.\\d+)\\/(\\d+)\\/(iOS|Android)`),le=e=>{let n=e.split(".").map(t=>Number.parseInt(t,10));return [n[0]??0,n[1]??0,n[2]??0]},ae=(e,n)=>{for(let t=0;t<3;t++){if(e[t]>n[t])return true;if(e[t]<n[t])return false}return true},ce=e=>{let n=e.match(ue);if(!n)return null;let[,t,r,s]=n;if(!t||!r||s!=="iOS"&&s!=="Android")return null;let u=ae(le(t),D[s]);return {type:"native_app",platform:s,appVersion:t,buildNumber:r,meetsMinVersion:u}},w=()=>{if(!i())return {type:"web",meetsMinVersion:false};let e=ce(navigator.userAgent??"");return e||(window.parent!==window?{type:"iframe",meetsMinVersion:false}:{type:"web",meetsMinVersion:false})};var $=(e,n,t)=>new Promise(r=>{let s=false,u=l=>{s||(s=true,p(),clearTimeout(c),r(l));},p=o.on(n,l=>{let T=t(l);T&&u(T);}),c=setTimeout(()=>u(null),B);try{window.parent.postMessage({type:e,timestamp:Date.now()},"*");}catch{u(null);}}),K=()=>$(h,"iframe.credentials",a),z=()=>$(F,"iframe.userinfo",m);var J=e=>typeof e!="object"||e===null?false:typeof Reflect.get(e,"postMessage")=="function",M=e=>{let n=Reflect.get(window,"webkit");if(typeof n=="object"&&n!==null){let r=Reflect.get(n,"messageHandlers");if(typeof r=="object"&&r!==null){let s=Reflect.get(r,e);if(J(s))return s}}let t=Reflect.get(window,e);return J(t)?t:null},X=(e,n={})=>{let{pollIntervalMs:t=50,timeoutMs:r=1500}=n;return new Promise(s=>{let u=Date.now(),p=()=>{let c=M(e);if(c){s(c);return}if(Date.now()-u>=r){s(null);return}setTimeout(p,t);};p();})};var W=async(e,n,t,r)=>{let s=e.platform==="Android"?await X(A,{pollIntervalMs:V,timeoutMs:j}):M(A);if(!s)return null;let u=N(t);return new Promise(p=>{let c=false,l=E=>{c||(c=true,T(),te(),clearTimeout(re),p(E));},T=o.on(u,E=>{let I=r(E);I&&l(I);}),te=o.on(t,E=>{let I=r(E);I&&l(I);}),re=setTimeout(()=>l(null),q);try{s.postMessage({command:n,parameters:JSON.stringify({timestamp:Date.now(),endpoint:u})});}catch{l(null);}})},Y=e=>W(e,x,d,a),Z=e=>W(e,L,R,m);Q();var C=null,S=null,fe=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?Y(e):Promise.resolve(null);case "iframe":return K();case "web":return Promise.resolve(null)}},pe=e=>{switch(e.type){case "native_app":return e.meetsMinVersion?Z(e):Promise.resolve(null);case "iframe":return z();case "web":return Promise.resolve(null)}},ee=e=>{C=e;},ne=()=>S||(S=fe(w()).then(e=>(e&&ee(e),e)).finally(()=>{S=null;}),S);i()&&o.on(d,e=>{let n=a(e);n&&ee(n);});var me=async()=>i()?C?C.token:(await ne())?.token??"":"",$e=async()=>i()?(await ne())?.token??"":"",de=async()=>i()?pe(w()):null;export{i as a,me as b,$e as c,de as d};
@@ -1,15 +0,0 @@
1
- interface Credentials {
2
- uid: string;
3
- token: string;
4
- }
5
- interface UserInfo {
6
- userId: string | number;
7
- username?: string;
8
- nickname?: string;
9
- avatar?: string | null;
10
- phone?: string | null;
11
- email?: string;
12
- [key: string]: unknown;
13
- }
14
-
15
- export type { Credentials as C, UserInfo as U };