@stacksjs/stx 0.2.574 → 0.2.576

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 (175) hide show
  1. package/README.md +3 -0
  2. package/dist/chunk-08a98yqt.js +2 -0
  3. package/dist/chunk-181m21rg.js +2 -0
  4. package/dist/{chunk-nxw03sy9.js → chunk-1edvsndv.js} +2 -2
  5. package/dist/chunk-1nbn56jw.js +2 -0
  6. package/dist/{chunk-a3w3jc0t.js → chunk-1w9ngqpv.js} +3 -3
  7. package/dist/{chunk-ta50ym5j.js → chunk-1wkpxa58.js} +2 -2
  8. package/dist/{chunk-6z57saf5.js → chunk-2ry2pfpe.js} +1 -1
  9. package/dist/{chunk-ss4h5ch3.js → chunk-32gycb72.js} +1 -1
  10. package/dist/{chunk-g8dx2jew.js → chunk-34fajf1n.js} +100 -99
  11. package/dist/chunk-3bj1w990.js +2 -0
  12. package/dist/{chunk-kcq2ed1d.js → chunk-3gqrv02t.js} +2 -2
  13. package/dist/chunk-4a12azrb.js +2 -0
  14. package/dist/{chunk-e7pjsrfc.js → chunk-4z21afpp.js} +2 -2
  15. package/dist/{chunk-r5ce7mkg.js → chunk-5dm4k229.js} +2 -2
  16. package/dist/chunk-6fpynp8q.js +2 -0
  17. package/dist/{chunk-ytf3qkaw.js → chunk-6q3yszw9.js} +1 -1
  18. package/dist/{chunk-crj0yqc6.js → chunk-6rfm6b1c.js} +1 -1
  19. package/dist/chunk-6ryab0yy.js +2 -0
  20. package/dist/{chunk-3pr388w5.js → chunk-6sasxbv9.js} +1 -1
  21. package/dist/chunk-6w9km7qb.js +2 -0
  22. package/dist/{chunk-4k6cb5fg.js → chunk-6wz6f8d5.js} +3 -3
  23. package/dist/{chunk-cp5903cg.js → chunk-7j9m4d7x.js} +1 -1
  24. package/dist/{chunk-7gxn7mvd.js → chunk-7y73q42g.js} +2 -2
  25. package/dist/chunk-98r9jk2b.js +2 -0
  26. package/dist/chunk-9dgygz8d.js +2 -0
  27. package/dist/chunk-a51f04an.js +2 -0
  28. package/dist/chunk-aa52jhak.js +2 -0
  29. package/dist/chunk-agk478t4.js +3 -0
  30. package/dist/chunk-ambynnzb.js +2 -0
  31. package/dist/chunk-asbq9cgs.js +2 -0
  32. package/dist/{chunk-1n9bxdnh.js → chunk-bbdg3sqq.js} +2 -2
  33. package/dist/{chunk-69k5t6pj.js → chunk-bctjmaxg.js} +53 -53
  34. package/dist/{chunk-9yht5n7g.js → chunk-bks1fe5e.js} +1 -1
  35. package/dist/chunk-bmtsb5mr.js +2 -0
  36. package/dist/chunk-c8rd3573.js +2 -0
  37. package/dist/chunk-d4b8cgvt.js +2 -0
  38. package/dist/chunk-d7skqhrc.js +2 -0
  39. package/dist/{chunk-hqda3vcw.js → chunk-d8ek63nc.js} +1 -1
  40. package/dist/chunk-f2y8bwdd.js +2 -0
  41. package/dist/{chunk-0px2ab3m.js → chunk-fkbthywg.js} +5 -5
  42. package/dist/chunk-g9vtny6q.js +2 -0
  43. package/dist/{chunk-f0mbj8w9.js → chunk-gjp2jxrp.js} +1 -1
  44. package/dist/{chunk-gh0q6jrm.js → chunk-gpb22a8n.js} +2 -2
  45. package/dist/{chunk-anjm087t.js → chunk-h1n43e5n.js} +2 -2
  46. package/dist/{chunk-gdxhe7ae.js → chunk-h72befy4.js} +2 -2
  47. package/dist/chunk-haeb904b.js +3 -0
  48. package/dist/chunk-hcsrj8z6.js +3 -0
  49. package/dist/chunk-hj1bntaa.js +2 -0
  50. package/dist/chunk-hwy3aw5v.js +2 -0
  51. package/dist/chunk-hyafyqy6.js +2 -0
  52. package/dist/{chunk-e27njk86.js → chunk-j4zyq2ap.js} +8 -8
  53. package/dist/chunk-j75hqvgt.js +2 -0
  54. package/dist/chunk-j83ax407.js +2 -0
  55. package/dist/{chunk-e40qpeg5.js → chunk-je0cttam.js} +1 -1
  56. package/dist/{chunk-jwe7yq8m.js → chunk-jgrtvs81.js} +2 -2
  57. package/dist/chunk-k3hfwve1.js +2 -0
  58. package/dist/{chunk-3kc7af8c.js → chunk-kskyfss0.js} +2 -2
  59. package/dist/{chunk-sej3ng5k.js → chunk-mp99h8wh.js} +3 -3
  60. package/dist/{chunk-svvavwp2.js → chunk-n0kw3q6p.js} +1 -1
  61. package/dist/{chunk-0gt7e1ns.js → chunk-n829xbbq.js} +1 -1
  62. package/dist/chunk-nd3qttxh.js +2 -0
  63. package/dist/{chunk-myhh1zsm.js → chunk-ndc1bmj7.js} +1 -1
  64. package/dist/chunk-nn462qm9.js +2 -0
  65. package/dist/chunk-nr07vxm2.js +2 -0
  66. package/dist/{chunk-yhqhv8mp.js → chunk-nskvepjv.js} +414 -162
  67. package/dist/{chunk-8hp6722y.js → chunk-pqkb1m5x.js} +3 -3
  68. package/dist/chunk-q7a5pwaz.js +2 -0
  69. package/dist/{chunk-yf90vn5t.js → chunk-qfb34r6k.js} +3 -3
  70. package/dist/chunk-r51vyhms.js +2 -0
  71. package/dist/{chunk-k5rrp1bt.js → chunk-s68bqf62.js} +1 -1
  72. package/dist/{chunk-32pxa1r0.js → chunk-sf7z2ar9.js} +3 -3
  73. package/dist/{chunk-825m59jr.js → chunk-sn3htx1z.js} +1 -1
  74. package/dist/chunk-svavrmxb.js +2 -0
  75. package/dist/chunk-sw7mvg9p.js +2 -0
  76. package/dist/{chunk-06hx32h4.js → chunk-szfkkbve.js} +1 -1
  77. package/dist/{chunk-c0ewddb3.js → chunk-tasjpnbf.js} +2 -2
  78. package/dist/{chunk-3dr757vb.js → chunk-tybk9hw9.js} +7 -7
  79. package/dist/chunk-tz40t18m.js +2 -0
  80. package/dist/chunk-v1k0bdsg.js +2 -0
  81. package/dist/chunk-vd10tty0.js +2 -0
  82. package/dist/{chunk-501h1mer.js → chunk-vmetcczm.js} +4 -4
  83. package/dist/{chunk-vnh550b5.js → chunk-vnsby98n.js} +1 -1
  84. package/dist/{chunk-zfw39q56.js → chunk-vqkzhd19.js} +1 -1
  85. package/dist/{chunk-bb5a8adb.js → chunk-vw1rmevt.js} +3 -3
  86. package/dist/{chunk-71zwgxws.js → chunk-w1yft5gg.js} +1 -1
  87. package/dist/chunk-w6sa921x.js +2 -0
  88. package/dist/{chunk-1x2x3xgc.js → chunk-wvk932dp.js} +1 -1
  89. package/dist/{chunk-nc0ba89b.js → chunk-x5xwe5nr.js} +6 -6
  90. package/dist/{chunk-76437eb4.js → chunk-xh0808cd.js} +1 -1
  91. package/dist/{chunk-b10n7cpe.js → chunk-xk2v20xe.js} +2 -2
  92. package/dist/{chunk-0ppzstqj.js → chunk-xsxh7h8z.js} +2 -2
  93. package/dist/{chunk-n8hnrgen.js → chunk-y120qq1a.js} +4 -4
  94. package/dist/{chunk-byhsfnkc.js → chunk-zak5xare.js} +1 -1
  95. package/dist/chunk-zcw74jmk.js +2 -0
  96. package/dist/chunk-zxvndwaz.js +2 -0
  97. package/dist/cli.js +58 -58
  98. package/dist/client/signals-context-runtime.js +200 -0
  99. package/dist/client/signals-effect-runtime.js +12 -1
  100. package/dist/client/signals-globals-runtime.js +3 -1
  101. package/dist/client/signals-kept-runtime.d.ts +1 -1
  102. package/dist/client/signals-kept-runtime.js +8 -3
  103. package/dist/client/signals-public-api-runtime.js +2 -0
  104. package/dist/client/signals-reactive-runtime.js +0 -1
  105. package/dist/client/signals-state-runtime.js +53 -20
  106. package/dist/composables/index.d.ts +2 -0
  107. package/dist/composables/index.js +1 -0
  108. package/dist/composables/use-cached-query.js +2 -1
  109. package/dist/craft-entry.js +2 -2
  110. package/dist/craft.js +2 -2
  111. package/dist/includes.js +10 -1
  112. package/dist/index.d.ts +2 -0
  113. package/dist/index.js +1 -0
  114. package/dist/native/runtime/craft-bridge.js +31 -9
  115. package/dist/native/runtime/craft.d.ts +3 -2
  116. package/dist/native/testing.d.ts +115 -0
  117. package/dist/native/testing.js +421 -0
  118. package/dist/offline/query-cache.d.ts +2 -0
  119. package/dist/offline/query-cache.js +43 -33
  120. package/dist/pwa.js +3 -3
  121. package/dist/reactivity.d.ts +36 -1
  122. package/dist/reactivity.js +33 -9
  123. package/dist/runtime-globals.js +2 -0
  124. package/dist/shared-request.d.ts +46 -0
  125. package/dist/shared-request.js +56 -0
  126. package/dist/signals-api.d.ts +32 -6
  127. package/dist/signals-api.js +42 -18
  128. package/dist/signals.js +2 -1
  129. package/dist/ssg.js +3 -3
  130. package/dist/stx-module.d.ts +2 -0
  131. package/package.json +9 -5
  132. package/stx-module.d.ts +2 -0
  133. package/stx.d.ts +54 -4
  134. package/dist/chunk-1m5pagp3.js +0 -2
  135. package/dist/chunk-27ja2rpd.js +0 -2
  136. package/dist/chunk-2b0p7am3.js +0 -2
  137. package/dist/chunk-3k6q1481.js +0 -2
  138. package/dist/chunk-42h0kvng.js +0 -2
  139. package/dist/chunk-4eff1v2p.js +0 -2
  140. package/dist/chunk-5n2v9g2c.js +0 -2
  141. package/dist/chunk-68ygpbta.js +0 -2
  142. package/dist/chunk-6gjfres0.js +0 -2
  143. package/dist/chunk-7debnvz9.js +0 -2
  144. package/dist/chunk-a77gbp9x.js +0 -2
  145. package/dist/chunk-bgbz0wzq.js +0 -2
  146. package/dist/chunk-bgr7fqhs.js +0 -2
  147. package/dist/chunk-bjfrwcfh.js +0 -2
  148. package/dist/chunk-c6jyp7ss.js +0 -3
  149. package/dist/chunk-cdt5pg28.js +0 -2
  150. package/dist/chunk-cfh798k7.js +0 -2
  151. package/dist/chunk-dax3zkmm.js +0 -2
  152. package/dist/chunk-dn676tdp.js +0 -2
  153. package/dist/chunk-dtbj816p.js +0 -2
  154. package/dist/chunk-e23cg45k.js +0 -2
  155. package/dist/chunk-ecwpsjpd.js +0 -2
  156. package/dist/chunk-h8vk3q9n.js +0 -2
  157. package/dist/chunk-hq8vxds5.js +0 -3
  158. package/dist/chunk-j8pamkbh.js +0 -2
  159. package/dist/chunk-mfm7ezh6.js +0 -2
  160. package/dist/chunk-mp16jxcg.js +0 -2
  161. package/dist/chunk-n1c9j5qv.js +0 -2
  162. package/dist/chunk-n61v7e3s.js +0 -2
  163. package/dist/chunk-nf63pk4s.js +0 -2
  164. package/dist/chunk-p5cry5s7.js +0 -2
  165. package/dist/chunk-r8qhex33.js +0 -2
  166. package/dist/chunk-rqvn1s52.js +0 -2
  167. package/dist/chunk-sjsant53.js +0 -2
  168. package/dist/chunk-snzh9z3g.js +0 -3
  169. package/dist/chunk-ty8g61y9.js +0 -2
  170. package/dist/chunk-v1k6w4z5.js +0 -2
  171. package/dist/chunk-vm7zv0gc.js +0 -2
  172. package/dist/chunk-vnxc48en.js +0 -2
  173. package/dist/chunk-y7vbwhh7.js +0 -2
  174. package/dist/chunk-yvyypd92.js +0 -2
  175. package/dist/chunk-zpm02e15.js +0 -2
@@ -137,11 +137,12 @@ export declare interface NativeCraft {
137
137
  snapshots: NativeSnapshots
138
138
  appearance: { colorScheme: () => 'light' | 'dark' }
139
139
  haptics: {
140
- impact: (style?: string) => Promise<void>
140
+ impact: (style?: 'light' | 'medium' | 'heavy' | 'soft' | 'rigid' | (string & {})) => Promise<void>
141
141
  notification: (type?: 'success' | 'warning' | 'error') => Promise<void>
142
142
  selection: () => Promise<void>
143
+ prepare: (kind?: string) => Promise<void>
143
144
  }
144
- haptic: (style?: string) => Promise<unknown>
145
+ haptic: (style?: string) => Promise<void>
145
146
  clipboard: { write: (text: string) => Promise<unknown>, read: () => Promise<string> }
146
147
  device: { getInfo: () => Promise<Record<string, unknown>> }
147
148
  biometrics: {
@@ -0,0 +1,115 @@
1
+ import path from 'node:path';
2
+ import vm from 'node:vm';
3
+ /** Wait for `check` to hold, polling every 5ms; throws after `timeoutMs`. */
4
+ export declare function waitFor(check: () => boolean, description: string, timeoutMs?: number): Promise<void>;
5
+ /**
6
+ * Compile one screen from its source, as the single-screen native compiler
7
+ * does: for a test that writes the template inline.
8
+ */
9
+ export declare function compileNativeScreen(source: string, options?: { name?: string, minify?: boolean }): Promise<{ code: string, diagnostics: Array<{ message: string }> }>;
10
+ /** End every screen still running. Registered after each test when run under `bun test`. */
11
+ export declare function unmountAllNativeScreens(): void;
12
+ /** Mount a compiled native bundle as screen `screen`, on a fake phone. */
13
+ export declare function mountNativeScreen(code: string, screen: string, options?: NativeScreenOptions): NativeScreen;
14
+ /** An API answer with this status and body. */
15
+ export declare const status: (code: number, body?: unknown) => StatusAnswer;
16
+ export declare interface NativeNode {
17
+ id: string
18
+ type: string
19
+ props: Record<string, any>
20
+ style: Record<string, any>
21
+ events: Record<string, string>
22
+ children: Array<NativeNode | string>
23
+ key?: string
24
+ }
25
+ export declare interface NativeOperation { op: string, id: string, parentId?: string, childId?: string, index?: number, node?: NativeNode, patch?: Partial<NativeNode> }
26
+ export declare interface NativeMessage { id: string, type: string, payload: { document?: NativeNode, operations?: NativeOperation[], handlerId?: string } & Record<string, unknown> }
27
+ /**
28
+ * A response the screen reads as it arrives (`Accept: text/event-stream`), as
29
+ * Craft's host streams one (`eventStream`): the test writes what the server
30
+ * would, and sees whether the screen still reads it.
31
+ */
32
+ export declare interface OpenStream {
33
+ path: string
34
+ open: boolean
35
+ write: (text: string) => void
36
+ end: () => void
37
+ }
38
+ export declare interface NativeScreenOptions {
39
+ initialAppState?: 'active' | 'background'
40
+ apiBase?: string
41
+ api?: (path: string, init: { method?: string, body?: any, headers?: Record<string, string>, signal?: AbortSignal }) => unknown
42
+ requestLabel?: (method: string, path: string, init: { headers?: Record<string, string> }) => string
43
+ snapshots?: Record<string, unknown>
44
+ snapshotWrite?: (name: string, value: unknown) => Promise<unknown>
45
+ dialog?: { actionSheet?: (options: any) => Promise<string>, confirm?: (options: any) => Promise<boolean> }
46
+ colorScheme?: 'light' | 'dark'
47
+ params?: Record<string, unknown>
48
+ capabilities?: string[]
49
+ capabilityTimeoutMs?: number
50
+ platform?: 'ios' | 'android' | 'web'
51
+ native?: (module: string, method: string, args: unknown[]) => unknown
52
+ files?: { pickImage: { path: string, name: string, type: string, size: number } | null }
53
+ secureStorage?: Record<string, string>
54
+ keychain?: Record<string, string>
55
+ storage?: Record<string, unknown>
56
+ offline?: () => boolean
57
+ stream?: (path: string) => StatusAnswer | undefined
58
+ globals?: Record<string, unknown>
59
+ craft?: Record<string, unknown>
60
+ appURL?: string
61
+ appVersion?: string
62
+ appBuild?: string
63
+ }
64
+ /** A mounted native screen: what `mountNativeScreen` returns. */
65
+ export declare interface NativeScreen {
66
+ nodes: Map<string, NativeNode>
67
+ messages: NativeMessage[]
68
+ requests: string[]
69
+ headers: Array<Record<string, string>>
70
+ opened: string[]
71
+ replaced: string[]
72
+ moves: Array<'back' | 'root'>
73
+ stored: Record<string, unknown>
74
+ secureStorage: Record<string, string>
75
+ bars: any[]
76
+ snapshots: Record<string, unknown>
77
+ natives: string[]
78
+ streams: OpenStream[]
79
+ animations: Array<Record<string, unknown>>
80
+ alerts: any[]
81
+ picks: any[]
82
+ removed: Array<string | null>
83
+ context: vm.Context
84
+ all: () => NativeNode[]
85
+ find: (predicate: (node: NativeNode) => boolean) => NativeNode | undefined
86
+ byTestID: (id: string) => NativeNode | undefined
87
+ ofType: (type: string) => NativeNode[]
88
+ texts: () => string[]
89
+ press: (node: NativeNode, event?: string, nativeEvent?: Record<string, unknown>) => void
90
+ type: (node: NativeNode, text: string) => void
91
+ barButtons: () => string[]
92
+ tapBar: (id: string) => void
93
+ appState: (state: 'active' | 'background' | 'inactive') => void
94
+ background: () => void
95
+ resume: () => void
96
+ appearance: (scheme: 'light' | 'dark') => void
97
+ appear: () => void
98
+ disappear: () => void
99
+ newParams: (params: Record<string, unknown>) => void
100
+ craftEvent: (event: string, detail?: unknown) => void
101
+ keepSnapshot: (name: string, value?: unknown) => void
102
+ setOnline: (online: boolean) => void
103
+ send: (type: string, payload?: Record<string, unknown>) => void
104
+ waitFor: (check: () => boolean, description: string, timeoutMs?: number) => Promise<void>
105
+ settle: (ms?: number) => Promise<void>
106
+ operations: () => NativeOperation[]
107
+ readonly ended: boolean
108
+ unmount: () => void
109
+ }
110
+ /** An API answer other than 200, for `api` to return: `status(403, { error })`. */
111
+ export declare class StatusAnswer {
112
+ readonly status: number;
113
+ readonly body: unknown;
114
+ constructor(status: number, body?: unknown);
115
+ }
@@ -0,0 +1,421 @@
1
+ var {require}=import.meta;import path from "node:path";
2
+ import vm from "node:vm";
3
+ import { compileSharedScreenBundle } from "./compiler/bundle.js";
4
+ import { NativeFormData } from "./runtime/jsc-globals.js";
5
+ import { createTempDir } from "../temp-dir.js";
6
+
7
+ export class StatusAnswer {
8
+ status;
9
+ body;
10
+ constructor(status, body = {}) {
11
+ this.status = status;
12
+ this.body = body;
13
+ }
14
+ }
15
+ export const status = (code, body) => new StatusAnswer(code, body);
16
+ export async function waitFor(check, description, timeoutMs = 5000) {
17
+ const started = performance.now();
18
+ while (!check()) {
19
+ if (performance.now() - started >= timeoutMs)
20
+ throw Error(`Timed out waiting for ${description}`);
21
+ await Bun.sleep(5);
22
+ }
23
+ }
24
+ export async function compileNativeScreen(source, options = {}) {
25
+ const root = createTempDir("stx-native-testing-"), file = path.join(root, `${options.name || "Screen"}.stx`);
26
+ await Bun.write(file, source);
27
+ const result = await compileSharedScreenBundle(file, { root, minify: options.minify });
28
+ return { code: result.code, diagnostics: result.diagnostics };
29
+ }
30
+ const running = new Set;
31
+ export function unmountAllNativeScreens() {
32
+ for (const end of [...running])
33
+ end();
34
+ }
35
+ try {
36
+ const { afterEach } = require("bun:test");
37
+ afterEach(unmountAllNativeScreens);
38
+ } catch {}
39
+ const copy = (value) => JSON.parse(JSON.stringify(value));
40
+ export function mountNativeScreen(code, screen, options = {}) {
41
+ let ended = !1, online = !0;
42
+ const timeouts = new Set, intervals = new Set, timers = {
43
+ setTimeout: (run, ms, ...args) => {
44
+ if (ended)
45
+ return 0;
46
+ const id = setTimeout((...rest) => {
47
+ timeouts.delete(id);
48
+ if (!ended)
49
+ run(...rest);
50
+ }, ms, ...args);
51
+ timeouts.add(id);
52
+ return id;
53
+ },
54
+ clearTimeout: (id) => {
55
+ timeouts.delete(id);
56
+ clearTimeout(id);
57
+ },
58
+ setInterval: (run, ms, ...args) => {
59
+ if (ended)
60
+ return 0;
61
+ const id = setInterval((...rest) => {
62
+ if (!ended)
63
+ run(...rest);
64
+ }, ms, ...args);
65
+ intervals.add(id);
66
+ return id;
67
+ },
68
+ clearInterval: (id) => {
69
+ intervals.delete(id);
70
+ clearInterval(id);
71
+ }
72
+ }, apiBase = options.apiBase || "", label = options.requestLabel || ((method, at, init) => `${method} ${at}${init.headers && Object.keys(init.headers).some((name) => name.toLowerCase() === "authorization") ? "" : " (guest)"}`), nodes = new Map, messages = [], requests = [], headers = [], opened = [], replaced = [], moves = [], stored = copy(options.storage ?? {}), natives = [], animations = [], streams = [], secureStorage = { ...options.keychain, ...options.secureStorage }, bars = [], alerts = [], picks = [], removed = [], snapshots = { ...options.snapshots };
73
+ let receive = () => {};
74
+ const visit = (node) => {
75
+ nodes.set(node.id, node);
76
+ for (const child of node.children || [])
77
+ if (typeof child !== "string")
78
+ visit(child);
79
+ }, openStream = (at, signal) => {
80
+ const queue = [], waiting = [], encode = (text) => new TextEncoder().encode(text), stop = () => {
81
+ stream.open = !1;
82
+ while (waiting.length)
83
+ waiting.shift()({ done: !0 });
84
+ }, stream = {
85
+ path: at,
86
+ open: !0,
87
+ write: (text) => {
88
+ if (!stream.open)
89
+ return;
90
+ const reader = waiting.shift();
91
+ if (reader)
92
+ reader({ done: !1, value: encode(text) });
93
+ else
94
+ queue.push(text);
95
+ },
96
+ end: stop
97
+ };
98
+ streams.push(stream);
99
+ signal?.addEventListener?.("abort", stop);
100
+ const reader = {
101
+ read: () => queue.length ? Promise.resolve({ done: !1, value: encode(queue.shift()) }) : stream.open ? new Promise((resolve) => waiting.push(resolve)) : Promise.resolve({ done: !0 }),
102
+ cancel: async () => stop(),
103
+ releaseLock: () => {}
104
+ };
105
+ return {
106
+ ok: !0,
107
+ status: 200,
108
+ headers: { get: (name) => name.toLowerCase() === "content-type" ? "text/event-stream" : null },
109
+ body: { getReader: () => reader, cancel: async () => stop() }
110
+ };
111
+ };
112
+ let fetching = 0, answeredAt = 0;
113
+ const offlineNow = () => !online || Boolean(options.offline?.()), context = vm.createContext({
114
+ console,
115
+ Promise,
116
+ Date,
117
+ Map,
118
+ Set,
119
+ WeakMap,
120
+ WeakSet,
121
+ ...timers,
122
+ Intl,
123
+ FormData: NativeFormData,
124
+ crypto: globalThis.crypto,
125
+ ...options.globals,
126
+ __stxNativeRoute: screen,
127
+ __stxNativeParams: options.params ?? {},
128
+ fetch: async (url, init = {}) => {
129
+ if (ended)
130
+ throw Object.assign(TypeError("The screen has ended."), { code: "NETWORK_ERROR" });
131
+ fetching++;
132
+ let counted = !0;
133
+ try {
134
+ await Bun.sleep(2);
135
+ if (ended || offlineNow())
136
+ throw Object.assign(TypeError("The Internet connection appears to be offline."), { code: "NETWORK_ERROR" });
137
+ const at = apiBase && String(url).startsWith(apiBase) ? String(url).slice(apiBase.length) : String(url);
138
+ requests.push(label(init.method || "GET", at, init));
139
+ headers.push(init.headers || {});
140
+ if (Object.entries(init.headers || {}).some(([name, value]) => name.toLowerCase() === "accept" && /text\/event-stream/i.test(String(value)))) {
141
+ const refused = options.stream?.(at);
142
+ if (refused)
143
+ return { ok: refused.status < 300, status: refused.status, headers: { get: () => "application/json" }, json: async () => refused.body };
144
+ return openStream(at, init.signal);
145
+ }
146
+ const given = options.api?.(at, init);
147
+ let answer = given;
148
+ if (given instanceof Promise) {
149
+ fetching--;
150
+ counted = !1;
151
+ const signal = init.signal;
152
+ answer = await (signal ? Promise.race([given, new Promise((_, reject) => signal.addEventListener("abort", () => reject(Object.assign(Error("The operation was aborted."), { name: "AbortError" }))))]) : given);
153
+ }
154
+ if (answer === void 0)
155
+ return { ok: !1, status: 404, json: async () => ({}) };
156
+ if (answer instanceof StatusAnswer)
157
+ return { ok: answer.status < 300, status: answer.status, json: async () => answer.body };
158
+ return { ok: !0, status: 200, json: async () => answer };
159
+ } finally {
160
+ if (counted)
161
+ fetching--;
162
+ answeredAt = performance.now();
163
+ }
164
+ },
165
+ craft: {
166
+ secureStorage: { getSync: (key) => secureStorage[key] ?? null },
167
+ storage: {
168
+ getSync: (key) => (key in stored) ? copy(stored[key]) : null,
169
+ setSync: (key, value) => {
170
+ if (value === null || value === void 0)
171
+ delete stored[key];
172
+ else
173
+ stored[key] = copy(value);
174
+ }
175
+ },
176
+ snapshots: {
177
+ get: (name) => snapshots[name] ?? null,
178
+ set: async (name, value) => {
179
+ await options.snapshotWrite?.(name, value);
180
+ if (value === null || value === void 0)
181
+ delete snapshots[name];
182
+ else
183
+ snapshots[name] = copy(value);
184
+ return !0;
185
+ },
186
+ clear: async (keep = []) => {
187
+ for (const name of Object.keys(snapshots))
188
+ if (!keep.includes(name))
189
+ delete snapshots[name];
190
+ return !0;
191
+ },
192
+ onChange: () => () => {}
193
+ },
194
+ lifecycle: { onStateChange: () => () => {} },
195
+ ...options.files ? {
196
+ files: {
197
+ pickImage: async (request) => {
198
+ picks.push(copy(request ?? {}));
199
+ return options.files.pickImage;
200
+ },
201
+ remove: async (file) => {
202
+ removed.push(file?.path ?? null);
203
+ return !0;
204
+ }
205
+ }
206
+ } : {},
207
+ dialog: {
208
+ ...options.dialog,
209
+ alert: async (alert) => {
210
+ alerts.push(copy(alert));
211
+ }
212
+ },
213
+ navigation: {
214
+ setOptions: (value) => bars.push(copy(value)),
215
+ open: (where) => {
216
+ opened.push(where);
217
+ return "";
218
+ },
219
+ back: () => "",
220
+ push: () => ""
221
+ },
222
+ ...options.craft
223
+ },
224
+ __stxNativeBridge: {
225
+ platform: options.platform ?? "ios",
226
+ capabilityTimeoutMs: options.capabilityTimeoutMs ?? 100,
227
+ colorScheme: options.colorScheme ?? "light",
228
+ capabilities: options.capabilities ?? [],
229
+ initialAppState: options.initialAppState ?? "active",
230
+ appURL: options.appURL ?? "https://fixture.invalid/m",
231
+ appVersion: options.appVersion ?? "1.0.0",
232
+ appBuild: options.appBuild ?? "1",
233
+ postMessage: (raw) => {
234
+ const message = JSON.parse(raw);
235
+ messages.push(JSON.parse(raw));
236
+ if (message.payload.document)
237
+ visit(message.payload.document);
238
+ for (const operation of message.payload.operations || []) {
239
+ if (operation.op === "removeNode") {
240
+ const drop = (node) => {
241
+ if (!node)
242
+ return;
243
+ nodes.delete(node.id);
244
+ for (const child of node.children || [])
245
+ if (typeof child !== "string")
246
+ drop(child);
247
+ };
248
+ drop(nodes.get(operation.id));
249
+ for (const parent of nodes.values())
250
+ parent.children = parent.children.filter((child) => typeof child === "string" || child.id !== operation.id);
251
+ }
252
+ if (operation.node)
253
+ visit({ ...operation.node, id: operation.id, events: operation.node.events || {}, children: operation.node.children || [] });
254
+ if (operation.op === "insertChild" || operation.op === "moveChild") {
255
+ const child = nodes.get(operation.childId), parent = nodes.get(operation.parentId);
256
+ if (child && parent) {
257
+ for (const owner of nodes.values())
258
+ owner.children = owner.children.filter((value) => typeof value === "string" || value.id !== child.id);
259
+ parent.children.splice(operation.index ?? parent.children.length, 0, child);
260
+ }
261
+ }
262
+ const node = nodes.get(operation.id);
263
+ if (node && operation.patch) {
264
+ node.style = { ...node.style, ...operation.patch.style };
265
+ node.props = { ...node.props, ...operation.patch.props };
266
+ node.events = { ...node.events, ...operation.patch.events };
267
+ if (operation.patch.children)
268
+ node.children = operation.patch.children;
269
+ }
270
+ }
271
+ if (message.type === "NAVIGATE_OPEN")
272
+ opened.push(String(message.payload.path));
273
+ if (message.type === "NAVIGATE_REPLACE") {
274
+ const where = String(message.payload.screen);
275
+ replaced.push(where);
276
+ opened.push(where);
277
+ }
278
+ if (message.type === "ANIMATE_NEXT")
279
+ animations.push({ ...message.payload });
280
+ if (message.type === "NAVIGATE_BACK" || message.type === "NAVIGATE_POP_TO_ROOT")
281
+ moves.push(message.type === "NAVIGATE_BACK" ? "back" : "root");
282
+ if (message.type === "API_REQUEST") {
283
+ const request = message.payload;
284
+ natives.push(`${request.module}.${request.method}`);
285
+ Promise.resolve().then(async () => {
286
+ const answer = await options.native?.(request.module, request.method, request.args);
287
+ if (request.module === "SecureStorage" && ["set", "remove"].includes(request.method)) {
288
+ if (answer === !1)
289
+ return !1;
290
+ const key = String(request.args[0]);
291
+ if (request.method === "set")
292
+ secureStorage[key] = String(request.args[1]);
293
+ else
294
+ delete secureStorage[key];
295
+ return !0;
296
+ }
297
+ if (request.module === "Storage" && request.method === "set") {
298
+ if (answer === !1)
299
+ return !1;
300
+ stored[String(request.args[0])] = copy(request.args[1]);
301
+ return !0;
302
+ }
303
+ if (request.module === "Storage" && request.method === "remove") {
304
+ if (answer === !1)
305
+ return !1;
306
+ delete stored[String(request.args[0])];
307
+ return !0;
308
+ }
309
+ return answer ?? null;
310
+ }).then((data) => {
311
+ if (!ended)
312
+ receive(JSON.stringify({ type: "API_RESPONSE", correlationId: message.id, payload: { data } }));
313
+ }, (error) => {
314
+ if (!ended)
315
+ receive(JSON.stringify({ type: "API_ERROR", correlationId: message.id, payload: { code: error?.code || "NATIVE_ERROR", message: error?.message || "Native request failed" } }));
316
+ });
317
+ }
318
+ },
319
+ onMessage: (callback) => {
320
+ receive = (raw) => {
321
+ if (!ended)
322
+ callback(raw);
323
+ };
324
+ }
325
+ }
326
+ });
327
+ vm.runInContext(code, context);
328
+ const end = () => {
329
+ if (ended)
330
+ return;
331
+ running.delete(end);
332
+ try {
333
+ context.__stxNativeUnmount?.();
334
+ } finally {
335
+ ended = !0;
336
+ for (const id of timeouts)
337
+ clearTimeout(id);
338
+ for (const id of intervals)
339
+ clearInterval(id);
340
+ timeouts.clear();
341
+ intervals.clear();
342
+ streams.forEach((stream) => stream.end());
343
+ }
344
+ };
345
+ running.add(end);
346
+ const send = (type, payload = {}) => receive(JSON.stringify({ type, payload })), all = () => [...nodes.values()], press = (node, event = "onPress", nativeEvent = {}) => {
347
+ if (!node)
348
+ throw Error(`nothing to ${event}`);
349
+ if (!node.events[event])
350
+ throw Error(`${node.type} has no ${event}`);
351
+ send("EVENT", { handlerId: node.events[event], nativeEvent });
352
+ }, appState = (state) => send("APP_STATE", { state });
353
+ return {
354
+ nodes,
355
+ messages,
356
+ requests,
357
+ headers,
358
+ opened,
359
+ replaced,
360
+ moves,
361
+ stored,
362
+ secureStorage,
363
+ bars,
364
+ snapshots,
365
+ natives,
366
+ streams,
367
+ animations,
368
+ alerts,
369
+ picks,
370
+ removed,
371
+ context,
372
+ all,
373
+ find: (predicate) => all().find(predicate),
374
+ byTestID: (id) => all().find((node) => node.props?.testID === id),
375
+ ofType: (type) => all().filter((node) => node.type === type),
376
+ texts: () => all().flatMap((node) => node.children.filter((child) => typeof child === "string")),
377
+ press,
378
+ type: (node, text) => press(node, "onChangeText", { text }),
379
+ barButtons: () => (bars.at(-1)?.rightButtons || []).map((button) => button.id),
380
+ tapBar: (id) => {
381
+ if (!(bars.at(-1)?.rightButtons || []).some((button) => button.id === id))
382
+ throw Error(`no bar button ${id}`);
383
+ send("NAV_BUTTON", { id });
384
+ },
385
+ appState,
386
+ background: () => appState("background"),
387
+ resume: () => appState("active"),
388
+ appearance: (scheme) => send("APPEARANCE", { colorScheme: scheme }),
389
+ appear: () => send("SCREEN_FOCUS", { focused: !0 }),
390
+ disappear: () => send("SCREEN_FOCUS", { focused: !1 }),
391
+ newParams: (params) => send("ROUTE_PARAMS", { params }),
392
+ craftEvent: (event, detail) => send("CRAFT_EVENT", { event, detail }),
393
+ keepSnapshot: (name, value) => {
394
+ if (value === null)
395
+ delete snapshots[name];
396
+ else if (value !== void 0)
397
+ snapshots[name] = copy(value);
398
+ send("SNAPSHOT_CHANGED", { name });
399
+ },
400
+ setOnline: (value) => {
401
+ online = value;
402
+ },
403
+ send,
404
+ waitFor: (check, description, timeoutMs = 5000) => waitFor(() => {
405
+ if (ended)
406
+ throw Error(`${screen} ended while waiting for ${description}`);
407
+ return check();
408
+ }, `${screen}: ${description}`, timeoutMs),
409
+ settle: async (ms = 30) => {
410
+ const started = performance.now();
411
+ await Bun.sleep(ms);
412
+ while (performance.now() - started < 5000 && (fetching > 0 || performance.now() - answeredAt < ms))
413
+ await Bun.sleep(5);
414
+ },
415
+ operations: () => messages.filter((message) => message.type === "MUTATE").flatMap((message) => message.payload.operations || []),
416
+ get ended() {
417
+ return ended;
418
+ },
419
+ unmount: end
420
+ };
421
+ }
@@ -1,4 +1,5 @@
1
1
  import type { KeptStore } from './kept-store';
2
+ import type { SharedRequest, SharedRequestOptions } from '../shared-request';
2
3
  /**
3
4
  * Whether an outbox entry's `affects` item, or a URL the worker refreshed,
4
5
  * names this query: its key, or its URL (an item without a query string
@@ -43,6 +44,7 @@ export declare interface CachedQuery<T> {
43
44
  export declare interface QueryCacheEnv {
44
45
  state: <T>(value: T) => QuerySignal<T>
45
46
  kept: KeptStore
47
+ sharedRequest: <K, T>(options?: SharedRequestOptions<K>) => SharedRequest<K, T>
46
48
  prefix?: string
47
49
  listen?: boolean
48
50
  matches?: (item: string, target: QueryTarget) => boolean
@@ -80,7 +80,9 @@ export function createQueryCache(env) {
80
80
  const initial = opts.initial === void 0 ? null : opts.initial, scopeNow = () => typeof opts.scope === "function" ? opts.scope() : opts.scope, urlNow = () => {
81
81
  return (typeof opts.url === "function" ? opts.url() : opts.url) || null;
82
82
  }, target = () => ({ key, url: urlNow() });
83
- let scope = scopeNow(), base = initial, fetchedAt = 0, inflight = null;
83
+ let scope = scopeNow(), base = initial, fetchedAt = 0;
84
+ const requests = env.sharedRequest();
85
+ let out = 0;
84
86
  const seeded = cache.seed(key, scope);
85
87
  if (seeded)
86
88
  base = seeded.data;
@@ -106,7 +108,9 @@ export function createQueryCache(env) {
106
108
  return;
107
109
  scope = now;
108
110
  generation++;
109
- inflight = null;
111
+ out = 0;
112
+ isFetching.set(!1);
113
+ loading.set(!1);
110
114
  fetchedAt = 0;
111
115
  const found = cache.seed(key, scope);
112
116
  base = found ? found.data : initial;
@@ -114,8 +118,8 @@ export function createQueryCache(env) {
114
118
  show();
115
119
  if (!found)
116
120
  restoreFrom(scope);
117
- }, request = (force) => {
118
- const url = urlNow(), timeout = opts.timeoutMs || 15000, controller = typeof AbortController < "u" ? new AbortController : null;
121
+ }, request = (force, url) => {
122
+ const timeout = opts.timeoutMs || 15000, controller = typeof AbortController < "u" ? new AbortController : null;
119
123
  let timer = null;
120
124
  const expired = new Promise((_, reject) => {
121
125
  timer = setTimeout(() => {
@@ -152,37 +156,43 @@ export function createQueryCache(env) {
152
156
  throw cause;
153
157
  });
154
158
  }, run = (force) => {
155
- if (inflight)
156
- return inflight;
157
- const asked = generation;
158
- isFetching.set(!0);
159
- if (fetchedAt === 0 && !updatedAt())
160
- loading.set(!0);
161
- const done = () => {
162
- if (asked !== generation)
163
- return;
164
- inflight = null;
165
- isFetching.set(!1);
166
- loading.set(!1);
167
- }, promise = request(force).then((value) => {
159
+ const asked = generation, url = urlNow(), start = () => {
168
160
  if (asked !== generation)
161
+ return Promise.resolve(data());
162
+ out++;
163
+ isFetching.set(!0);
164
+ if (fetchedAt === 0 && !updatedAt())
165
+ loading.set(!0);
166
+ const done = () => {
167
+ if (asked !== generation)
168
+ return;
169
+ out = Math.max(0, out - 1);
170
+ if (!out) {
171
+ isFetching.set(!1);
172
+ loading.set(!1);
173
+ }
174
+ };
175
+ return request(force, url).then((value) => {
176
+ if (asked !== generation || url !== urlNow()) {
177
+ done();
178
+ return data();
179
+ }
180
+ base = value;
181
+ fetchedAt = Date.now();
182
+ updatedAt.set(fetchedAt);
183
+ error.set(null);
184
+ cache.persist(key, value, scope);
185
+ show();
186
+ done();
169
187
  return data();
170
- base = value;
171
- fetchedAt = Date.now();
172
- updatedAt.set(fetchedAt);
173
- error.set(null);
174
- cache.persist(key, value, scope);
175
- show();
176
- done();
177
- return data();
178
- }, (cause) => {
179
- if (asked === generation)
180
- error.set(cause && cause.message ? cause.message : "Could not load.");
181
- done();
182
- return data();
183
- });
184
- inflight = promise;
185
- return promise;
188
+ }, (cause) => {
189
+ if (asked === generation && url === urlNow())
190
+ error.set(cause && cause.message ? cause.message : "Could not load.");
191
+ done();
192
+ return data();
193
+ });
194
+ }, at = `${asked} ${url || ""}`;
195
+ return force ? requests.fresh(at, start) : requests.run(at, start);
186
196
  }, query = {
187
197
  data,
188
198
  loading,