@swiftbrowser/native 0.17.7 → 0.18.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.
Files changed (100) hide show
  1. package/README.md +99 -11
  2. package/dist/blob.d.ts +60 -0
  3. package/dist/blob.d.ts.map +1 -0
  4. package/dist/blob.js +153 -0
  5. package/dist/blob.js.map +1 -0
  6. package/dist/bridge.d.ts +65 -1
  7. package/dist/bridge.d.ts.map +1 -1
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/fetch.d.ts +11 -3
  10. package/dist/fetch.d.ts.map +1 -1
  11. package/dist/fetch.js +26 -2
  12. package/dist/fetch.js.map +1 -1
  13. package/dist/hostRequests.d.ts +55 -0
  14. package/dist/hostRequests.d.ts.map +1 -0
  15. package/dist/hostRequests.js +196 -0
  16. package/dist/hostRequests.js.map +1 -0
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +8 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/matchMedia.d.ts +43 -0
  22. package/dist/matchMedia.d.ts.map +1 -0
  23. package/dist/matchMedia.js +63 -0
  24. package/dist/matchMedia.js.map +1 -0
  25. package/dist/notifications.d.ts +108 -0
  26. package/dist/notifications.d.ts.map +1 -0
  27. package/dist/notifications.js +251 -0
  28. package/dist/notifications.js.map +1 -0
  29. package/dist/run.d.ts.map +1 -1
  30. package/dist/run.js +23 -2
  31. package/dist/run.js.map +1 -1
  32. package/dist/runtime.d.ts +2 -0
  33. package/dist/runtime.d.ts.map +1 -1
  34. package/dist/runtime.js +69 -0
  35. package/dist/runtime.js.map +1 -1
  36. package/dist/secureStorage.d.ts +20 -0
  37. package/dist/secureStorage.d.ts.map +1 -0
  38. package/dist/secureStorage.js +28 -0
  39. package/dist/secureStorage.js.map +1 -0
  40. package/dist/site.d.ts +3 -3
  41. package/dist/site.d.ts.map +1 -1
  42. package/dist/site.js +1 -1
  43. package/dist/site.js.map +1 -1
  44. package/dist/subtle.d.ts +38 -0
  45. package/dist/subtle.d.ts.map +1 -0
  46. package/dist/subtle.js +72 -0
  47. package/dist/subtle.js.map +1 -0
  48. package/dist/undo.d.ts +23 -0
  49. package/dist/undo.d.ts.map +1 -0
  50. package/dist/undo.js +44 -0
  51. package/dist/undo.js.map +1 -0
  52. package/dist/webSocket.d.ts +73 -0
  53. package/dist/webSocket.d.ts.map +1 -0
  54. package/dist/webSocket.js +145 -0
  55. package/dist/webSocket.js.map +1 -0
  56. package/package.json +3 -3
  57. package/src/blob.ts +186 -0
  58. package/src/bridge.ts +74 -1
  59. package/src/fetch.ts +29 -3
  60. package/src/hostRequests.ts +216 -0
  61. package/src/index.ts +8 -0
  62. package/src/matchMedia.ts +79 -0
  63. package/src/notifications.ts +317 -0
  64. package/src/run.ts +21 -2
  65. package/src/runtime.ts +71 -0
  66. package/src/secureStorage.ts +39 -0
  67. package/src/site.ts +3 -3
  68. package/src/subtle.ts +87 -0
  69. package/src/undo.ts +47 -0
  70. package/src/webSocket.ts +175 -0
  71. package/swift/Sources/SwiftBrowserNative/Host/AudioRecorderBridge.swift +199 -0
  72. package/swift/Sources/SwiftBrowserNative/Host/FilesBridge.swift +154 -0
  73. package/swift/Sources/SwiftBrowserNative/Host/HostBridge.swift +211 -0
  74. package/swift/Sources/SwiftBrowserNative/Host/HostRequestBridge.swift +451 -0
  75. package/swift/Sources/SwiftBrowserNative/Host/NotificationBridge.swift +304 -0
  76. package/swift/Sources/SwiftBrowserNative/Host/SecureStorage.swift +60 -0
  77. package/swift/Sources/SwiftBrowserNative/Host/ShimAliases.swift +1 -0
  78. package/swift/Sources/SwiftBrowserNative/Host/TextMeasureBridge.swift +139 -0
  79. package/swift/Sources/SwiftBrowserNative/Host/UndoBridge.swift +170 -0
  80. package/swift/Sources/SwiftBrowserNative/Host/WebSocketBridge.swift +118 -0
  81. package/swift/Sources/SwiftBrowserNative/Runtime/NativeApp.swift +56 -0
  82. package/swift/Sources/SwiftBrowserNative/Runtime/NativeAppDelegate.swift +36 -0
  83. package/swift/Sources/SwiftBrowserNative/Views/Kinds/Controls.swift +362 -16
  84. package/swift/Sources/SwiftBrowserNative/Views/Kinds/DeleteBackward.swift +147 -0
  85. package/swift/Sources/SwiftBrowserNative/Views/Kinds/KeyboardBar.swift +84 -0
  86. package/swift/Sources/SwiftBrowserNative/Views/Kinds/More.swift +116 -11
  87. package/swift/Sources/SwiftBrowserNative/Views/Kinds/Navigation.swift +12 -1
  88. package/swift/Sources/SwiftBrowserNative/Views/Kinds/Shapes.swift +30 -9
  89. package/swift/Sources/SwiftBrowserNative/Views/Kinds/Stacks.swift +163 -10
  90. package/swift/Sources/SwiftBrowserNative/Views/Kinds/TextAndImages.swift +17 -4
  91. package/swift/Sources/SwiftBrowserNative/Views/Kinds/Video.swift +8 -3
  92. package/swift/Sources/SwiftBrowserNative/Views/NativeRootView.swift +8 -0
  93. package/swift/Sources/SwiftBrowserNative/Views/StyleModifier.swift +41 -0
  94. package/swift/Sources/SwiftBrowserProtocol/Op.swift +27 -4
  95. package/swift/Sources/SwiftBrowserProtocol/Props.swift +110 -3
  96. package/swift/Sources/SwiftBrowserProtocol/RendererEvent.swift +47 -0
  97. package/swift/Sources/SwiftBrowserProtocol/SVGPath.swift +260 -0
  98. package/swift/Sources/SwiftBrowserProtocol/Style.swift +58 -0
  99. package/swift/Sources/SwiftBrowserTree/OpTree.swift +22 -2
  100. package/wasm/SwiftBrowserNative.wasm +2 -2
package/src/blob.ts ADDED
@@ -0,0 +1,186 @@
1
+ /**
2
+ * `Blob`, `File` and `FormData` for the native app: bytes with a type, a
3
+ * named one, and a form whose entries `fetch` sends as multipart. A body is
4
+ * still whole (no streams); `URL.createObjectURL` gives a `data:` URL, which
5
+ * the host's image loader and `URLSession` both read, and
6
+ * `revokeObjectURL` has nothing to free.
7
+ */
8
+
9
+ import { base64Encode, utf8Decode, utf8Encode } from './encoding';
10
+
11
+ export type BlobPartLike = string | ArrayBuffer | ArrayBufferView | SimpleBlob;
12
+
13
+ export interface BlobOptions {
14
+ type?: string;
15
+ }
16
+
17
+ export interface FileOptions extends BlobOptions {
18
+ lastModified?: number;
19
+ }
20
+
21
+ function partBytes(part: BlobPartLike): Uint8Array {
22
+ if (typeof part === 'string') return utf8Encode(part);
23
+ if (part instanceof SimpleBlob) return part.bytes();
24
+ if (part instanceof ArrayBuffer) return new Uint8Array(part.slice(0));
25
+ if (ArrayBuffer.isView(part)) return new Uint8Array(part.buffer.slice(part.byteOffset, part.byteOffset + part.byteLength));
26
+ return utf8Encode(String(part));
27
+ }
28
+
29
+ function concat(parts: Uint8Array[]): Uint8Array {
30
+ const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
31
+ const out = new Uint8Array(total);
32
+ let offset = 0;
33
+ for (const part of parts) {
34
+ out.set(part, offset);
35
+ offset += part.byteLength;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ /** The browser's `Blob`: bytes and a MIME type. */
41
+ export class SimpleBlob {
42
+ private readonly data: Uint8Array;
43
+ readonly type: string;
44
+
45
+ constructor(parts: Iterable<BlobPartLike> = [], options: BlobOptions = {}) {
46
+ this.data = concat([...parts].map(partBytes));
47
+ // As the browser does: lowercased, and empty when it is not printable ASCII.
48
+ const type = options.type ?? '';
49
+ this.type = /^[\x20-\x7e]*$/.test(type) ? type.toLowerCase() : '';
50
+ }
51
+
52
+ get size(): number {
53
+ return this.data.byteLength;
54
+ }
55
+
56
+ /** The bytes (a view; callers must not write into it). */
57
+ bytes(): Uint8Array {
58
+ return this.data;
59
+ }
60
+
61
+ slice(start = 0, end = this.size, contentType = ''): SimpleBlob {
62
+ const from = start < 0 ? Math.max(this.size + start, 0) : Math.min(start, this.size);
63
+ const to = end < 0 ? Math.max(this.size + end, 0) : Math.min(end, this.size);
64
+ return new SimpleBlob([this.data.subarray(from, Math.max(from, to))], { type: contentType });
65
+ }
66
+
67
+ async arrayBuffer(): Promise<ArrayBuffer> {
68
+ return this.data.buffer.slice(this.data.byteOffset, this.data.byteOffset + this.data.byteLength) as ArrayBuffer;
69
+ }
70
+
71
+ async text(): Promise<string> {
72
+ return utf8Decode(this.data);
73
+ }
74
+
75
+ get [Symbol.toStringTag](): string {
76
+ return 'Blob';
77
+ }
78
+ }
79
+
80
+ /** The browser's `File`: a `Blob` with a name. */
81
+ export class SimpleFile extends SimpleBlob {
82
+ readonly name: string;
83
+ readonly lastModified: number;
84
+
85
+ constructor(parts: Iterable<BlobPartLike>, name: string, options: FileOptions = {}) {
86
+ super(parts, options);
87
+ this.name = String(name);
88
+ this.lastModified = options.lastModified ?? Date.now();
89
+ }
90
+
91
+ override get [Symbol.toStringTag](): string {
92
+ return 'File';
93
+ }
94
+ }
95
+
96
+ export type FormDataEntryValueLike = string | SimpleFile;
97
+
98
+ /** The browser's `FormData`, as far as a request body needs it. */
99
+ export class SimpleFormData {
100
+ private entries_: [string, FormDataEntryValueLike][] = [];
101
+
102
+ private static value(value: unknown, filename?: string): FormDataEntryValueLike {
103
+ if (value instanceof SimpleBlob) {
104
+ const name = filename ?? (value instanceof SimpleFile ? value.name : 'blob');
105
+ return value instanceof SimpleFile && filename === undefined ? value : new SimpleFile([value], name, { type: value.type });
106
+ }
107
+ return String(value);
108
+ }
109
+
110
+ append(name: string, value: unknown, filename?: string): void {
111
+ this.entries_.push([String(name), SimpleFormData.value(value, filename)]);
112
+ }
113
+
114
+ set(name: string, value: unknown, filename?: string): void {
115
+ const key = String(name);
116
+ const entry: [string, FormDataEntryValueLike] = [key, SimpleFormData.value(value, filename)];
117
+ const index = this.entries_.findIndex(([entryName]) => entryName === key);
118
+ if (index < 0) {
119
+ this.entries_.push(entry);
120
+ return;
121
+ }
122
+ this.entries_ = this.entries_.filter(([entryName], position) => position === index || entryName !== key);
123
+ this.entries_[index] = entry;
124
+ }
125
+
126
+ get(name: string): FormDataEntryValueLike | null {
127
+ return this.entries_.find(([entryName]) => entryName === String(name))?.[1] ?? null;
128
+ }
129
+
130
+ getAll(name: string): FormDataEntryValueLike[] {
131
+ return this.entries_.filter(([entryName]) => entryName === String(name)).map(([, value]) => value);
132
+ }
133
+
134
+ has(name: string): boolean {
135
+ return this.entries_.some(([entryName]) => entryName === String(name));
136
+ }
137
+
138
+ delete(name: string): void {
139
+ this.entries_ = this.entries_.filter(([entryName]) => entryName !== String(name));
140
+ }
141
+
142
+ *entries(): IterableIterator<[string, FormDataEntryValueLike]> {
143
+ yield* this.entries_;
144
+ }
145
+
146
+ *keys(): IterableIterator<string> {
147
+ for (const [name] of this.entries_) yield name;
148
+ }
149
+
150
+ *values(): IterableIterator<FormDataEntryValueLike> {
151
+ for (const [, value] of this.entries_) yield value;
152
+ }
153
+
154
+ forEach(callback: (value: FormDataEntryValueLike, name: string, form: SimpleFormData) => void): void {
155
+ for (const [name, value] of this.entries_) callback(value, name, this);
156
+ }
157
+
158
+ [Symbol.iterator](): IterableIterator<[string, FormDataEntryValueLike]> {
159
+ return this.entries();
160
+ }
161
+
162
+ get [Symbol.toStringTag](): string {
163
+ return 'FormData';
164
+ }
165
+ }
166
+
167
+ /** A multipart/form-data body for the form, with the boundary `random` makes unique. */
168
+ export function encodeMultipart(form: SimpleFormData, random: (count: number) => Uint8Array): { bytes: Uint8Array; contentType: string } {
169
+ const boundary = `----SwiftBrowserFormBoundary${Array.from(random(16), (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
170
+ const escape = (text: string): string => text.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
171
+ const parts: Uint8Array[] = [];
172
+ for (const [name, value] of form.entries()) {
173
+ const head = [`--${boundary}`, `Content-Disposition: form-data; name="${escape(name)}"` + (typeof value === 'string' ? '' : `; filename="${escape(value.name)}"`)];
174
+ if (typeof value !== 'string') head.push(`Content-Type: ${value.type || 'application/octet-stream'}`);
175
+ parts.push(utf8Encode(`${head.join('\r\n')}\r\n\r\n`));
176
+ parts.push(typeof value === 'string' ? utf8Encode(value) : value.bytes());
177
+ parts.push(utf8Encode('\r\n'));
178
+ }
179
+ parts.push(utf8Encode(`--${boundary}--\r\n`));
180
+ return { bytes: concat(parts), contentType: `multipart/form-data; boundary=${boundary}` };
181
+ }
182
+
183
+ /** `URL.createObjectURL`: a `data:` URL holding the blob. */
184
+ export function objectURL(blob: SimpleBlob): string {
185
+ return `data:${blob.type || 'application/octet-stream'};base64,${base64Encode(blob.bytes())}`;
186
+ }
package/src/bridge.ts CHANGED
@@ -3,7 +3,9 @@
3
3
  * (Native/Sources/SwiftBrowserNative/Host/HostBridge.swift). Every call is
4
4
  * synchronous; the ones that answer later do so by calling a global this
5
5
  * package defines (`__sbTimerFired`, `__sbFetchResult`, `__sbImageProbed`,
6
- * `__sbWorkerMessage`, `__sbOpenURL`, `__sbMediaSessionCommand`).
6
+ * `__sbWorkerMessage`, `__sbOpenURL`, `__sbMediaSessionCommand`,
7
+ * `__sbNotificationPermission`, `__sbPushRegistered`, `__sbNotification`,
8
+ * `__sbWebSocketEvent`, `__sbHostResponse`, `__sbUndoCommand`).
7
9
  */
8
10
  export interface NativeBridge {
9
11
  /** Applies a render pass's ops (a JSON array). Returns an error message, or nothing. */
@@ -44,6 +46,77 @@ export interface NativeBridge {
44
46
  */
45
47
  mediaSession?(update: string): void;
46
48
 
49
+ // Notifications (notifications.ts), on UserNotifications. Hosts before 0.20 lack them.
50
+ /** The app listens: what came before it did (a tap that launched it) arrives at `__sbNotification(json)`. */
51
+ notificationsReady?(): void;
52
+ /** Answers `__sbNotificationPermission(id, 'default' | 'granted' | 'denied')`, after asking the viewer when `request` is set. */
53
+ notificationPermission?(id: number, request: boolean): void;
54
+ /** Shows `{ id, title, subtitle?, body?, data?, badge?, silent? }` now; returns what was wrong with it, or nothing. */
55
+ notificationShow?(json: string): string | null | undefined;
56
+ /** Closes the notifications with these identifiers (a JSON array). */
57
+ notificationClose?(json: string): void;
58
+ /** The app badge (0 clears it). */
59
+ setBadge?(count: number): void;
60
+ /**
61
+ * Registers for remote notifications; the device token (hex) or the
62
+ * failure answers `__sbPushRegistered(id, { token } | { error })`.
63
+ * `applicationServerKey` is for the page (the round trip's Web Push).
64
+ */
65
+ pushRegister?(id: number, applicationServerKey?: string): void;
66
+
67
+ // WebSockets (webSocket.ts) on `URLSessionWebSocketTask`; events come to `__sbWebSocketEvent(id, json)`. Hosts before 0.20 lack them.
68
+ wsOpen?(id: number, url: string, protocols: string[]): void;
69
+ /** `{ text }` or `{ binary }` (base64), as JSON. */
70
+ wsSend?(id: number, json: string): void;
71
+ wsClose?(id: number, code: number, reason: string): void;
72
+
73
+ // `crypto.subtle` (subtle.ts) on CryptoKit, synchronously. Hosts before 0.20 lack them.
74
+ /** The base64 digest of base64 `data` under `algorithm` (`SHA-256`, …), or nothing when the host cannot. */
75
+ digest?(algorithm: string, data: string): string | null | undefined;
76
+ /** The base64 HMAC of base64 `data` with base64 `key` under the hash `algorithm`, or nothing. */
77
+ hmac?(algorithm: string, key: string, data: string): string | null | undefined;
78
+
79
+ /** `navigator.vibrate`: a haptic (`impact`, `selection`, `success`, `warning`, `error`). Hosts before 0.20 lack it. */
80
+ haptic?(kind: string): void;
81
+
82
+ /**
83
+ * A host request of the web renderer's kinds (hostRequests.ts): `share`,
84
+ * `pickFiles`, `clipboard`, `pickColor` and `webAuth`, with the request's
85
+ * params as JSON; the answer arrives at `__sbHostResponse(id, { value } | { error })`.
86
+ * Hosts before 0.20 lack it.
87
+ */
88
+ hostRequest?(id: number, kind: string, json: string): void;
89
+
90
+ /**
91
+ * The app's undo manager's state (undo.ts): `{ canUndo, canRedo,
92
+ * undoActionName, redoActionName }` as JSON, which the host mirrors on the
93
+ * window's `UndoManager` so the system's undo reaches the app; the undo or
94
+ * redo the system asks for arrives at `__sbUndoCommand('undo' | 'redo')`.
95
+ * Hosts before 0.18 lack it.
96
+ */
97
+ undoState?(json: string): void;
98
+
99
+ /**
100
+ * `measureText` (@swiftbrowser/react): the size `text` in `font` (a Font
101
+ * JSON object over the body font) takes wrapped to `width` points (one
102
+ * line when null), from `NSAttributedString`'s bounding rect, synchronously:
103
+ * `{ width, height, lines }`, or nothing when the host cannot measure.
104
+ * Hosts before 0.21 lack it.
105
+ */
106
+ measureText?(text: string, font: string, width: number | null): { width: number; height: number; lines: number } | null | undefined;
107
+
108
+ /**
109
+ * The app's standard directories as `file:` URLs, a JSON object
110
+ * `{ documents, applicationSupport, caches, temporary }` (hostRequests.ts
111
+ * `files`, Host/FilesBridge.swift). Hosts before 0.22 lack it.
112
+ */
113
+ appDirectories?(): string | null | undefined;
114
+
115
+ // The Keychain (secureStorage.ts). Hosts before 0.20 lack them.
116
+ secureGet?(key: string): string | null;
117
+ secureSet?(key: string, value: string): void;
118
+ secureRemove?(key: string): void;
119
+
47
120
  // Workers (worker.ts): a second context on its own thread, from a bundle
48
121
  // `swiftbrowser-native build --worker <name>=<entry>` wrote next to app.js
49
122
  // (`<name>.worker.js`). The app's context has the first three; a worker's
package/src/fetch.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * `fetch`, `Headers`, `Request`, `Response` and `AbortController` over the
3
3
  * bridge's `fetch` primitive (`URLSession` on the Swift side). Bodies cross
4
- * as base64; a `Response` reads them back as text, JSON or bytes. Streams
5
- * and `Blob` are not here: a body is whole.
4
+ * as base64; a `Response` reads them back as text, JSON, bytes or a `Blob`.
5
+ * A `Blob` or `FormData` body (blob.ts) is sent whole, the form as
6
+ * multipart; there are no streams.
6
7
  */
7
8
 
8
9
  import type { NativeBridge, NativeFetchResult } from './bridge';
10
+ import { encodeMultipart, SimpleBlob, SimpleFormData } from './blob';
9
11
  import { base64Decode, base64Encode, utf8Decode, utf8Encode } from './encoding';
10
12
 
11
13
  type HeadersInitLike = SimpleHeaders | Record<string, string> | [string, string][];
@@ -114,16 +116,25 @@ function timeoutError(): Error {
114
116
  return error;
115
117
  }
116
118
 
117
- type BodyInitLike = string | ArrayBuffer | ArrayBufferView | SimpleURLSearchParamsLike | null | undefined;
119
+ type BodyInitLike = string | ArrayBuffer | ArrayBufferView | SimpleURLSearchParamsLike | SimpleBlob | SimpleFormData | null | undefined;
118
120
  interface SimpleURLSearchParamsLike {
119
121
  toString(): string;
120
122
  [Symbol.iterator](): IterableIterator<[string, string]>;
121
123
  }
122
124
 
125
+ /** The multipart boundary's randomness: the bridge's bytes once the runtime is installed, a counter before. */
126
+ let randomBytes: (count: number) => Uint8Array = (count) => Uint8Array.from({ length: count }, (_, i) => (i * 37 + 11) & 255);
127
+
128
+ export function setBodyRandomness(random: (count: number) => Uint8Array): void {
129
+ randomBytes = random;
130
+ }
131
+
123
132
  /** Bytes of a body, and the content type it implies when the caller set none. */
124
133
  function encodeBody(body: BodyInitLike): { bytes: Uint8Array | null; contentType: string | null } {
125
134
  if (body === null || body === undefined) return { bytes: null, contentType: null };
126
135
  if (typeof body === 'string') return { bytes: utf8Encode(body), contentType: 'text/plain;charset=UTF-8' };
136
+ if (body instanceof SimpleBlob) return { bytes: body.bytes(), contentType: body.type || null };
137
+ if (body instanceof SimpleFormData) return encodeMultipart(body, randomBytes);
127
138
  if (body instanceof ArrayBuffer) return { bytes: new Uint8Array(body), contentType: null };
128
139
  if (ArrayBuffer.isView(body)) return { bytes: new Uint8Array(body.buffer, body.byteOffset, body.byteLength), contentType: null };
129
140
  if (typeof body === 'object' && Symbol.iterator in body && typeof body.toString === 'function') {
@@ -160,6 +171,13 @@ class Body {
160
171
  async json(): Promise<unknown> {
161
172
  return JSON.parse(utf8Decode(this.take()));
162
173
  }
174
+ async blob(): Promise<SimpleBlob> {
175
+ return new SimpleBlob([this.take()], { type: this.contentType() });
176
+ }
177
+ /** The body's content type, for `blob()`; a Request or Response reads its headers. */
178
+ protected contentType(): string {
179
+ return '';
180
+ }
163
181
  }
164
182
 
165
183
  export interface RequestInitLike {
@@ -190,6 +208,10 @@ export class SimpleRequest extends Body {
190
208
  rawBytes(): Uint8Array | null {
191
209
  return this.bytes;
192
210
  }
211
+ protected override contentType(): string {
212
+ return this.headers.get('content-type') ?? '';
213
+ }
214
+
193
215
  clone(): SimpleRequest {
194
216
  return new SimpleRequest(this, { body: this.bytes });
195
217
  }
@@ -222,6 +244,10 @@ export class SimpleResponse extends Body {
222
244
  get ok(): boolean {
223
245
  return this.status >= 200 && this.status < 300;
224
246
  }
247
+ protected override contentType(): string {
248
+ return this.headers.get('content-type') ?? '';
249
+ }
250
+
225
251
  clone(): SimpleResponse {
226
252
  return new SimpleResponse(this.bytes, { status: this.status, statusText: this.statusText, headers: this.headers, url: this.url });
227
253
  }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * The host requests `@swiftbrowser/react` sends to the browser environment
3
+ * (`ShareLink`, `fileImporter`, the clipboard, a color chooser: the web
4
+ * renderer's `performHostRequest` with its `browserEnvironment`), answered by
5
+ * the native app instead: the bridge's `hostRequest(id, kind, json)` performs
6
+ * one with UIKit (a share sheet, the photo or document picker, the
7
+ * pasteboard, the color picker, `ASWebAuthenticationSession`, a recording
8
+ * from the microphone with `AVAudioRecorder`), answering
9
+ * `__sbHostResponse(id, { value } | { error })`. `installHostEnvironment`
10
+ * fills the environment's gaps with these, and with the window's undo
11
+ * manager (undo.ts), leaving what the page has (the round trip runs in a
12
+ * browser with a share sheet and a keyboard of its own).
13
+ *
14
+ * `webAuthenticate` is the sign-in window apps open for OAuth: the system's
15
+ * sheet, resolving with the callback URL.
16
+ *
17
+ * `files` is the app's sandbox for `fileManager` (@swiftbrowser/react): the
18
+ * `files` requests of Host/FilesBridge.swift, bytes crossing as base64, with
19
+ * the standard directories from the bridge's `appDirectories()`.
20
+ */
21
+
22
+ import { objectURL, SimpleBlob, SimpleFile } from './blob';
23
+ import type { NativeBridge } from './bridge';
24
+ import { base64Decode, base64Encode } from './encoding';
25
+ import { nativeUndoHost } from './undo';
26
+
27
+ export type HostRequestBridge = Required<Pick<NativeBridge, 'hostRequest'>> & Pick<NativeBridge, 'appDirectories'>;
28
+
29
+ /** A file as it crosses the bridge: its name, MIME type and bytes (base64). */
30
+ export interface BridgedFile {
31
+ name: string;
32
+ type: string;
33
+ data: string;
34
+ }
35
+
36
+ export interface WebAuthenticateOptions {
37
+ /** The scheme of the callback URL the sign-in ends with (`myapp` for `myapp://auth`); universal links need none. */
38
+ callbackScheme?: string;
39
+ /** Whether the session shares no cookies with the system browser. */
40
+ ephemeral?: boolean;
41
+ }
42
+
43
+ let bridge: HostRequestBridge | null = null;
44
+ let nextId = 1;
45
+ const pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void }>();
46
+
47
+ /** Points the requests at the bridge (the runtime, once per install). */
48
+ export function installHostRequests(native: HostRequestBridge): void {
49
+ bridge = native;
50
+ }
51
+
52
+ /** The bridge's `__sbHostResponse(id, result)`. */
53
+ export function receiveHostResponse(id: number, result: string | { value?: unknown; error?: string }): void {
54
+ const waiting = pending.get(id);
55
+ if (!waiting) return;
56
+ pending.delete(id);
57
+ let parsed: { value?: unknown; error?: string };
58
+ try {
59
+ parsed = typeof result === 'string' ? (JSON.parse(result) as { value?: unknown; error?: string }) : result;
60
+ } catch {
61
+ waiting.reject(new Error('host: malformed response'));
62
+ return;
63
+ }
64
+ if (typeof parsed.error === 'string') {
65
+ const error = new Error(parsed.error);
66
+ if (parsed.error.startsWith('cancelled')) error.name = 'AbortError';
67
+ waiting.reject(error);
68
+ } else {
69
+ waiting.resolve(parsed.value);
70
+ }
71
+ }
72
+
73
+ /** Performs one request of `kind` with `params`; resolves with the host's value. */
74
+ export function hostRequest<T = unknown>(kind: string, params: Record<string, unknown>): Promise<T> {
75
+ return new Promise<T>((resolve, reject) => {
76
+ if (!bridge) {
77
+ reject(new Error(`unsupported: no native host for ${kind}`));
78
+ return;
79
+ }
80
+ const id = nextId++;
81
+ pending.set(id, { resolve: resolve as (value: unknown) => void, reject });
82
+ bridge.hostRequest(id, kind, JSON.stringify(params));
83
+ });
84
+ }
85
+
86
+ /** Forgets the bridge and the waiting requests, for tests. */
87
+ export function resetHostRequests(): void {
88
+ bridge = null;
89
+ pending.clear();
90
+ nextId = 1;
91
+ }
92
+
93
+ async function bridgedFile(file: SimpleBlob & { name?: string }): Promise<BridgedFile> {
94
+ return { name: file.name ?? 'file', type: file.type, data: base64Encode(file.bytes()) };
95
+ }
96
+
97
+ function filesOf(value: unknown): SimpleFile[] {
98
+ const files = (value as { files?: BridgedFile[] } | undefined)?.files ?? [];
99
+ return files.map((file) => new SimpleFile([base64Decode(file.data)], file.name, { type: file.type }));
100
+ }
101
+
102
+ /**
103
+ * Opens the system's sign-in sheet at `url` and resolves with the callback
104
+ * URL it ends with; rejects with an `AbortError` when the viewer closes it.
105
+ */
106
+ export async function webAuthenticate(url: string, options: WebAuthenticateOptions = {}): Promise<string> {
107
+ const params: Record<string, unknown> = { action: 'start', url };
108
+ if (options.callbackScheme) params['callbackScheme'] = options.callbackScheme;
109
+ if (options.ephemeral !== undefined) params['ephemeral'] = options.ephemeral;
110
+ const result = await hostRequest<{ url?: string }>('webAuth', params);
111
+ if (typeof result?.url !== 'string') throw new Error('webAuth: the sign-in ended without a URL');
112
+ return result.url;
113
+ }
114
+
115
+ interface FileDirectories {
116
+ documents: string;
117
+ applicationSupport: string;
118
+ caches: string;
119
+ temporary: string;
120
+ }
121
+
122
+ /** The app's directories the bridge reports, or null on a host without `appDirectories`. */
123
+ function appDirectories(): FileDirectories | null {
124
+ try {
125
+ const json = bridge?.appDirectories?.();
126
+ if (!json) return null;
127
+ const parsed = JSON.parse(json) as Partial<FileDirectories>;
128
+ const { documents, applicationSupport, caches, temporary } = parsed;
129
+ if ([documents, applicationSupport, caches, temporary].every((url) => typeof url === 'string')) {
130
+ return { documents: documents!, applicationSupport: applicationSupport!, caches: caches!, temporary: temporary! };
131
+ }
132
+ } catch {
133
+ // Malformed: as if the host had none.
134
+ }
135
+ return null;
136
+ }
137
+
138
+ /** The app's files (`files` requests): `fileManager`'s host over the sandbox. */
139
+ function nativeFiles(directories: FileDirectories): Record<string, unknown> {
140
+ const files = <T>(params: Record<string, unknown>): Promise<T> => hostRequest<T>('files', params);
141
+ return {
142
+ directories,
143
+ read: async (url: string): Promise<Uint8Array> => base64Decode((await files<{ data?: string }>({ action: 'read', url }))?.data ?? ''),
144
+ write: (url: string, data: Uint8Array): Promise<void> => files({ action: 'write', url, data: base64Encode(data) }).then(() => undefined),
145
+ remove: (url: string): Promise<void> => files({ action: 'remove', url }).then(() => undefined),
146
+ createDirectory: (url: string): Promise<void> => files({ action: 'createDirectory', url }).then(() => undefined),
147
+ list: async (url: string): Promise<string[]> => (await files<{ urls?: string[] }>({ action: 'list', url }))?.urls ?? [],
148
+ attributes: async (url: string): Promise<{ size: number; modified: number | null; directory: boolean } | null> => {
149
+ const found = await files<{ size?: number; modified?: number | null; directory?: boolean } | null>({ action: 'attributes', url });
150
+ if (!found || typeof found.size !== 'number') return null;
151
+ return { size: found.size, modified: typeof found.modified === 'number' ? found.modified : null, directory: found.directory === true };
152
+ },
153
+ move: (from: string, to: string): Promise<void> => files({ action: 'move', from, to }).then(() => undefined),
154
+ copy: (from: string, to: string): Promise<void> => files({ action: 'copy', from, to }).then(() => undefined),
155
+ // AVPlayer and UIImage read the file themselves.
156
+ loadURL: async (url: string): Promise<string> => url,
157
+ };
158
+ }
159
+
160
+ /** The environment fields the host answers, shaped as the web renderer's `HostRequestEnvironment`. */
161
+ export function nativeHostEnvironment(): Record<string, unknown> {
162
+ const directories = appDirectories();
163
+ return {
164
+ ...(directories ? { files: nativeFiles(directories) } : {}),
165
+ share: async (data: { title?: string; text?: string; url?: string; files?: SimpleFile[] }): Promise<void> => {
166
+ const params: Record<string, unknown> = {};
167
+ if (data.title) params['title'] = data.title;
168
+ if (data.text) params['text'] = data.text;
169
+ if (data.url) params['url'] = data.url;
170
+ if (data.files?.length) params['files'] = await Promise.all(data.files.map(bridgedFile));
171
+ const result = await hostRequest<{ outcome?: string }>('share', params);
172
+ if (result?.outcome === 'cancelled') {
173
+ const error = new Error('cancelled: the viewer closed the share sheet');
174
+ error.name = 'AbortError';
175
+ throw error;
176
+ }
177
+ },
178
+ canShare: () => true,
179
+ download: (blob: SimpleBlob, filename: string): void => {
180
+ void hostRequest('share', { files: [{ name: filename, type: blob.type, data: base64Encode(blob.bytes()) }] }).catch(() => undefined);
181
+ },
182
+ pickFiles: async (options: { accept: string; multiple: boolean }): Promise<SimpleFile[]> => filesOf(await hostRequest('pickFiles', { accept: options.accept, multiple: options.multiple })),
183
+ objectURL: (file: SimpleBlob): string => objectURL(file),
184
+ clipboard: {
185
+ writeText: (text: string): Promise<void> => hostRequest('clipboard', { action: 'write', text }).then(() => undefined),
186
+ writeImage: async (png: Promise<SimpleBlob>): Promise<void> => {
187
+ const file = await png;
188
+ await hostRequest('clipboard', { action: 'write', files: [{ name: 'image.png', type: file.type || 'image/png', data: base64Encode(file.bytes()) }] });
189
+ },
190
+ readText: async (): Promise<string> => (await hostRequest<{ text?: string }>('clipboard', { action: 'readText' }))?.text ?? '',
191
+ },
192
+ pickColor: async (color: string): Promise<string | null> => (await hostRequest<{ color?: string }>('pickColor', { color }))?.color ?? null,
193
+ // `AVAudioRecorder` (AudioRecorderBridge.swift): a recording ends as a file URL in Documents; `trim` writes another.
194
+ audioRecorder: {
195
+ start: (): Promise<void> => hostRequest('audioRecord', { action: 'start' }).then(() => undefined),
196
+ pause: (): Promise<void> => hostRequest('audioRecord', { action: 'pause' }).then(() => undefined),
197
+ resume: (): Promise<void> => hostRequest('audioRecord', { action: 'resume' }).then(() => undefined),
198
+ stop: (): Promise<{ url: string; duration: number; type: string }> => hostRequest('audioRecord', { action: 'stop' }),
199
+ cancel: (): Promise<void> => hostRequest('audioRecord', { action: 'cancel' }).then(() => undefined),
200
+ meter: (): Promise<{ level: number; time: number }> => hostRequest('audioRecord', { action: 'meter' }),
201
+ discard: (url: string): Promise<void> => hostRequest('audioRecord', { action: 'discard', url }).then(() => undefined),
202
+ trim: (url: string, keep: readonly { start: number; end: number }[]): Promise<{ url: string; duration: number; type: string }> =>
203
+ hostRequest('audioRecord', { action: 'trim', url, keep: keep.map((range) => ({ start: range.start, end: range.end })) }),
204
+ },
205
+ };
206
+ }
207
+
208
+ /** Fills what `environment` lacks with the host's answers; what the page has stays. */
209
+ export function installHostEnvironment(environment: Record<string, unknown>): void {
210
+ if (!bridge) return;
211
+ const undo = nativeUndoHost();
212
+ if (undo && environment['undoManager'] === undefined) environment['undoManager'] = undo;
213
+ for (const [key, value] of Object.entries(nativeHostEnvironment())) {
214
+ if (environment[key] === undefined) environment[key] = value;
215
+ }
216
+ }
package/src/index.ts CHANGED
@@ -17,7 +17,15 @@ export { installRuntime, type InstallOptions } from './runtime';
17
17
  export { nativeBridge, launchArguments, type NativeBridge, type NativeFetchRequest, type NativeFetchResult, type WorkerEngine } from './bridge';
18
18
  export { SimpleHeaders, SimpleRequest, SimpleResponse, SimpleAbortController, SimpleAbortSignal, createFetch } from './fetch';
19
19
  export { SimpleURL, SimpleURLSearchParams } from './url';
20
+ export { SimpleBlob, SimpleFile, SimpleFormData, encodeMultipart, objectURL } from './blob';
21
+ export { NativeWebSocket, type NativeWebSocketEvent } from './webSocket';
22
+ export { createSubtleCrypto } from './subtle';
23
+ export { matchMedia, updateMediaEnvironment, type MediaEnvironment } from './matchMedia';
24
+ export { hostRequest, webAuthenticate, nativeHostEnvironment, installHostEnvironment, type WebAuthenticateOptions, type BridgedFile } from './hostRequests';
25
+ export { secureStorage, createSecureStorage, type SecureStorage } from './secureStorage';
20
26
  export { SimpleTextEncoder, SimpleTextDecoder, base64Encode, base64Decode, utf8Encode, utf8Decode } from './encoding';
21
27
  export { createWorker, NativeWorker, encodeMessage, decodeMessage, workerName, type NativeWorkerOptions, type WorkerLike, type WorkerMessageEvent, type WorkerErrorEvent } from './worker';
22
28
  export { onOpenURL } from './openURL';
29
+ export { onNotification, registerForPush, type NotificationEvent, type NativeNotificationOptions, type RegisterForPushOptions } from './notifications';
30
+ export { createUndoHost, nativeUndoHost } from './undo';
23
31
  export { createMediaSession, NativeMediaMetadata, type NativeMediaSession, type MediaMetadataInit, type MediaActionDetails, type MediaActionHandler, type MediaPositionState } from './mediaSession';
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `matchMedia` for the native app: `(prefers-color-scheme: dark)` and
3
+ * `light` follow the color scheme the host sends with the environment
4
+ * (run.ts hands it over), `(prefers-reduced-motion: reduce)` the host's
5
+ * accessibility setting when it sends one; every other query matches
6
+ * nothing. Listeners hear a change when the environment does.
7
+ */
8
+
9
+ export interface MediaQueryListLike {
10
+ readonly media: string;
11
+ readonly matches: boolean;
12
+ onchange: ((event: { matches: boolean; media: string }) => void) | null;
13
+ addEventListener(type: 'change', listener: (event: { matches: boolean; media: string }) => void): void;
14
+ removeEventListener(type: 'change', listener: (event: { matches: boolean; media: string }) => void): void;
15
+ /** The older names. */
16
+ addListener(listener: (event: { matches: boolean; media: string }) => void): void;
17
+ removeListener(listener: (event: { matches: boolean; media: string }) => void): void;
18
+ }
19
+
20
+ export interface MediaEnvironment {
21
+ colorScheme?: 'light' | 'dark';
22
+ reducedMotion?: boolean;
23
+ }
24
+
25
+ type Listener = (event: { matches: boolean; media: string }) => void;
26
+
27
+ let environment: MediaEnvironment = {};
28
+ const lists = new Set<{ media: string; matches: boolean; listeners: Set<Listener>; onchange: Listener | null }>();
29
+
30
+ function evaluate(query: string): boolean {
31
+ const normalized = query.trim().toLowerCase().replace(/\s+/g, '');
32
+ if (normalized === '(prefers-color-scheme:dark)') return environment.colorScheme === 'dark';
33
+ if (normalized === '(prefers-color-scheme:light)') return environment.colorScheme !== 'dark';
34
+ if (normalized === '(prefers-reduced-motion:reduce)') return environment.reducedMotion === true;
35
+ if (normalized === '(prefers-reduced-motion:no-preference)') return environment.reducedMotion !== true;
36
+ return false;
37
+ }
38
+
39
+ /** The runtime's `matchMedia(query)`. */
40
+ export function matchMedia(query: string): MediaQueryListLike {
41
+ const media = String(query);
42
+ const state = { media, matches: evaluate(media), listeners: new Set<Listener>(), onchange: null as Listener | null };
43
+ lists.add(state);
44
+ return {
45
+ media,
46
+ get matches() {
47
+ return state.matches;
48
+ },
49
+ get onchange() {
50
+ return state.onchange;
51
+ },
52
+ set onchange(listener) {
53
+ state.onchange = listener;
54
+ },
55
+ addEventListener: (_type, listener) => void state.listeners.add(listener),
56
+ removeEventListener: (_type, listener) => void state.listeners.delete(listener),
57
+ addListener: (listener) => void state.listeners.add(listener),
58
+ removeListener: (listener) => void state.listeners.delete(listener),
59
+ };
60
+ }
61
+
62
+ /** What the host sent with the environment; lists whose answer changed tell their listeners. */
63
+ export function updateMediaEnvironment(next: MediaEnvironment): void {
64
+ environment = { ...environment, ...next };
65
+ for (const state of lists) {
66
+ const matches = evaluate(state.media);
67
+ if (matches === state.matches) continue;
68
+ state.matches = matches;
69
+ const event = { matches, media: state.media };
70
+ state.onchange?.(event);
71
+ for (const listener of state.listeners) listener(event);
72
+ }
73
+ }
74
+
75
+ /** Forgets the environment and the lists, for tests. */
76
+ export function resetMediaEnvironment(): void {
77
+ environment = {};
78
+ lists.clear();
79
+ }