@palgroup/simstream 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # @palgroup/simstream
2
+
3
+ Start and drive remote iOS simulator sessions.
4
+
5
+ ```bash
6
+ npm install @palgroup/simstream
7
+ ```
8
+
9
+ ```ts
10
+ import { SimStream, SimStreamError } from '@palgroup/simstream';
11
+
12
+ const sim = new SimStream({
13
+ baseUrl: process.env.SIMSTREAM_URL!, // the coordinator
14
+ apiKey: process.env.SIMSTREAM_KEY!, // your customer key
15
+ });
16
+
17
+ // A simulator, and your app installed onto it in parallel. The answer comes back before the
18
+ // download starts: the device is already booted and waiting, and making somebody watch a
19
+ // download undoes the reason it was.
20
+ const session = await sim.startSession({
21
+ app: 'https://your-bucket/App.zip', // a .app, zipped. Simulator builds, not .ipa.
22
+ wait: true, // queue instead of failing when the fleet is busy
23
+ onQueue: (position) => console.log(`waiting, ${position} ahead`),
24
+ });
25
+
26
+ // Open it. That is the whole client — a page that streams the simulator and sends touches
27
+ // back. Treat the URL like a password: it carries a grant scoped to one device.
28
+ console.log(session.url);
29
+ ```
30
+
31
+ ## A new build lands
32
+
33
+ Somebody is already looking at a simulator and their app should be replaced under them,
34
+ without reconnecting:
35
+
36
+ ```ts
37
+ await sim.pushBuild('https://your-bucket/App.zip');
38
+ ```
39
+
40
+ It goes only to hosts holding *your* sessions.
41
+
42
+ ## When there is nothing free
43
+
44
+ `startSession()` throws a `SimStreamError`. The `code` says what to do about it:
45
+
46
+ | code | meaning | what to do |
47
+ |---|---|---|
48
+ | `quota` | you are at your own concurrent limit | wait, or raise the limit |
49
+ | `capacity` | the whole fleet is busy | pass `wait: true` |
50
+ | `unauthorized` | the key is not recognised | check `apiKey` |
51
+ | `timeout` | `timeoutMs` elapsed while queued | the ticket is gone; ask again |
52
+ | `gone` | the ticket was already collected, or abandoned | ask again |
53
+
54
+ With `wait: true` the client keeps its place and honours the server's own `retry-after`
55
+ rather than choosing an interval — the server is the one that knows how fast the queue is
56
+ moving. `pollTicket()` is there if you would rather drive the waiting yourself.
57
+
58
+ ## What you used
59
+
60
+ ```ts
61
+ await sim.usage();
62
+ // [{ customer: 'palcore', sessions: 12, seconds: 4210, live: 2 }]
63
+ ```
64
+
65
+ Sessions running right now are counted at their length so far. It is a measurement, not an
66
+ invoice: what a second is worth is not a decision this system makes.
67
+
68
+ ## Notes
69
+
70
+ Needs `fetch` — Node 18+, or pass your own in the options. No other dependencies.
71
+
72
+ The full HTTP surface is in `docs/api.md`; this package is only the part that is easy to get
73
+ subtly wrong: waiting without hammering, telling "still waiting" apart from "gone", and not
74
+ mistaking a viewer link for something you can log.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Creating and revoking customers.
3
+ *
4
+ * Separate from the customer client on purpose, and behind a separate token: a customer must
5
+ * never be able to create a customer, and a single credential for both would mean exactly
6
+ * that. Nothing in an application should import this.
7
+ */
8
+ export interface AdminOptions {
9
+ baseUrl: string;
10
+ /** The coordinator's -admin-token. Not a customer key. */
11
+ adminToken: string;
12
+ fetch?: typeof fetch;
13
+ }
14
+ export interface Customer {
15
+ id: string;
16
+ maxConcurrent: number;
17
+ ratePerMinute: number;
18
+ /** Key prefixes only — the keys themselves are stored hashed and cannot be read back. */
19
+ keys: string[];
20
+ note?: string;
21
+ }
22
+ export declare class SimStreamAdmin {
23
+ private readonly base;
24
+ private readonly token;
25
+ private readonly fetchImpl;
26
+ constructor(opts: AdminOptions);
27
+ /**
28
+ * Creates a customer and its first key.
29
+ *
30
+ * The key is returned here and never again: it is stored hashed, so there is nothing to
31
+ * read back. Put it somewhere before you drop the response.
32
+ */
33
+ createCustomer(input: {
34
+ id: string;
35
+ maxConcurrent: number;
36
+ ratePerMinute?: number;
37
+ note?: string;
38
+ }): Promise<{
39
+ customer: Customer;
40
+ key: string;
41
+ }>;
42
+ listCustomers(): Promise<Customer[]>;
43
+ /** Issues another key. Rotation without downtime: both work until the old one is removed. */
44
+ issueKey(id: string, label?: string): Promise<string>;
45
+ /** Revokes by prefix, because the prefix is the only part of a key anybody still has. */
46
+ revokeKey(id: string, prefix: string): Promise<void>;
47
+ private req;
48
+ }
package/dist/admin.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ /**
3
+ * Creating and revoking customers.
4
+ *
5
+ * Separate from the customer client on purpose, and behind a separate token: a customer must
6
+ * never be able to create a customer, and a single credential for both would mean exactly
7
+ * that. Nothing in an application should import this.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.SimStreamAdmin = void 0;
11
+ class SimStreamAdmin {
12
+ base;
13
+ token;
14
+ fetchImpl;
15
+ constructor(opts) {
16
+ this.base = opts.baseUrl.replace(/\/+$/, '');
17
+ this.token = opts.adminToken;
18
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
19
+ }
20
+ /**
21
+ * Creates a customer and its first key.
22
+ *
23
+ * The key is returned here and never again: it is stored hashed, so there is nothing to
24
+ * read back. Put it somewhere before you drop the response.
25
+ */
26
+ async createCustomer(input) {
27
+ const res = await this.req('POST', '/api/customers', input);
28
+ return (await res.json());
29
+ }
30
+ async listCustomers() {
31
+ const res = await this.req('GET', '/api/customers');
32
+ return (await res.json());
33
+ }
34
+ /** Issues another key. Rotation without downtime: both work until the old one is removed. */
35
+ async issueKey(id, label) {
36
+ const res = await this.req('POST', `/api/customers/${encodeURIComponent(id)}/keys`, { label });
37
+ return (await res.json()).key;
38
+ }
39
+ /** Revokes by prefix, because the prefix is the only part of a key anybody still has. */
40
+ async revokeKey(id, prefix) {
41
+ await this.req('DELETE', `/api/customers/${encodeURIComponent(id)}/keys/${encodeURIComponent(prefix)}`);
42
+ }
43
+ async req(method, path, body) {
44
+ const res = await this.fetchImpl(`${this.base}${path}`, {
45
+ method,
46
+ headers: {
47
+ 'x-admin-token': this.token,
48
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
49
+ },
50
+ body: body === undefined ? undefined : JSON.stringify(body),
51
+ });
52
+ if (res.status >= 400) {
53
+ throw new Error((await res.text().catch(() => '')).trim() || `HTTP ${res.status}`);
54
+ }
55
+ return res;
56
+ }
57
+ }
58
+ exports.SimStreamAdmin = SimStreamAdmin;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Start and drive remote iOS simulator sessions.
3
+ *
4
+ * The API underneath is plain HTTP and documented in `docs/api.md`; this exists so that using
5
+ * it does not mean reimplementing the parts that are easy to get subtly wrong — waiting in a
6
+ * queue without hammering, telling "still waiting" apart from "gone", and never mistaking a
7
+ * viewer link for something you can put in a log.
8
+ *
9
+ * Nothing here knows who the caller is. That is the point: the same package serves the first
10
+ * customer and the tenth, and the day one of them needs a method the others cannot have, the
11
+ * separation has stopped being real.
12
+ */
13
+ export interface SimStreamOptions {
14
+ /** Coordinator base URL, e.g. https://simstream.example */
15
+ baseUrl: string;
16
+ /** Customer API key. Sent as x-api-key. */
17
+ apiKey: string;
18
+ /** Defaults to global fetch; supply one for older Node or for tests. */
19
+ fetch?: typeof fetch;
20
+ }
21
+ export interface Session {
22
+ /**
23
+ * Open this in a browser. It carries a grant scoped to one device and expiring, so it is a
24
+ * capability rather than an address: treat it like a password, not like a URL.
25
+ */
26
+ url: string;
27
+ host: string;
28
+ device: string;
29
+ name: string;
30
+ expiresAt?: string;
31
+ /** This session's id. Needed to end it, and therefore to switch device without paying for two. */
32
+ session?: string;
33
+ /** Present when an app was supplied; poll it to watch the install. Carries no credential. */
34
+ appStatus?: string;
35
+ app?: string;
36
+ }
37
+ export interface DeviceKind {
38
+ /** What to pass as `device` when starting a session — a name, matched loosely. */
39
+ name: string;
40
+ runtime: string;
41
+ count: number;
42
+ free: number;
43
+ }
44
+ export interface AppStatus {
45
+ /** Empty when nothing has been pushed to this simulator yet. */
46
+ phase?: 'downloading' | 'installing' | 'launching' | 'ready' | 'failed';
47
+ bundle?: string;
48
+ /** Present only with phase 'failed', and it says what went wrong rather than that it did. */
49
+ error?: string;
50
+ elapsed?: string;
51
+ }
52
+ export interface StartOptions {
53
+ /** A .app directory, or a .zip/.tar.gz containing one. Simulator builds, not .ipa. */
54
+ app?: string;
55
+ /**
56
+ * The kind of device to open — "iPad", "iphone-17", or an exact udid.
57
+ *
58
+ * Matched loosely against the device's name, because a customer knows they want an iPad and has
59
+ * no idea which machine in which rack is holding one. Omitted means whatever is free.
60
+ */
61
+ device?: string;
62
+ /** Launch it once installed. Default true. */
63
+ launch?: boolean;
64
+ /**
65
+ * Wait for a device when the fleet is full or this customer is at its limit, instead of
66
+ * failing. The wait is usually seconds — a session ends every time somebody closes a tab.
67
+ */
68
+ wait?: boolean;
69
+ /** How long the returned link stays valid. Default is the server's, thirty minutes. */
70
+ ttl?: string;
71
+ /** Give up waiting. Rejects with SimStreamError code 'timeout'. */
72
+ timeoutMs?: number;
73
+ signal?: AbortSignal;
74
+ /** Called with the queue position while waiting, so a caller can show it. */
75
+ onQueue?: (position: number, reason: string) => void;
76
+ }
77
+ export interface UsageRecord {
78
+ customer: string;
79
+ session: string;
80
+ device: string;
81
+ host: string;
82
+ started: string;
83
+ ended: string;
84
+ seconds: number;
85
+ ratePerMinute: number;
86
+ /** What this session cost, at the rate in force when it ended. */
87
+ cost: number;
88
+ }
89
+ export interface CustomerUsage {
90
+ customer: string;
91
+ sessions: number;
92
+ seconds: number;
93
+ live: number;
94
+ cost: number;
95
+ }
96
+ export type SimStreamErrorCode = 'unauthorized' | 'quota' | 'capacity' | 'timeout' | 'gone' | 'http';
97
+ export declare class SimStreamError extends Error {
98
+ readonly code: SimStreamErrorCode;
99
+ readonly status?: number | undefined;
100
+ constructor(message: string, code: SimStreamErrorCode, status?: number | undefined);
101
+ }
102
+ export declare class SimStream {
103
+ private readonly base;
104
+ private readonly key;
105
+ private readonly fetchImpl;
106
+ constructor(opts: SimStreamOptions);
107
+ /**
108
+ * Claim a simulator. With `wait`, keeps a place in line until one frees up rather than
109
+ * failing — and honours the server's own retry-after rather than choosing an interval,
110
+ * because the server is the one that knows how quickly the queue is moving.
111
+ */
112
+ startSession(opts?: StartOptions): Promise<Session>;
113
+ /** Where a queued session got to, without waiting for it. */
114
+ pollTicket(ticket: string): Promise<Session | {
115
+ position: number;
116
+ }>;
117
+ /**
118
+ * A new build has appeared; put it on the sessions this customer already has open.
119
+ *
120
+ * This is the other direction from `startSession({app})`: nobody is starting anything, the
121
+ * person is already looking at a simulator and their app should be replaced under them.
122
+ *
123
+ * Pass `version` whenever you have one — R2's etag, a git sha, a build number. A presigned
124
+ * URL cannot serve as the identity of a build: its signature changes every time it is
125
+ * generated, so the same object presigned twice looks like two different sources and every
126
+ * push re-downloads. With a version, an artifact already on the host costs nothing at all.
127
+ */
128
+ pushBuild(app: string, opts?: {
129
+ version?: string;
130
+ launch?: boolean;
131
+ }): Promise<{
132
+ hosts: number;
133
+ version?: string;
134
+ }>;
135
+ /**
136
+ * A fresh link to a session that is already running.
137
+ *
138
+ * ‼️ A GRANT EXPIRES AND A SESSION DOES NOT. The link handed back when a session was claimed
139
+ * carries a grant good for minutes; the session outlives it, so anything that stored that link and
140
+ * showed it later — a studio panel reopened an hour on — embeds a URL the Mac correctly refuses.
141
+ * Ask for a new one rather than holding the old one open for longer: a link that never expires is
142
+ * a link that still works after it leaks.
143
+ */
144
+ sessionLink(session: string, opts?: {
145
+ ttl?: string;
146
+ }): Promise<{
147
+ url: string;
148
+ expiresAt?: string;
149
+ }>;
150
+ /**
151
+ * The kinds of simulator this customer can ask for.
152
+ *
153
+ * ‼️ ASK RATHER THAN HARDCODE. What is on offer is whatever the fleet is running, and it changes
154
+ * when a Mac joins, when a runtime is installed, and when a new platform arrives. A menu written
155
+ * into a client goes stale without saying so — it offered an iPad while streaming an iPhone.
156
+ *
157
+ * `free` is how many could be claimed right now without crowding a host; `count` is how many exist.
158
+ */
159
+ devices(): Promise<DeviceKind[]>;
160
+ /**
161
+ * How far the app pushed to this session has got.
162
+ *
163
+ * ‼️ pushBuild ANSWERS "SENT", NOT "THERE". It returns as soon as the Macs have taken the job; the
164
+ * download, the install and the launch happen after, and until they finish the session is a live
165
+ * simulator showing a home screen. Poll this to tell that apart from a failure — `error` carries
166
+ * the reason, and `phase` is one of downloading, installing, launching, ready, failed.
167
+ */
168
+ appStatus(session: string): Promise<AppStatus>;
169
+ /**
170
+ * Show one of the app's screens on the simulator this session is watching.
171
+ *
172
+ * ‼️ NOTHING RESTARTS. An app built to host its own previews carries every screen it was compiled
173
+ * with and takes the choice live, so a person clicking through a list sees each screen arrive in a
174
+ * frame. Name the screen by its preview id, or by the screen and the state within it — whichever
175
+ * the catalogue gave you.
176
+ *
177
+ * Rejected with `unavailable` when the app on that simulator is not one that takes live changes;
178
+ * the message says which, because "the app was started outside this agent" and "no app is
179
+ * installed" send you to different places.
180
+ */
181
+ showPreview(session: string, target: {
182
+ previewId?: string;
183
+ screen?: string;
184
+ variant?: string;
185
+ }): Promise<void>;
186
+ /**
187
+ * The language and theme the app renders in, changed live.
188
+ *
189
+ * This is the APP's appearance, not the simulator's: two people watching two devices can read two
190
+ * languages, and neither setting survives into whatever runs there next.
191
+ */
192
+ setAppearance(session: string, look: {
193
+ lang?: string;
194
+ theme?: 'light' | 'dark' | 'system';
195
+ }): Promise<void>;
196
+ /**
197
+ * End a session now, rather than waiting for the viewer to close.
198
+ *
199
+ * Idempotent, and silent about sessions that are not this customer's: telling a caller apart
200
+ * from a stranger by which error they get is how session ids become a way to probe the fleet.
201
+ */
202
+ endSession(session: string): Promise<void>;
203
+ /**
204
+ * Move this customer to a different kind of device, keeping one simulator at a time.
205
+ *
206
+ * ‼️ THE OLD SESSION IS ENDED FIRST, AND THAT IS THE WHOLE DIFFERENCE. A customer entitled to one
207
+ * simulator who claims a second before releasing the first is over their own limit for the length
208
+ * of the switch — and on a fleet with one device free, refused the very thing they asked for.
209
+ */
210
+ switchDevice(session: string, device: string, opts?: StartOptions): Promise<Session>;
211
+ /** What this customer has used, in total. A measurement, not an invoice. */
212
+ usage(): Promise<CustomerUsage[]>;
213
+ /**
214
+ * The individual sessions, which is what you store against a project so you can bill for it
215
+ * later. Each carries the rate that was in force when it ended, so a price change does not
216
+ * rewrite what somebody already used.
217
+ */
218
+ sessions(): Promise<UsageRecord[]>;
219
+ private sessionUrl;
220
+ private collect;
221
+ private request;
222
+ private errorFor;
223
+ }
224
+ export { SimStreamAdmin } from './admin';
225
+ export type { AdminOptions, Customer } from './admin';
package/dist/index.js ADDED
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+ /**
3
+ * Start and drive remote iOS simulator sessions.
4
+ *
5
+ * The API underneath is plain HTTP and documented in `docs/api.md`; this exists so that using
6
+ * it does not mean reimplementing the parts that are easy to get subtly wrong — waiting in a
7
+ * queue without hammering, telling "still waiting" apart from "gone", and never mistaking a
8
+ * viewer link for something you can put in a log.
9
+ *
10
+ * Nothing here knows who the caller is. That is the point: the same package serves the first
11
+ * customer and the tenth, and the day one of them needs a method the others cannot have, the
12
+ * separation has stopped being real.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SimStreamAdmin = exports.SimStream = exports.SimStreamError = void 0;
16
+ class SimStreamError extends Error {
17
+ code;
18
+ status;
19
+ constructor(message, code, status) {
20
+ super(message);
21
+ this.code = code;
22
+ this.status = status;
23
+ this.name = 'SimStreamError';
24
+ }
25
+ }
26
+ exports.SimStreamError = SimStreamError;
27
+ const sleep = (ms, signal) => new Promise((resolve, reject) => {
28
+ const t = setTimeout(resolve, ms);
29
+ signal?.addEventListener('abort', () => {
30
+ clearTimeout(t);
31
+ reject(new SimStreamError('aborted', 'timeout'));
32
+ }, { once: true });
33
+ });
34
+ class SimStream {
35
+ base;
36
+ key;
37
+ fetchImpl;
38
+ constructor(opts) {
39
+ if (!opts.baseUrl)
40
+ throw new SimStreamError('baseUrl is required', 'http');
41
+ if (!opts.apiKey)
42
+ throw new SimStreamError('apiKey is required', 'unauthorized');
43
+ this.base = opts.baseUrl.replace(/\/+$/, '');
44
+ this.key = opts.apiKey;
45
+ this.fetchImpl = opts.fetch ?? globalThis.fetch;
46
+ if (!this.fetchImpl) {
47
+ throw new SimStreamError('no fetch available; pass one in options', 'http');
48
+ }
49
+ }
50
+ /**
51
+ * Claim a simulator. With `wait`, keeps a place in line until one frees up rather than
52
+ * failing — and honours the server's own retry-after rather than choosing an interval,
53
+ * because the server is the one that knows how quickly the queue is moving.
54
+ */
55
+ async startSession(opts = {}) {
56
+ const body = {
57
+ app: opts.app,
58
+ launch: opts.launch,
59
+ queue: opts.wait === true,
60
+ device: opts.device,
61
+ };
62
+ const deadline = opts.timeoutMs ? Date.now() + opts.timeoutMs : Infinity;
63
+ const res = await this.request('POST', this.sessionUrl(opts.ttl), body);
64
+ if (res.status === 200)
65
+ return (await res.json());
66
+ if (res.status === 202) {
67
+ const first = (await res.json());
68
+ opts.onQueue?.(first.position, first.reason ?? '');
69
+ return this.collect(first.ticket, deadline, opts);
70
+ }
71
+ throw await this.errorFor(res);
72
+ }
73
+ /** Where a queued session got to, without waiting for it. */
74
+ async pollTicket(ticket) {
75
+ const res = await this.request('GET', `/api/session?ticket=${encodeURIComponent(ticket)}`);
76
+ if (res.status === 200)
77
+ return (await res.json());
78
+ if (res.status === 202)
79
+ return (await res.json());
80
+ throw await this.errorFor(res);
81
+ }
82
+ /**
83
+ * A new build has appeared; put it on the sessions this customer already has open.
84
+ *
85
+ * This is the other direction from `startSession({app})`: nobody is starting anything, the
86
+ * person is already looking at a simulator and their app should be replaced under them.
87
+ *
88
+ * Pass `version` whenever you have one — R2's etag, a git sha, a build number. A presigned
89
+ * URL cannot serve as the identity of a build: its signature changes every time it is
90
+ * generated, so the same object presigned twice looks like two different sources and every
91
+ * push re-downloads. With a version, an artifact already on the host costs nothing at all.
92
+ */
93
+ async pushBuild(app, opts = {}) {
94
+ const res = await this.request('POST', '/api/builds', {
95
+ app,
96
+ version: opts.version,
97
+ launch: opts.launch,
98
+ });
99
+ if (res.status !== 200)
100
+ throw await this.errorFor(res);
101
+ return (await res.json());
102
+ }
103
+ /**
104
+ * A fresh link to a session that is already running.
105
+ *
106
+ * ‼️ A GRANT EXPIRES AND A SESSION DOES NOT. The link handed back when a session was claimed
107
+ * carries a grant good for minutes; the session outlives it, so anything that stored that link and
108
+ * showed it later — a studio panel reopened an hour on — embeds a URL the Mac correctly refuses.
109
+ * Ask for a new one rather than holding the old one open for longer: a link that never expires is
110
+ * a link that still works after it leaks.
111
+ */
112
+ async sessionLink(session, opts = {}) {
113
+ const res = await this.request('POST', `/api/session/link${opts.ttl ? `?ttl=${encodeURIComponent(opts.ttl)}` : ''}`, {
114
+ session,
115
+ });
116
+ if (res.status !== 200)
117
+ throw await this.errorFor(res);
118
+ return (await res.json());
119
+ }
120
+ /**
121
+ * The kinds of simulator this customer can ask for.
122
+ *
123
+ * ‼️ ASK RATHER THAN HARDCODE. What is on offer is whatever the fleet is running, and it changes
124
+ * when a Mac joins, when a runtime is installed, and when a new platform arrives. A menu written
125
+ * into a client goes stale without saying so — it offered an iPad while streaming an iPhone.
126
+ *
127
+ * `free` is how many could be claimed right now without crowding a host; `count` is how many exist.
128
+ */
129
+ async devices() {
130
+ const res = await this.request('GET', '/api/devices');
131
+ if (res.status !== 200)
132
+ throw await this.errorFor(res);
133
+ return (await res.json()).devices ?? [];
134
+ }
135
+ /**
136
+ * How far the app pushed to this session has got.
137
+ *
138
+ * ‼️ pushBuild ANSWERS "SENT", NOT "THERE". It returns as soon as the Macs have taken the job; the
139
+ * download, the install and the launch happen after, and until they finish the session is a live
140
+ * simulator showing a home screen. Poll this to tell that apart from a failure — `error` carries
141
+ * the reason, and `phase` is one of downloading, installing, launching, ready, failed.
142
+ */
143
+ async appStatus(session) {
144
+ const res = await this.request('GET', `/api/session/app?session=${encodeURIComponent(session)}`);
145
+ if (res.status !== 200)
146
+ throw await this.errorFor(res);
147
+ return (await res.json());
148
+ }
149
+ /**
150
+ * Show one of the app's screens on the simulator this session is watching.
151
+ *
152
+ * ‼️ NOTHING RESTARTS. An app built to host its own previews carries every screen it was compiled
153
+ * with and takes the choice live, so a person clicking through a list sees each screen arrive in a
154
+ * frame. Name the screen by its preview id, or by the screen and the state within it — whichever
155
+ * the catalogue gave you.
156
+ *
157
+ * Rejected with `unavailable` when the app on that simulator is not one that takes live changes;
158
+ * the message says which, because "the app was started outside this agent" and "no app is
159
+ * installed" send you to different places.
160
+ */
161
+ async showPreview(session, target) {
162
+ const res = await this.request('POST', '/api/session/preview', { session, ...target });
163
+ if (res.status !== 200)
164
+ throw await this.errorFor(res);
165
+ }
166
+ /**
167
+ * The language and theme the app renders in, changed live.
168
+ *
169
+ * This is the APP's appearance, not the simulator's: two people watching two devices can read two
170
+ * languages, and neither setting survives into whatever runs there next.
171
+ */
172
+ async setAppearance(session, look) {
173
+ const res = await this.request('POST', '/api/session/appearance', { session, ...look });
174
+ if (res.status !== 200)
175
+ throw await this.errorFor(res);
176
+ }
177
+ /**
178
+ * End a session now, rather than waiting for the viewer to close.
179
+ *
180
+ * Idempotent, and silent about sessions that are not this customer's: telling a caller apart
181
+ * from a stranger by which error they get is how session ids become a way to probe the fleet.
182
+ */
183
+ async endSession(session) {
184
+ await this.request('POST', '/api/session/end', { session });
185
+ }
186
+ /**
187
+ * Move this customer to a different kind of device, keeping one simulator at a time.
188
+ *
189
+ * ‼️ THE OLD SESSION IS ENDED FIRST, AND THAT IS THE WHOLE DIFFERENCE. A customer entitled to one
190
+ * simulator who claims a second before releasing the first is over their own limit for the length
191
+ * of the switch — and on a fleet with one device free, refused the very thing they asked for.
192
+ */
193
+ async switchDevice(session, device, opts = {}) {
194
+ await this.endSession(session);
195
+ return this.startSession({ ...opts, device });
196
+ }
197
+ /** What this customer has used, in total. A measurement, not an invoice. */
198
+ async usage() {
199
+ const res = await this.request('GET', '/api/usage');
200
+ if (res.status !== 200)
201
+ throw await this.errorFor(res);
202
+ return (await res.json());
203
+ }
204
+ /**
205
+ * The individual sessions, which is what you store against a project so you can bill for it
206
+ * later. Each carries the rate that was in force when it ended, so a price change does not
207
+ * rewrite what somebody already used.
208
+ */
209
+ async sessions() {
210
+ const res = await this.request('GET', '/api/usage?detail=1');
211
+ if (res.status !== 200)
212
+ throw await this.errorFor(res);
213
+ return (await res.json());
214
+ }
215
+ sessionUrl(ttl) {
216
+ return ttl ? `/api/session?ttl=${encodeURIComponent(ttl)}` : '/api/session';
217
+ }
218
+ async collect(ticket, deadline, opts) {
219
+ for (;;) {
220
+ if (Date.now() > deadline) {
221
+ throw new SimStreamError('gave up waiting for a simulator', 'timeout');
222
+ }
223
+ const res = await this.request('GET', `/api/session?ticket=${encodeURIComponent(ticket)}`);
224
+ if (res.status === 200)
225
+ return (await res.json());
226
+ if (res.status === 202) {
227
+ const body = (await res.json());
228
+ opts.onQueue?.(body.position, body.reason ?? '');
229
+ // The server says how soon to come back; guessing an interval either hammers it or
230
+ // leaves somebody waiting after their turn came up.
231
+ const after = Number(res.headers.get('retry-after') ?? '2');
232
+ await sleep(Math.max(1, after) * 1000, opts.signal);
233
+ continue;
234
+ }
235
+ throw await this.errorFor(res);
236
+ }
237
+ }
238
+ request(method, path, body) {
239
+ return this.fetchImpl(`${this.base}${path}`, {
240
+ method,
241
+ headers: {
242
+ 'x-api-key': this.key,
243
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
244
+ },
245
+ body: body === undefined ? undefined : JSON.stringify(body),
246
+ });
247
+ }
248
+ async errorFor(res) {
249
+ const text = (await res.text().catch(() => '')).trim();
250
+ // The status is the fact; the body is what to tell somebody. Both are kept, because
251
+ // "429" alone does not say whose limit was reached.
252
+ const code = res.status === 401 ? 'unauthorized'
253
+ : res.status === 429 ? 'quota'
254
+ : res.status === 503 ? 'capacity'
255
+ : res.status === 410 ? 'gone'
256
+ : 'http';
257
+ return new SimStreamError(text || `HTTP ${res.status}`, code, res.status);
258
+ }
259
+ }
260
+ exports.SimStream = SimStream;
261
+ var admin_1 = require("./admin");
262
+ Object.defineProperty(exports, "SimStreamAdmin", { enumerable: true, get: function () { return admin_1.SimStreamAdmin; } });
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@palgroup/simstream",
3
+ "version": "0.6.0",
4
+ "description": "Start and drive remote iOS simulator sessions.",
5
+ "license": "Apache-2.0",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "LICENSE"
11
+ ],
12
+ "scripts": {
13
+ "build": "tsc -p tsconfig.json",
14
+ "test": "tsc -p tsconfig.test.json && node --test dist-test/*.test.js"
15
+ },
16
+ "devDependencies": {
17
+ "typescript": "^5.6.0",
18
+ "@types/node": "^22.0.0"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/palgroup/simstream.git",
23
+ "directory": "sdk/ts"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "homepage": "https://github.com/palgroup/simstream#readme",
29
+ "keywords": [
30
+ "ios",
31
+ "simulator",
32
+ "webrtc",
33
+ "remote",
34
+ "preview",
35
+ "simstream"
36
+ ],
37
+ "engines": {
38
+ "node": ">=18"
39
+ }
40
+ }