@stacksjs/stx 0.2.493 → 0.2.494

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.
Files changed (76) hide show
  1. package/dist/{chunk-nwy97xaa.js → chunk-0adrp7qd.js} +1 -1
  2. package/dist/{chunk-zxkzdbcv.js → chunk-15w4adyd.js} +1 -1
  3. package/dist/{chunk-nf9fhj10.js → chunk-2gr5zcm3.js} +1 -1
  4. package/dist/chunk-2wvezjd5.js +33 -0
  5. package/dist/{chunk-q21e52cb.js → chunk-33snwgdy.js} +1 -1
  6. package/dist/chunk-379nn8yc.js +2 -0
  7. package/dist/{chunk-jnf8vt18.js → chunk-40jd0b4h.js} +1 -1
  8. package/dist/{chunk-nfd56dgj.js → chunk-4mrgy3ve.js} +1 -1
  9. package/dist/{chunk-djwms13g.js → chunk-4rmdngzw.js} +1 -1
  10. package/dist/{chunk-4tb1mqr8.js → chunk-4ssg2hn4.js} +1 -1
  11. package/dist/chunk-52saa2nj.js +2 -0
  12. package/dist/{chunk-z26ty1t1.js → chunk-6v3p6cx1.js} +1 -1
  13. package/dist/{chunk-e43ckdk2.js → chunk-78vfptph.js} +1 -1
  14. package/dist/{chunk-b6xrqx6w.js → chunk-7e6sxdp6.js} +1 -1
  15. package/dist/{chunk-kzg3h5wg.js → chunk-81t6zr3m.js} +1 -1
  16. package/dist/{chunk-ze9vhhvc.js → chunk-8qdvhbv7.js} +2 -2
  17. package/dist/{chunk-2b1zg7xp.js → chunk-93sr9q8g.js} +1 -1
  18. package/dist/{chunk-sdxq5ej9.js → chunk-9mh1qq3g.js} +1 -1
  19. package/dist/{chunk-ft6k76e4.js → chunk-b5mcvm6y.js} +1 -1
  20. package/dist/{chunk-z7bqn398.js → chunk-b90y5phw.js} +5 -5
  21. package/dist/{chunk-7c18zqdc.js → chunk-dve4q9tg.js} +1 -1
  22. package/dist/{chunk-0zs1fd9z.js → chunk-fxppbahx.js} +1 -1
  23. package/dist/{chunk-c0jedy4d.js → chunk-gvkfydq5.js} +1 -1
  24. package/dist/{chunk-jaghd4j0.js → chunk-h0sd5cda.js} +2 -2
  25. package/dist/{chunk-bay6snzz.js → chunk-hhj1txvj.js} +1 -1
  26. package/dist/{chunk-j1d4aemv.js → chunk-jh385m2w.js} +1 -1
  27. package/dist/chunk-kxg9q64a.js +2 -0
  28. package/dist/{chunk-jws8btr5.js → chunk-m9nr12a1.js} +40 -40
  29. package/dist/{chunk-dnq9fhwf.js → chunk-mdfrm5hv.js} +1 -1
  30. package/dist/{chunk-fzwy4nny.js → chunk-mq7vvaf4.js} +1 -1
  31. package/dist/{chunk-cfj3c9ss.js → chunk-nfffn3s0.js} +1 -1
  32. package/dist/{chunk-0acycggt.js → chunk-nw7qvyek.js} +1 -1
  33. package/dist/{chunk-perp76wy.js → chunk-ny64ezsj.js} +1 -1
  34. package/dist/{chunk-f324yttz.js → chunk-qhnpc3ac.js} +1 -1
  35. package/dist/{chunk-1x4b64mx.js → chunk-qjba655t.js} +1 -1
  36. package/dist/{chunk-gparzn81.js → chunk-qjxxd4a0.js} +1 -1
  37. package/dist/{chunk-fh3r97cq.js → chunk-qsy7phd4.js} +1 -1
  38. package/dist/{chunk-vbthtg0x.js → chunk-rfq1jfhf.js} +1 -1
  39. package/dist/{chunk-fh7w72xm.js → chunk-rr41gk8b.js} +1 -1
  40. package/dist/{chunk-aertsqje.js → chunk-snyq0jj6.js} +1 -1
  41. package/dist/{chunk-52fcqzmc.js → chunk-stvqwzen.js} +1 -1
  42. package/dist/{chunk-6mqb6vf7.js → chunk-tdetcthb.js} +1 -1
  43. package/dist/{chunk-gwvg2c50.js → chunk-v8m2khkq.js} +1 -1
  44. package/dist/{chunk-g3hn7ncc.js → chunk-vtn0gmen.js} +2 -2
  45. package/dist/{chunk-emx5wsaa.js → chunk-xk2mwk61.js} +1 -1
  46. package/dist/{chunk-86vgttef.js → chunk-yvt8zszz.js} +1 -1
  47. package/dist/{chunk-nnqjjtqz.js → chunk-zbzmfqmk.js} +1 -1
  48. package/dist/{chunk-bt58m9y8.js → chunk-zqxqdns1.js} +1 -1
  49. package/dist/cli.js +7 -7
  50. package/dist/component-renderer.js +15 -1
  51. package/dist/craft-entry.js +1 -1
  52. package/dist/craft.js +1 -1
  53. package/dist/native/bridge/protocol.d.ts +5 -1
  54. package/dist/native/compiler/component-mapping.js +1 -0
  55. package/dist/native/compiler/html-to-ir.js +26 -5
  56. package/dist/native/compiler/icons.d.ts +15 -0
  57. package/dist/native/compiler/icons.js +15 -0
  58. package/dist/native/compiler/ir.d.ts +1 -0
  59. package/dist/native/components/primitives.d.ts +48 -1
  60. package/dist/native/components/primitives.js +3 -0
  61. package/dist/native/primitives/Video.stx +5 -0
  62. package/dist/native/prop-names.d.ts +6 -0
  63. package/dist/native/prop-names.js +34 -1
  64. package/dist/native/runtime/craft-bridge.js +240 -34
  65. package/dist/native/runtime/craft.d.ts +54 -1
  66. package/dist/native/runtime/event-stream.d.ts +31 -0
  67. package/dist/native/runtime/event-stream.js +232 -0
  68. package/dist/native/runtime/jsc-globals.d.ts +23 -0
  69. package/dist/native/runtime/jsc-globals.js +60 -0
  70. package/dist/pwa.js +1 -1
  71. package/dist/ssg.js +2 -2
  72. package/package.json +5 -5
  73. package/dist/chunk-0gx8he4p.js +0 -33
  74. package/dist/chunk-af944jrx.js +0 -2
  75. package/dist/chunk-q9w7sb6r.js +0 -2
  76. package/dist/chunk-qnyfg99e.js +0 -2
@@ -1,12 +1,14 @@
1
1
  import { STXBridge } from "../bridge/protocol.js";
2
+ import { createEventSourceClass, createStreamingBody } from "./event-stream.js";
3
+ import { abortError } from "./jsc-globals.js";
2
4
  function capabilityFlags(capabilities) {
3
5
  return {
4
6
  haptics: capabilities.has("haptics"),
5
7
  speechRecognition: !1,
6
- share: !1,
8
+ share: capabilities.has("share"),
7
9
  camera: !1,
8
10
  biometric: capabilities.has("biometric"),
9
- pushNotifications: !1,
11
+ pushNotifications: capabilities.has("push"),
10
12
  secureStorage: capabilities.has("secureStorage"),
11
13
  storage: capabilities.has("storage"),
12
14
  localDatabase: capabilities.has("database"),
@@ -21,7 +23,10 @@ function capabilityFlags(capabilities) {
21
23
  orientationLock: !1,
22
24
  deepLinks: capabilities.has("deepLinks"),
23
25
  flashlight: !1,
24
- speech: !1,
26
+ speech: capabilities.has("speech"),
27
+ audio: capabilities.has("audio"),
28
+ eventStream: capabilities.has("eventStream"),
29
+ linking: capabilities.has("linking"),
25
30
  network: !1,
26
31
  deviceInfo: capabilities.has("device"),
27
32
  fetch: capabilities.has("fetch"),
@@ -43,14 +48,31 @@ function platformUserAgent(platform) {
43
48
  export function installCraftBridge(protocol, nativeBridge, target = globalThis, options = {}) {
44
49
  const craft = target.craft = target.craft || {}, capabilities = new Set(nativeBridge.capabilities || []), request = (module, method, args) => protocol.callNativeAPI(module, method, ...args), ask = (module, method, args) => protocol.callPersonFacingAPI(module, method, ...args);
45
50
  let appState = nativeBridge.initialAppState || "active", initialDeepLinkClaimed = !1;
46
- const appStateHandlers = new Set, deepLinkHandlers = new Set, navButtonHandlers = new Set, navButtonPresses = new Map, routeName = options.routeName || "main", routeNames = options.routeNames || [routeName];
51
+ const appStateHandlers = new Set, deepLinkHandlers = new Set, navButtonHandlers = new Set, navButtonPresses = new Map, appearHandlers = new Set, disappearHandlers = new Set;
52
+ let focused = !0;
53
+ const routeName = options.routeName || "main", routeNames = options.routeNames || [routeName];
47
54
  craft.platform = nativeBridge.platform || "unknown";
48
55
  const navigatorObject = target.navigator = target.navigator || {};
49
56
  if (typeof navigatorObject.userAgent !== "string")
50
57
  navigatorObject.userAgent = platformUserAgent(craft.platform);
51
58
  craft.capabilityProtocolVersion = Number(nativeBridge.capabilityProtocolVersion || 0);
52
59
  craft.capabilities = capabilityFlags(capabilities);
60
+ const paramsHandlers = new Set;
53
61
  craft.route = { name: routeName, params: target.__stxNativeParams || {} };
62
+ Object.defineProperty(craft.route, "onParams", {
63
+ value: (callback) => {
64
+ if (typeof callback !== "function")
65
+ throw TypeError("route.onParams needs a function");
66
+ paramsHandlers.add(callback);
67
+ return () => paramsHandlers.delete(callback);
68
+ }
69
+ });
70
+ protocol.on("ROUTE_PARAMS", ({ payload }) => {
71
+ const previous = craft.route.params, params = payload?.params && typeof payload.params === "object" ? payload.params : {};
72
+ craft.route.params = params;
73
+ target.__stxNativeParams = params;
74
+ paramsHandlers.forEach((handler) => handler(params, previous));
75
+ });
54
76
  craft.appearance = { colorScheme: () => nativeBridge.colorScheme === "dark" ? "dark" : "light" };
55
77
  craft.device = { getInfo: () => request("Device", "getInfo", []) };
56
78
  craft.clipboard = {
@@ -121,6 +143,105 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
121
143
  craft.browser = { open: (url, options = {}) => ask("Browser", "open", [url, options]) };
122
144
  if (capabilities.has("appleSignIn"))
123
145
  craft.signInWithApple = (options = {}) => ask("Auth", "signInWithApple", [options]);
146
+ if (capabilities.has("linking")) {
147
+ craft.linking = {
148
+ openURL: (url) => request("Linking", "openURL", [String(url)]).then(Boolean),
149
+ canOpenURL: (url) => request("Linking", "canOpenURL", [String(url)]).then(Boolean)
150
+ };
151
+ craft.openURL = craft.linking.openURL;
152
+ }
153
+ if (capabilities.has("share")) {
154
+ const share = (options = {}) => ask("Share", "share", [options]).then(Boolean);
155
+ craft.share = Object.assign(share, { share });
156
+ }
157
+ if (capabilities.has("speech"))
158
+ craft.speech = {
159
+ speak: (text, options = {}) => {
160
+ if (typeof text !== "string" || !text.trim())
161
+ return Promise.reject(Object.assign(TypeError("speech.speak needs some text to say"), { code: "INVALID_ARGUMENT" }));
162
+ return ask("Speech", "speak", [text, options]).then((spoken) => spoken === !0);
163
+ },
164
+ stop: () => request("Speech", "stop", []).then(() => {
165
+ return;
166
+ })
167
+ };
168
+ if (capabilities.has("audio")) {
169
+ let nextSound = 0;
170
+ const soundHandlers = new Map, done = () => {
171
+ return;
172
+ }, handle = (id) => {
173
+ const handlers = { end: new Set, error: new Set };
174
+ soundHandlers.set(id, handlers);
175
+ return {
176
+ id,
177
+ pause: () => request("Audio", "pause", [id]).then(done),
178
+ resume: () => request("Audio", "resume", [id]).then(done),
179
+ stop: (options = {}) => request("Audio", "stop", [id, options]).then(done),
180
+ setVolume: (volume, options = {}) => request("Audio", "setVolume", [id, Number(volume), options]).then(done),
181
+ onEnd: (callback) => {
182
+ handlers.end.add(callback);
183
+ return () => handlers.end.delete(callback);
184
+ },
185
+ onError: (callback) => {
186
+ handlers.error.add(callback);
187
+ return () => handlers.error.delete(callback);
188
+ }
189
+ };
190
+ };
191
+ craft.audio = {
192
+ play: (url, options = {}) => {
193
+ if (typeof url !== "string" || !url)
194
+ return Promise.reject(TypeError("audio.play needs a URL"));
195
+ const id = `sound-${++nextSound}`, sound = handle(id);
196
+ return request("Audio", "play", [id, url, options]).then(() => sound, (error) => {
197
+ soundHandlers.delete(id);
198
+ throw error;
199
+ });
200
+ },
201
+ stopAll: (options = {}) => request("Audio", "stopAll", [options]).then(done)
202
+ };
203
+ protocol.on("SOUND_EVENT", ({ payload }) => {
204
+ const handlers = soundHandlers.get(String(payload?.id));
205
+ if (!handlers)
206
+ return;
207
+ soundHandlers.delete(String(payload?.id));
208
+ if (payload?.event === "ended")
209
+ handlers.end.forEach((handler) => handler());
210
+ else
211
+ handlers.error.forEach((handler) => handler(String(payload?.message || "The sound could not be played")));
212
+ });
213
+ }
214
+ if (capabilities.has("push")) {
215
+ const tokenHandlers = new Set;
216
+ craft.push = {
217
+ getPermissionStatus: () => request("Push", "getPermissionStatus", []),
218
+ requestPermission: () => ask("Push", "requestPermission", []),
219
+ register: () => ask("Push", "register", []).then(String),
220
+ onToken: (callback) => {
221
+ if (typeof callback !== "function")
222
+ throw TypeError("push.onToken needs a function");
223
+ tokenHandlers.add(callback);
224
+ return () => tokenHandlers.delete(callback);
225
+ },
226
+ openSettings: () => request("Push", "openSettings", []).then(Boolean)
227
+ };
228
+ craft.registerPush = craft.push.register;
229
+ craft.permissions = Object.assign({}, craft.permissions, {
230
+ check: (permission) => permission === "notifications" ? craft.push.getPermissionStatus() : Promise.resolve("undetermined"),
231
+ request: (permission) => permission === "notifications" ? craft.push.requestPermission() : Promise.resolve("undetermined"),
232
+ openSettings: () => craft.push.openSettings().then(() => {
233
+ return;
234
+ })
235
+ });
236
+ protocol.on("PUSH_TOKEN", ({ payload }) => {
237
+ const token = String(payload?.token || "");
238
+ if (!token)
239
+ return;
240
+ tokenHandlers.forEach((handler) => handler(token));
241
+ if (typeof target.dispatchEvent === "function" && typeof target.CustomEvent === "function")
242
+ target.dispatchEvent(new target.CustomEvent("craftPushToken", { detail: { token } }));
243
+ });
244
+ }
124
245
  if (capabilities.has("health"))
125
246
  craft.health = {
126
247
  requestAuthorization: (types, options = {}) => ask("Health", "requestAuthorization", [types, options]),
@@ -173,7 +294,24 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
173
294
  throw TypeError("navigation.onButton needs a function");
174
295
  navButtonHandlers.add(callback);
175
296
  return () => navButtonHandlers.delete(callback);
176
- }
297
+ },
298
+ onAppear: (callback) => {
299
+ if (typeof callback !== "function")
300
+ throw TypeError("navigation.onAppear needs a function");
301
+ appearHandlers.add(callback);
302
+ return () => appearHandlers.delete(callback);
303
+ },
304
+ onDisappear: (callback) => {
305
+ if (typeof callback !== "function")
306
+ throw TypeError("navigation.onDisappear needs a function");
307
+ disappearHandlers.add(callback);
308
+ return () => disappearHandlers.delete(callback);
309
+ },
310
+ isFocused: () => focused
311
+ });
312
+ protocol.on("SCREEN_FOCUS", ({ payload }) => {
313
+ focused = payload?.focused !== !1;
314
+ (focused ? appearHandlers : disappearHandlers).forEach((handler) => handler());
177
315
  });
178
316
  const onAppStateChange = (callback) => {
179
317
  if (typeof callback !== "function")
@@ -217,6 +355,57 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
217
355
  if (payload?.handlerId === "navButton" || payload?.handlerName === "navButton")
218
356
  dispatchNavButton(payload.nativeEvent || {});
219
357
  });
358
+ const streaming = capabilities.has("eventStream"), streamSinks = new Map;
359
+ let nextStream = 0;
360
+ if (streaming)
361
+ protocol.on("NETWORK_STREAM", ({ payload }) => {
362
+ const sink = streamSinks.get(String(payload?.id));
363
+ if (!sink)
364
+ return;
365
+ if (typeof payload.chunk === "string")
366
+ return sink.push(payload.chunk);
367
+ streamSinks.delete(String(payload.id));
368
+ if (payload.error)
369
+ sink.fail(payload.error);
370
+ else
371
+ sink.end();
372
+ });
373
+ const streamingFetch = (url, method, headers, body, signal) => {
374
+ const id = `stream-${++nextStream}`, encoder = new target.TextEncoder;
375
+ let settled = !1;
376
+ const stream = createStreamingBody((text) => encoder.encode(text), () => {
377
+ streamSinks.delete(id);
378
+ request("Network", "cancelStream", [id]).catch(() => {});
379
+ });
380
+ streamSinks.set(id, stream.sink);
381
+ return new Promise((resolve, reject) => {
382
+ signal?.addEventListener?.("abort", () => {
383
+ stream.body.cancel();
384
+ if (!settled) {
385
+ settled = !0;
386
+ reject(abortError(signal.reason));
387
+ }
388
+ });
389
+ request("Network", "stream", [{ id, url, method, headers, body }]).then((data) => {
390
+ if (settled)
391
+ return;
392
+ settled = !0;
393
+ resolve(response(data, { get bodyUsed() {
394
+ return stream.used();
395
+ }, text: stream.text, body: stream.body }));
396
+ }, (error) => {
397
+ streamSinks.delete(id);
398
+ if (settled)
399
+ return;
400
+ settled = !0;
401
+ try {
402
+ networkFailure(error);
403
+ } catch (failure) {
404
+ reject(failure);
405
+ }
406
+ });
407
+ });
408
+ };
220
409
  if (capabilities.has("fetch") && typeof target.fetch !== "function")
221
410
  target.fetch = (input, init = {}) => {
222
411
  const source = input && typeof input === "object" ? input : {}, url = typeof input === "string" ? input : String(source.url || input), method = String(init.method || source.method || "GET").toUpperCase(), headers = {}, inputHeaders = init.headers || source.headers, addHeader = (name, value) => {
@@ -233,40 +422,57 @@ export function installCraftBridge(protocol, nativeBridge, target = globalThis,
233
422
  return Promise.reject(TypeError("fetch in a native screen sends string bodies only"));
234
423
  if (body != null && (method === "GET" || method === "HEAD"))
235
424
  return Promise.reject(TypeError("A GET or HEAD request cannot have a body"));
236
- return request("Network", "fetch", [{ url, method, headers, body: body == null ? null : body }]).then((data) => {
237
- const responseHeaders = data?.headers && typeof data.headers === "object" ? data.headers : {}, responseBody = data?.body == null ? "" : String(data.body);
425
+ const signal = init.signal || source.signal;
426
+ if (signal?.aborted)
427
+ return Promise.reject(abortError(signal.reason));
428
+ if (streaming && /text\/event-stream/i.test(headers.accept || ""))
429
+ return streamingFetch(url, method, headers, body == null ? null : body, signal);
430
+ const answer = request("Network", "fetch", [{ url, method, headers, body: body == null ? null : body }]).then((data) => {
431
+ const responseBody = data?.body == null ? "" : String(data.body);
238
432
  let bodyUsed = !1;
239
- const consume = () => {
433
+ return response(data, { get bodyUsed() {
434
+ return bodyUsed;
435
+ }, text: () => {
240
436
  if (bodyUsed)
241
437
  return Promise.reject(TypeError("Body has already been consumed"));
242
438
  bodyUsed = !0;
243
439
  return Promise.resolve(responseBody);
244
- };
245
- return {
246
- type: "basic",
247
- url: data?.url || "",
248
- status: Number(data?.status) || 0,
249
- statusText: data?.statusText || "",
250
- ok: Number(data?.status) >= 200 && Number(data?.status) < 300,
251
- redirected: Boolean(data?.redirected),
252
- headers: {
253
- get: (name) => responseHeaders[String(name).toLowerCase()] == null ? null : String(responseHeaders[String(name).toLowerCase()]),
254
- has: (name) => responseHeaders[String(name).toLowerCase()] != null,
255
- forEach: (callback) => Object.keys(responseHeaders).forEach((name) => callback(String(responseHeaders[name]), name))
256
- },
257
- get bodyUsed() {
258
- return bodyUsed;
259
- },
260
- text: consume,
261
- json: () => consume().then(JSON.parse)
262
- };
263
- }, (error) => {
264
- if (error?.code === "INVALID_ARGUMENT")
265
- throw error;
266
- const failure = TypeError(error?.message || "Network request failed");
267
- failure.code = error?.code || "NETWORK_ERROR";
268
- throw failure;
269
- });
440
+ } });
441
+ }, networkFailure);
442
+ return signal ? Promise.race([answer, aborted(signal)]) : answer;
270
443
  };
444
+ if (streaming && typeof target.fetch === "function" && typeof target.EventSource !== "function")
445
+ target.EventSource = createEventSourceClass(target);
271
446
  return craft;
272
447
  }
448
+ function aborted(signal) {
449
+ return new Promise((_, reject) => signal.addEventListener?.("abort", () => reject(abortError(signal.reason))));
450
+ }
451
+ function networkFailure(error) {
452
+ if (error?.code === "INVALID_ARGUMENT")
453
+ throw error;
454
+ const failure = TypeError(error?.message || "Network request failed");
455
+ failure.code = error?.code || "NETWORK_ERROR";
456
+ throw failure;
457
+ }
458
+ function response(data, reading) {
459
+ const responseHeaders = data?.headers && typeof data.headers === "object" ? data.headers : {}, result = {
460
+ type: "basic",
461
+ url: data?.url || "",
462
+ status: Number(data?.status) || 0,
463
+ statusText: data?.statusText || "",
464
+ ok: Number(data?.status) >= 200 && Number(data?.status) < 300,
465
+ redirected: Boolean(data?.redirected),
466
+ headers: {
467
+ get: (name) => responseHeaders[String(name).toLowerCase()] == null ? null : String(responseHeaders[String(name).toLowerCase()]),
468
+ has: (name) => responseHeaders[String(name).toLowerCase()] != null,
469
+ forEach: (callback) => Object.keys(responseHeaders).forEach((name) => callback(String(responseHeaders[name]), name))
470
+ },
471
+ text: reading.text,
472
+ json: () => reading.text().then(JSON.parse)
473
+ };
474
+ Object.defineProperty(result, "bodyUsed", { enumerable: !0, get: () => reading.bodyUsed });
475
+ if (reading.body)
476
+ result.body = reading.body;
477
+ return result;
478
+ }
@@ -36,6 +36,31 @@ export declare interface NativeNavigation {
36
36
  open: (path: string) => string
37
37
  setOptions: (options: NativeNavigationOptions) => unknown
38
38
  onButton: (callback: (event: { id: string }) => unknown) => () => void
39
+ onAppear: (callback: () => unknown) => () => void
40
+ onDisappear: (callback: () => unknown) => () => void
41
+ isFocused: () => boolean
42
+ }
43
+ export declare interface NativeRoute {
44
+ name: string
45
+ params: Record<string, unknown>
46
+ onParams: (callback: (params: Record<string, unknown>, previous: Record<string, unknown>) => unknown) => () => void
47
+ }
48
+ /** A sound `craft.audio.play` started. */
49
+ export declare interface NativeSound {
50
+ id: string
51
+ pause: () => Promise<void>
52
+ resume: () => Promise<void>
53
+ stop: (options?: { fadeOut?: number }) => Promise<void>
54
+ setVolume: (volume: number, options?: { fade?: number }) => Promise<void>
55
+ onEnd: (callback: () => unknown) => () => void
56
+ onError: (callback: (message: string) => unknown) => () => void
57
+ }
58
+ export declare interface NativeShareOptions {
59
+ title?: string
60
+ text?: string
61
+ url?: string
62
+ files?: string[]
63
+ image?: string
39
64
  }
40
65
  export declare interface NativeStorage {
41
66
  get: <T = unknown>(key: string) => Promise<T | null>
@@ -62,7 +87,7 @@ export declare interface NativeSnapshots {
62
87
  export declare interface NativeCraft {
63
88
  platform: string
64
89
  capabilityProtocolVersion: number
65
- route: { name: string, params: Record<string, unknown> }
90
+ route: NativeRoute
66
91
  capabilities: Record<string, boolean>
67
92
  navigation: NativeNavigation
68
93
  storage: NativeStorage
@@ -98,6 +123,33 @@ export declare interface NativeCraft {
98
123
  confirm: (options?: { title?: string, message?: string, confirmLabel?: string, cancelLabel?: string, destructive?: boolean }) => Promise<boolean>
99
124
  actionSheet: (options?: { title?: string, message?: string, actions?: Array<{ id?: string, title: string, style?: 'default' | 'destructive' | 'cancel' }> }) => Promise<string | null>
100
125
  }
126
+ speech?: {
127
+ speak: (text: string, options?: { language?: string, rate?: number, interrupt?: boolean }) => Promise<boolean>
128
+ stop: () => Promise<void>
129
+ }
130
+ audio?: {
131
+ play: (url: string, options?: { loop?: boolean, volume?: number, fadeIn?: number, respectSilentSwitch?: boolean }) => Promise<NativeSound>
132
+ stopAll: (options?: { fadeOut?: number }) => Promise<void>
133
+ }
134
+ push?: {
135
+ getPermissionStatus: () => Promise<NativePermissionStatus>
136
+ requestPermission: () => Promise<NativePermissionStatus>
137
+ register: () => Promise<string>
138
+ onToken: (callback: (token: string) => unknown) => () => void
139
+ openSettings: () => Promise<boolean>
140
+ }
141
+ registerPush?: () => Promise<string>
142
+ permissions?: {
143
+ check: (permission: string) => Promise<NativePermissionStatus>
144
+ request: (permission: string) => Promise<NativePermissionStatus>
145
+ openSettings: () => Promise<void>
146
+ }
147
+ linking?: {
148
+ openURL: (url: string) => Promise<boolean>
149
+ canOpenURL: (url: string) => Promise<boolean>
150
+ }
151
+ openURL?: (url: string) => Promise<boolean>
152
+ share?: ((options: NativeShareOptions) => Promise<boolean>) & { share: (options: NativeShareOptions) => Promise<boolean> }
101
153
  health?: {
102
154
  requestAuthorization: (types: string[], options?: { write?: boolean }) => Promise<boolean>
103
155
  getData: (type: string, options?: { startDate?: number, endDate?: number }) => Promise<unknown>
@@ -121,3 +173,4 @@ export declare interface NativeCraft {
121
173
  }
122
174
  deepLinks: { getInitialURL: () => Promise<string | null>, onLink: (callback: (link: unknown) => unknown) => () => void }
123
175
  }
176
+ export type NativePermissionStatus = 'granted' | 'denied' | 'undetermined';
@@ -0,0 +1,31 @@
1
+ /**
2
+ * A `response.body` fed by `sink`. `cancel` tells the host to stop sending;
3
+ * it runs once, whichever way the reader stops.
4
+ */
5
+ export declare function createStreamingBody(encode: (text: string) => Uint8Array, cancel: () => void): { body: AnyRecord, sink: StreamSink, text: () => Promise<string>, used: () => boolean };
6
+ /**
7
+ * `EventSource`, on the streaming `fetch`. Standard but for one addition the
8
+ * browser's lacks: `new EventSource(url, { headers })`, since a native screen
9
+ * signs its requests with a token rather than a cookie.
10
+ */
11
+ export declare function createEventSourceClass(target: AnyRecord): AnyRecord;
12
+ /** Where the host's pieces go: in order, then the end or a failure. */
13
+ export declare interface StreamSink {
14
+ push: (text: string) => void
15
+ end: () => void
16
+ fail: (message: string) => void
17
+ }
18
+ /**
19
+ * Responses read as they arrive, on a native screen.
20
+ *
21
+ * A native screen's `fetch` is one request to the host and one answer, which
22
+ * is no use for a server-sent event stream: the answer never ends. A request
23
+ * that accepts `text/event-stream` goes to the host's `Network.stream`
24
+ * instead (when it advertises `eventStream`). The host answers with the head,
25
+ * then sends every piece of the body as it comes (`NETWORK_STREAM`). Here the
26
+ * pieces become a `response.body` reader, which is all the web's stream
27
+ * readers use (`@stacksjs/stx`'s `useBroadcastStream`), and an `EventSource`
28
+ * on top of that, which can send headers (a bearer token) as the browser's
29
+ * cannot.
30
+ */
31
+ declare type AnyRecord = Record<string, any> // eslint-disable-line ts/no-explicit-any;
@@ -0,0 +1,232 @@
1
+ export function createStreamingBody(encode, cancel) {
2
+ const queue = [], waiting = [], decoded = [];
3
+ let finished = !1, failure = null, cancelled = !1, locked = !1;
4
+ const stop = () => {
5
+ if (cancelled)
6
+ return;
7
+ cancelled = !0;
8
+ if (!finished)
9
+ cancel();
10
+ finished = !0;
11
+ queue.length = 0;
12
+ while (waiting.length)
13
+ waiting.shift().resolve({ done: !0, value: void 0 });
14
+ }, sink = {
15
+ push(text) {
16
+ if (finished)
17
+ return;
18
+ decoded.push(text);
19
+ const value = encode(text), reader = waiting.shift();
20
+ if (reader)
21
+ reader.resolve({ done: !1, value });
22
+ else
23
+ queue.push(value);
24
+ },
25
+ end() {
26
+ if (finished)
27
+ return;
28
+ finished = !0;
29
+ while (waiting.length)
30
+ waiting.shift().resolve({ done: !0, value: void 0 });
31
+ },
32
+ fail(message) {
33
+ if (finished)
34
+ return;
35
+ finished = !0;
36
+ failure = TypeError(message || "Network connection lost");
37
+ while (waiting.length)
38
+ waiting.shift().reject(failure);
39
+ }
40
+ }, read = () => {
41
+ if (queue.length)
42
+ return Promise.resolve({ done: !1, value: queue.shift() });
43
+ if (failure)
44
+ return Promise.reject(failure);
45
+ if (finished)
46
+ return Promise.resolve({ done: !0, value: void 0 });
47
+ return new Promise((resolve, reject) => waiting.push({ resolve, reject }));
48
+ }, body = {
49
+ get locked() {
50
+ return locked;
51
+ },
52
+ getReader() {
53
+ if (locked)
54
+ throw TypeError("The response body is already being read");
55
+ locked = !0;
56
+ return {
57
+ read,
58
+ cancel: () => {
59
+ stop();
60
+ return Promise.resolve();
61
+ },
62
+ releaseLock: () => {
63
+ locked = !1;
64
+ },
65
+ closed: Promise.resolve()
66
+ };
67
+ },
68
+ cancel: () => {
69
+ stop();
70
+ return Promise.resolve();
71
+ }
72
+ };
73
+ return { body, sink, text: async () => {
74
+ const reader = body.getReader();
75
+ while (!(await reader.read()).done)
76
+ ;
77
+ return decoded.join("");
78
+ }, used: () => locked };
79
+ }
80
+ export function createEventSourceClass(target) {
81
+
82
+ class NativeEventSource {
83
+ static CONNECTING = 0;
84
+ static OPEN = 1;
85
+ static CLOSED = 2;
86
+ CONNECTING = 0;
87
+ OPEN = 1;
88
+ CLOSED = 2;
89
+ url;
90
+ withCredentials;
91
+ readyState = 0;
92
+ onopen = null;
93
+ onmessage = null;
94
+ onerror = null;
95
+ listeners = new Map;
96
+ headers;
97
+ controller = null;
98
+ timer = null;
99
+ retry = 3000;
100
+ lastEventId = "";
101
+ constructor(url, init = {}) {
102
+ this.url = String(url);
103
+ this.withCredentials = Boolean(init.withCredentials);
104
+ this.headers = { ...init.headers || {} };
105
+ Promise.resolve().then(() => this.connect());
106
+ }
107
+ addEventListener(type, listener) {
108
+ if (typeof listener !== "function")
109
+ return;
110
+ const group = this.listeners.get(type) ?? new Set;
111
+ group.add(listener);
112
+ this.listeners.set(type, group);
113
+ }
114
+ removeEventListener(type, listener) {
115
+ this.listeners.get(type)?.delete(listener);
116
+ }
117
+ dispatchEvent(event) {
118
+ const handler = this[`on${event.type}`];
119
+ if (typeof handler === "function")
120
+ handler.call(this, event);
121
+ for (const listener of [...this.listeners.get(event.type) ?? []])
122
+ listener.call(this, event);
123
+ return !0;
124
+ }
125
+ close() {
126
+ this.readyState = 2;
127
+ if (this.timer !== null)
128
+ target.clearTimeout(this.timer);
129
+ this.timer = null;
130
+ this.controller?.abort();
131
+ this.controller = null;
132
+ }
133
+ emit(type, extra = {}) {
134
+ this.dispatchEvent({ type, target: this, currentTarget: this, ...extra });
135
+ }
136
+ reconnect() {
137
+ if (this.readyState === 2)
138
+ return;
139
+ this.readyState = 0;
140
+ this.emit("error");
141
+ if (this.readyState === 2)
142
+ return;
143
+ this.timer = target.setTimeout(() => {
144
+ this.timer = null;
145
+ this.connect();
146
+ }, this.retry);
147
+ }
148
+ async connect() {
149
+ if (this.readyState === 2)
150
+ return;
151
+ const controller = new target.AbortController;
152
+ this.controller = controller;
153
+ const headers = { Accept: "text/event-stream", "Cache-Control": "no-cache", ...this.headers };
154
+ if (this.lastEventId)
155
+ headers["Last-Event-ID"] = this.lastEventId;
156
+ let response;
157
+ try {
158
+ response = await target.fetch(this.url, { headers, signal: controller.signal });
159
+ } catch {
160
+ if (this.controller === controller)
161
+ this.reconnect();
162
+ return;
163
+ }
164
+ if (this.controller !== controller || this.readyState === 2) {
165
+ response.body?.cancel?.();
166
+ return;
167
+ }
168
+ const type = String(response.headers?.get?.("content-type") || "");
169
+ if (response.status !== 200 || !type.toLowerCase().includes("text/event-stream") || !response.body) {
170
+ this.readyState = 2;
171
+ response.body?.cancel?.();
172
+ this.emit("error");
173
+ return;
174
+ }
175
+ this.readyState = 1;
176
+ this.emit("open");
177
+ const reader = response.body.getReader(), decoder = new target.TextDecoder;
178
+ let buffer = "", data = "", event = "";
179
+ const line = (text) => {
180
+ if (text === "") {
181
+ if (data)
182
+ this.emit(event || "message", { data: data.endsWith(`
183
+ `) ? data.slice(0, -1) : data, lastEventId: this.lastEventId, origin: originOf(this.url) });
184
+ data = "";
185
+ event = "";
186
+ return;
187
+ }
188
+ if (text.startsWith(":"))
189
+ return;
190
+ const colon = text.indexOf(":"), field = colon === -1 ? text : text.slice(0, colon);
191
+ let value = colon === -1 ? "" : text.slice(colon + 1);
192
+ if (value.startsWith(" "))
193
+ value = value.slice(1);
194
+ if (field === "data")
195
+ data += `${value}
196
+ `;
197
+ else if (field === "event")
198
+ event = value;
199
+ else if (field === "id" && !value.includes("\x00"))
200
+ this.lastEventId = value;
201
+ else if (field === "retry" && /^\d+$/.test(value))
202
+ this.retry = Number(value);
203
+ };
204
+ try {
205
+ while (this.readyState !== 2) {
206
+ const { done, value } = await reader.read();
207
+ if (done)
208
+ break;
209
+ buffer += decoder.decode(value, { stream: !0 });
210
+ let end;
211
+ while ((end = buffer.search(/\r\n|\r|\n/)) !== -1) {
212
+ const width = buffer[end] === "\r" && buffer[end + 1] === `
213
+ ` ? 2 : 1;
214
+ if (buffer[end] === "\r" && end + 1 === buffer.length)
215
+ break;
216
+ line(buffer.slice(0, end));
217
+ buffer = buffer.slice(end + width);
218
+ }
219
+ }
220
+ } catch {} finally {
221
+ reader.cancel?.().catch?.(() => {});
222
+ }
223
+ if (this.controller === controller)
224
+ this.reconnect();
225
+ }
226
+ }
227
+ return NativeEventSource;
228
+ }
229
+ function originOf(url) {
230
+ const match = /^([a-z][a-z0-9+.-]*:\/\/[^/?#]+)/i.exec(url);
231
+ return match ? match[1] : "";
232
+ }