@c9up/orbit 0.0.0-stage → 0.1.1

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 (105) hide show
  1. package/Cargo.lock +139 -0
  2. package/Cargo.toml +20 -0
  3. package/LICENSE +21 -0
  4. package/README.md +320 -2
  5. package/android/orbit.cmake +31 -0
  6. package/android/src/main/cpp/NativeOrbit.cpp +309 -0
  7. package/android/src/main/cpp/NativeOrbit.h +35 -0
  8. package/android/src/main/cpp/orbit_host.h +34 -0
  9. package/android/src/main/java/com/c9up/orbit/OrbitEffects.kt +286 -0
  10. package/android/src/main/java/com/c9up/orbit/OrbitHost.kt +258 -0
  11. package/android/src/main/java/com/c9up/orbit/OrbitImage.kt +346 -0
  12. package/android/src/main/java/com/c9up/orbit/OrbitInput.kt +161 -0
  13. package/android/src/main/java/com/c9up/orbit/OrbitPress.kt +110 -0
  14. package/android/src/main/java/com/c9up/orbit/OrbitVector.kt +115 -0
  15. package/android/src/main/java/com/c9up/orbit/OrbitViews.kt +362 -0
  16. package/crates/orbit-host/Cargo.toml +14 -0
  17. package/crates/orbit-host/src/gesture.rs +561 -0
  18. package/crates/orbit-host/src/lib.rs +2042 -0
  19. package/crates/orbit-host/src/motion.rs +328 -0
  20. package/crates/orbit-host/src/vector.rs +1173 -0
  21. package/dist/color.d.ts +10 -0
  22. package/dist/color.d.ts.map +1 -0
  23. package/dist/color.js +62 -0
  24. package/dist/color.js.map +1 -0
  25. package/dist/commit.d.ts +77 -0
  26. package/dist/commit.d.ts.map +1 -0
  27. package/dist/commit.js +302 -0
  28. package/dist/commit.js.map +1 -0
  29. package/dist/errors.d.ts +76 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +89 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/host.d.ts +49 -0
  34. package/dist/host.d.ts.map +1 -0
  35. package/dist/host.js +20 -0
  36. package/dist/host.js.map +1 -0
  37. package/dist/index.d.ts +31 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +31 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/motion.d.ts +18 -0
  42. package/dist/motion.d.ts.map +1 -0
  43. package/dist/motion.js +67 -0
  44. package/dist/motion.js.map +1 -0
  45. package/dist/node.d.ts +46 -0
  46. package/dist/node.d.ts.map +1 -0
  47. package/dist/node.js +110 -0
  48. package/dist/node.js.map +1 -0
  49. package/dist/pages.d.ts +56 -0
  50. package/dist/pages.d.ts.map +1 -0
  51. package/dist/pages.js +157 -0
  52. package/dist/pages.js.map +1 -0
  53. package/dist/react-native/index.d.ts +33 -0
  54. package/dist/react-native/index.d.ts.map +1 -0
  55. package/dist/react-native/index.js +71 -0
  56. package/dist/react-native/index.js.map +1 -0
  57. package/dist/report.d.ts +13 -0
  58. package/dist/report.d.ts.map +1 -0
  59. package/dist/report.js +22 -0
  60. package/dist/report.js.map +1 -0
  61. package/dist/server.d.ts +109 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +290 -0
  64. package/dist/server.js.map +1 -0
  65. package/dist/stack.d.ts +117 -0
  66. package/dist/stack.d.ts.map +1 -0
  67. package/dist/stack.js +299 -0
  68. package/dist/stack.js.map +1 -0
  69. package/dist/styles.d.ts +138 -0
  70. package/dist/styles.d.ts.map +1 -0
  71. package/dist/styles.js +920 -0
  72. package/dist/styles.js.map +1 -0
  73. package/dist/template.d.ts +27 -0
  74. package/dist/template.d.ts.map +1 -0
  75. package/dist/template.js +1436 -0
  76. package/dist/template.js.map +1 -0
  77. package/dist/textDecoder.d.ts +29 -0
  78. package/dist/textDecoder.d.ts.map +1 -0
  79. package/dist/textDecoder.js +149 -0
  80. package/dist/textDecoder.js.map +1 -0
  81. package/dist/url.d.ts +45 -0
  82. package/dist/url.d.ts.map +1 -0
  83. package/dist/url.js +303 -0
  84. package/dist/url.js.map +1 -0
  85. package/package.json +96 -3
  86. package/scripts/build-android.sh +27 -0
  87. package/scripts/test-styles.mjs +31 -0
  88. package/specs/NativeOrbit.ts +34 -0
  89. package/src/color.ts +68 -0
  90. package/src/commit.ts +373 -0
  91. package/src/errors.ts +178 -0
  92. package/src/host.ts +91 -0
  93. package/src/index.ts +64 -0
  94. package/src/motion.ts +88 -0
  95. package/src/node.ts +133 -0
  96. package/src/pages.ts +207 -0
  97. package/src/react-native/index.ts +115 -0
  98. package/src/react-native/react-native.d.ts +39 -0
  99. package/src/report.ts +25 -0
  100. package/src/server.ts +395 -0
  101. package/src/stack.ts +428 -0
  102. package/src/styles.ts +1021 -0
  103. package/src/template.ts +1681 -0
  104. package/src/textDecoder.ts +162 -0
  105. package/src/url.ts +333 -0
package/src/server.ts ADDED
@@ -0,0 +1,395 @@
1
+ /**
2
+ * The app's ream server, as one connection: what pages, comet calls and relay
3
+ * subscriptions all go through on the phone.
4
+ *
5
+ * const server = connectServer('https://app.example')
6
+ * serverPages({ server, pages })
7
+ * const rpc = createRpcClient({ url: server.url('/rpc'), transport: server.json })
8
+ * configureRelay({
9
+ * sseUrl: server.url('/__relay/events'),
10
+ * subscribeUrl: server.url('/__relay/subscribe'),
11
+ * unsubscribeUrl: server.url('/__relay/unsubscribe'),
12
+ * stream: server.stream,
13
+ * fetch: server.fetch,
14
+ * })
15
+ *
16
+ * A browser gets this from the page for free: one origin, its cookies sent
17
+ * along, the `XSRF-TOKEN` cookie readable by the page, an `EventSource`. An
18
+ * app has none of it, so the connection gives each: requests to the server's
19
+ * origin only, with the session cookie (React Native sends cookies only with
20
+ * `credentials: 'include'`), the `XSRF-TOKEN` the server set echoed on every
21
+ * mutation, and server-sent events read from React Native's streaming XHR.
22
+ */
23
+
24
+ import {
25
+ E_ORBIT_FOREIGN_ORIGIN,
26
+ E_ORBIT_INSECURE_SERVER,
27
+ E_ORBIT_NO_XHR,
28
+ E_ORBIT_SERVER_REQUEST_FAILED,
29
+ } from "./errors.js";
30
+
31
+ export interface ServerConnection {
32
+ /** The server's origin (`https://app.example`). */
33
+ readonly origin: string;
34
+ /** `path` on the server, absolute. */
35
+ url(path: string): string;
36
+ /**
37
+ * A request to the server: refused for another origin, carrying the
38
+ * session cookie and, on a mutation, the `X-XSRF-TOKEN` the server's
39
+ * `XSRF-TOKEN` cookie set.
40
+ */
41
+ fetch(url: string, init?: RequestInit): Promise<Response>;
42
+ /**
43
+ * POST `body` as JSON and resolve the JSON answer (nothing for a 204): the
44
+ * shape of comet's `RpcTransport`.
45
+ */
46
+ json(
47
+ url: string,
48
+ body: unknown,
49
+ options?: { signal?: AbortSignal },
50
+ ): Promise<unknown>;
51
+ /** A server-sent event stream at `url`: what relay's `stream` option takes. */
52
+ stream(url: string): ServerEventStream;
53
+ /** The `XSRF-TOKEN` the server set last, if any. */
54
+ xsrf(): string | undefined;
55
+ /**
56
+ * Send `Authorization: Bearer <token>` with every request and stream from
57
+ * now on (`null` stops): an API's token, which — unlike a browser's
58
+ * `EventSource` — the phone can send on server-sent events too. With a
59
+ * `tokenStore`, the token is kept there too (and forgotten on `null`);
60
+ * the promise settles once it is.
61
+ */
62
+ authorize(token: string | null): Promise<void>;
63
+ /**
64
+ * Authorize again with the token the `tokenStore` kept, as when the app
65
+ * starts: true when there was one. Without a store, false.
66
+ */
67
+ restore(): Promise<boolean>;
68
+ }
69
+
70
+ /**
71
+ * Where a connection keeps its API token between launches — on a phone,
72
+ * `@c9up/orbit-secure-store`'s getItem / setItem / deleteItem under a key:
73
+ *
74
+ * connectServer(origin, { tokenStore: {
75
+ * get: () => getItem('session'),
76
+ * set: (token) => token === null ? deleteItem('session') : setItem('session', token),
77
+ * } })
78
+ */
79
+ export interface TokenStore {
80
+ get(): Promise<string | null>;
81
+ set(token: string | null): Promise<void>;
82
+ }
83
+
84
+ export interface ConnectOptions {
85
+ /** Keeps the token `authorize` sets, so `restore` finds it at the next launch. */
86
+ tokenStore?: TokenStore;
87
+ }
88
+
89
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "10.0.2.2"]);
90
+ const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
91
+
92
+ /** The `XSRF-TOKEN` a response set, verbatim (the server compares bytes). */
93
+ function xsrfFrom(response: Response): string | undefined {
94
+ const header = response.headers.get("set-cookie");
95
+ if (header === null) return undefined;
96
+ const match = /(?:^|[,;]\s*)XSRF-TOKEN=([^;,]*)/.exec(header);
97
+ return match === null ? undefined : match[1];
98
+ }
99
+
100
+ /** Connect to the app's ream server: https, or http to this machine or the emulator's host. */
101
+ export function connectServer(
102
+ server: string,
103
+ options: ConnectOptions = {},
104
+ ): ServerConnection {
105
+ const base = new URL(server);
106
+ const local = LOCAL_HOSTS.has(base.hostname);
107
+ if (base.protocol !== "https:" && !(base.protocol === "http:" && local)) {
108
+ throw new E_ORBIT_INSECURE_SERVER([base.origin]);
109
+ }
110
+ const origin = base.origin;
111
+ let token: string | undefined;
112
+ let bearer: string | null = null;
113
+
114
+ const url = (path: string): string => {
115
+ const target = new URL(path, `${origin}/`).href;
116
+ if (new URL(target).origin !== origin) {
117
+ throw new E_ORBIT_FOREIGN_ORIGIN([origin, target]);
118
+ }
119
+ return target;
120
+ };
121
+
122
+ const request = async (
123
+ target: string,
124
+ init: RequestInit = {},
125
+ ): Promise<Response> => {
126
+ const absolute = url(target);
127
+ const method = (init.method ?? "GET").toUpperCase();
128
+ const headers = new Headers(init.headers);
129
+ if (
130
+ !SAFE_METHODS.has(method) &&
131
+ token !== undefined &&
132
+ !headers.has("x-xsrf-token")
133
+ ) {
134
+ headers.set("x-xsrf-token", token);
135
+ }
136
+ if (bearer !== null && !headers.has("authorization")) {
137
+ headers.set("authorization", `Bearer ${bearer}`);
138
+ }
139
+ const response = await fetch(absolute, {
140
+ ...init,
141
+ headers,
142
+ credentials: "include",
143
+ });
144
+ token = xsrfFrom(response) ?? token;
145
+ return response;
146
+ };
147
+
148
+ return {
149
+ origin,
150
+ url,
151
+ fetch: request,
152
+ json: async (target, body, options = {}) => {
153
+ const response = await request(target, {
154
+ method: "POST",
155
+ headers: {
156
+ "content-type": "application/json",
157
+ accept: "application/json",
158
+ },
159
+ body: JSON.stringify(body),
160
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
161
+ });
162
+ const text = await response.text();
163
+ if (text !== "") return JSON.parse(text);
164
+ if (response.ok) return undefined;
165
+ throw new E_ORBIT_SERVER_REQUEST_FAILED([target, response.status]);
166
+ },
167
+ stream: (target) =>
168
+ new ServerEventStream(url(target), () => ({
169
+ ...(token === undefined ? {} : { "x-xsrf-token": token }),
170
+ ...(bearer === null ? {} : { authorization: `Bearer ${bearer}` }),
171
+ })),
172
+ xsrf: () => token,
173
+ authorize: async (next) => {
174
+ bearer = next;
175
+ await options.tokenStore?.set(next);
176
+ },
177
+ restore: async () => {
178
+ const kept = await options.tokenStore?.get();
179
+ if (typeof kept !== "string" || kept === "") return false;
180
+ bearer = kept;
181
+ return true;
182
+ },
183
+ };
184
+ }
185
+
186
+ /** A server-sent event: its type, data and id, as an `EventSource`'s `MessageEvent` carries them. */
187
+ export interface ServerEvent {
188
+ readonly type: string;
189
+ readonly data?: string;
190
+ readonly lastEventId?: string;
191
+ }
192
+
193
+ type Listener = (event: ServerEvent) => void;
194
+
195
+ /** The part of React Native's (and the browser's) XMLHttpRequest a stream reads. */
196
+ interface StreamingRequest {
197
+ readyState: number;
198
+ status: number;
199
+ responseText: string;
200
+ withCredentials: boolean;
201
+ onprogress: (() => void) | null;
202
+ onreadystatechange: (() => void) | null;
203
+ onerror: (() => void) | null;
204
+ onload: (() => void) | null;
205
+ open(method: string, url: string): void;
206
+ setRequestHeader(name: string, value: string): void;
207
+ getResponseHeader(name: string): string | null;
208
+ send(): void;
209
+ abort(): void;
210
+ }
211
+
212
+ function isStreamingRequest(value: unknown): value is StreamingRequest {
213
+ return (
214
+ typeof value === "object" &&
215
+ value !== null &&
216
+ typeof Reflect.get(value, "open") === "function" &&
217
+ typeof Reflect.get(value, "send") === "function"
218
+ );
219
+ }
220
+
221
+ function createRequest(): StreamingRequest {
222
+ const Xhr: unknown = Reflect.get(globalThis, "XMLHttpRequest");
223
+ const request: unknown =
224
+ typeof Xhr === "function" ? Reflect.construct(Xhr, []) : undefined;
225
+ if (!isStreamingRequest(request)) {
226
+ throw new E_ORBIT_NO_XHR();
227
+ }
228
+ return request;
229
+ }
230
+
231
+ /** The time before reconnecting when the server set none (`retry:`), in ms. */
232
+ const DEFAULT_RETRY = 3000;
233
+
234
+ /**
235
+ * Server-sent events over XHR — what `EventSource` does, where there is
236
+ * none (React Native): the stream is read as it arrives, parsed as the
237
+ * HTML standard says (`event:`, `data:`, `id:`, `retry:`, comments), each
238
+ * event dispatched under its type; a dropped connection dispatches `error`
239
+ * and reconnects after `retry` ms with `Last-Event-ID`. An answer that is
240
+ * not a 200 `text/event-stream` fails the stream for good (`error`, no
241
+ * reconnect), as `EventSource` does.
242
+ */
243
+ export class ServerEventStream {
244
+ static readonly CONNECTING = 0;
245
+ static readonly OPEN = 1;
246
+ static readonly CLOSED = 2;
247
+
248
+ readonly url: string;
249
+ readyState = ServerEventStream.CONNECTING;
250
+ readonly #listeners = new Map<string, Set<Listener>>();
251
+ readonly #headers: () => Record<string, string>;
252
+ readonly #credentials: boolean;
253
+ #request: StreamingRequest | null = null;
254
+ #retry = DEFAULT_RETRY;
255
+ #lastEventId = "";
256
+ #timer: ReturnType<typeof setTimeout> | null = null;
257
+
258
+ constructor(
259
+ url: string,
260
+ headers: () => Record<string, string> = () => ({}),
261
+ options: { credentials?: boolean } = {},
262
+ ) {
263
+ this.url = url;
264
+ this.#headers = headers;
265
+ this.#credentials = options.credentials ?? true;
266
+ this.#connect();
267
+ }
268
+
269
+ addEventListener(type: string, listener: Listener): void {
270
+ const set = this.#listeners.get(type) ?? new Set();
271
+ set.add(listener);
272
+ this.#listeners.set(type, set);
273
+ }
274
+
275
+ removeEventListener(type: string, listener: Listener): void {
276
+ this.#listeners.get(type)?.delete(listener);
277
+ }
278
+
279
+ close(): void {
280
+ this.readyState = ServerEventStream.CLOSED;
281
+ if (this.#timer !== null) clearTimeout(this.#timer);
282
+ this.#timer = null;
283
+ const request = this.#request;
284
+ this.#request = null;
285
+ request?.abort();
286
+ }
287
+
288
+ #dispatch(event: ServerEvent): void {
289
+ for (const listener of [...(this.#listeners.get(event.type) ?? [])]) {
290
+ listener(event);
291
+ }
292
+ }
293
+
294
+ #connect(): void {
295
+ const request = createRequest();
296
+ this.#request = request;
297
+ let read = 0;
298
+ let buffer = "";
299
+ let type = "";
300
+ let data: string[] = [];
301
+ let checked = false;
302
+
303
+ const line = (text: string): void => {
304
+ if (text === "") {
305
+ if (data.length > 0) {
306
+ this.#dispatch({
307
+ type: type === "" ? "message" : type,
308
+ data: data.join("\n"),
309
+ lastEventId: this.#lastEventId,
310
+ });
311
+ }
312
+ type = "";
313
+ data = [];
314
+ return;
315
+ }
316
+ if (text.startsWith(":")) return;
317
+ const colon = text.indexOf(":");
318
+ const field = colon < 0 ? text : text.slice(0, colon);
319
+ let value = colon < 0 ? "" : text.slice(colon + 1);
320
+ if (value.startsWith(" ")) value = value.slice(1);
321
+ if (field === "event") type = value;
322
+ else if (field === "data") data.push(value);
323
+ else if (field === "id" && !value.includes("\0"))
324
+ this.#lastEventId = value;
325
+ else if (field === "retry" && /^\d+$/.test(value))
326
+ this.#retry = Number(value);
327
+ };
328
+
329
+ const fail = (): boolean => {
330
+ if (checked) return false;
331
+ // Status 0 is a network failure, not an answer: `ended` reconnects.
332
+ if (request.readyState < 2 || request.status === 0) return false;
333
+ checked = true;
334
+ const contentType = request.getResponseHeader("content-type") ?? "";
335
+ if (request.status === 200 && contentType.includes("text/event-stream")) {
336
+ this.readyState = ServerEventStream.OPEN;
337
+ this.#dispatch({ type: "open" });
338
+ return false;
339
+ }
340
+ // Not a stream: fail it for good, as EventSource does.
341
+ this.#request = null;
342
+ request.abort();
343
+ this.readyState = ServerEventStream.CLOSED;
344
+ this.#dispatch({ type: "error" });
345
+ return true;
346
+ };
347
+
348
+ const progress = (): void => {
349
+ if (this.#request !== request || fail()) return;
350
+ const text = request.responseText;
351
+ if (text.length <= read) return;
352
+ let pending = buffer + text.slice(read);
353
+ read = text.length;
354
+ // A trailing `\r` may be the first half of a `\r\n` split across
355
+ // chunks: hold it back, or the `\n` would end a second, empty line.
356
+ const held = pending.endsWith("\r") ? "\r" : "";
357
+ if (held !== "") pending = pending.slice(0, -1);
358
+ const parts = pending.split(/\r\n|\r|\n/);
359
+ buffer = (parts.pop() ?? "") + held;
360
+ for (const part of parts) line(part);
361
+ };
362
+
363
+ const ended = (): void => {
364
+ if (this.#request !== request) return;
365
+ progress();
366
+ if (this.readyState === ServerEventStream.CLOSED) return;
367
+ this.#request = null;
368
+ this.readyState = ServerEventStream.CONNECTING;
369
+ this.#dispatch({ type: "error" });
370
+ if (this.readyState !== ServerEventStream.CONNECTING) return;
371
+ this.#timer = setTimeout(() => {
372
+ this.#timer = null;
373
+ if (this.readyState === ServerEventStream.CONNECTING) this.#connect();
374
+ }, this.#retry);
375
+ };
376
+
377
+ request.onreadystatechange = () => {
378
+ if (request.readyState >= 2) progress();
379
+ };
380
+ request.onprogress = progress;
381
+ request.onload = ended;
382
+ request.onerror = ended;
383
+ request.open("GET", this.url);
384
+ request.withCredentials = this.#credentials;
385
+ request.setRequestHeader("accept", "text/event-stream");
386
+ request.setRequestHeader("cache-control", "no-cache");
387
+ if (this.#lastEventId !== "") {
388
+ request.setRequestHeader("last-event-id", this.#lastEventId);
389
+ }
390
+ for (const [name, value] of Object.entries(this.#headers())) {
391
+ request.setRequestHeader(name, value);
392
+ }
393
+ request.send();
394
+ }
395
+ }