@nativescript/cloudflare-cli 0.1.0-beta.1 → 0.1.0-beta.11

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/README.md CHANGED
@@ -1,10 +1,21 @@
1
1
  # @nativescript/cloudflare-cli
2
2
 
3
+ ```sh
4
+ npx @nativescript/cloudflare-cli live # a phone app: opens the IDE and prints a QR code for NativeScript Preview
5
+ npx @nativescript/cloudflare-cli live --react # the same with a framework: --ng (Angular), --react, --vue, --svelte or --solid
6
+ npx @nativescript/cloudflare-cli live --mac # a Mac app: opens the IDE and runs the app on this Mac, streamed into the IDE
7
+ npx @nativescript/cloudflare-cli live --electron # an Electron app with native views, run the same way
8
+ ```
9
+
10
+ `live` creates a project on preview.nativescript.org (`--server` or `NS_EDGE_SERVER` for another edge), saves it to `.ns-edge.json` and opens its IDE. The framework flags are `ns create`'s (`--ng`/`--angular`, `--react`, `--vue`, `--svelte`, `--solid`, `--ts`); without one a phone project is plain TypeScript with XML views. Run it again in the same folder to reopen that project (no flag needed), or add `--new` for another; a flag for a different kind of project than the folder's asks for `--new`. `--from <sample>` starts from a copy of a shared project instead: a sample's name (`--from expo-settings`; `samples` lists them), or any project's link or bare id. While `live` runs a Mac app it restarts the app if it crashes, unless it crashes three times in a minute. Without a create token the project is free: a few hosted agent turns a day, no backend, deleted after 30 days unused. `--no-open` skips the browser; with `--mac` or `--electron`, `--allow-eval` lets the agent run code on this Mac.
11
+
12
+ ## Mirror a local project
13
+
3
14
  Mirror a NativeScript project into an ns-edge project from a terminal or a Vite dev server.
4
15
 
5
16
  ```sh
6
17
  npm i -D @nativescript/cloudflare-cli@beta
7
- npx ns-edge create --server https://preview.nativescript.org --token <create token>
18
+ npx ns-edge create --server https://preview.nativescript.org --token <create token> # --template vue for nativescript-vue
8
19
  npx ns-edge watch # push, then every save
9
20
  npx ns-edge qr # print the pairing QR code again
10
21
  ```
package/dist/bin.js CHANGED
@@ -1,12 +1,46 @@
1
1
  #!/usr/bin/env node
2
- import { watch } from 'node:fs';
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync, watch } from 'node:fs';
3
4
  import { readFile, writeFile } from 'node:fs/promises';
4
- import { join, sep } from 'node:path';
5
+ import { dirname, join, sep } from 'node:path';
5
6
  import { createInterface } from 'node:readline/promises';
6
7
  import QRCode from 'qrcode';
7
8
  import { applyChanges, collect, createProject, projectUrl, report, SYNCED } from './sync.js';
8
9
  const CONFIG = '.ns-edge.json';
9
10
  const DEBOUNCE_MS = 120;
11
+ const LIVE_SERVER = process.env.NS_EDGE_SERVER ?? 'https://preview.nativescript.org';
12
+ /** The hosts `live --desktop` (or `--mac`, `--windows`), `--electron` and `--expo` run; bump them with each host release this CLI is tested against. */
13
+ const DESKTOP_HOSTS = {
14
+ macos: { spec: '@nativescript/cloudflare-desktop@0.1.0-alpha.6', bin: 'ns-edge-desktop' },
15
+ electron: { spec: '@nativescript/cloudflare-electron@0.1.0-alpha.3', bin: 'ns-edge-electron' },
16
+ expo: { spec: '@nativescript/cloudflare-expo-desktop@0.1.0-alpha.1', bin: 'ns-edge-expo-desktop' },
17
+ };
18
+ const DESKTOP_TEMPLATES = new Set(['macos', 'electron', 'expo']);
19
+ /** The macos template is the desktop one: it runs on a Mac with AppKit and on Windows with WinUI, so all three flags pick it. */
20
+ const DESKTOP_FLAGS = { macos: ['desktop', 'mac', 'windows'], electron: ['electron'], expo: ['expo'] };
21
+ /** The NativeScript CLI's `ns create` framework flags, so `live` and `create` take the same ones. */
22
+ const FRAMEWORK_FLAGS = {
23
+ angular: ['ng', 'angular'],
24
+ react: ['react', 'reactjs'],
25
+ vue: ['vue', 'vuejs'],
26
+ svelte: ['svelte'],
27
+ solid: ['solid', 'solidjs'],
28
+ core: ['ts', 'tsc', 'typescript'],
29
+ };
30
+ const TEMPLATE_KINDS = {
31
+ core: 'a phone',
32
+ angular: 'an Angular phone',
33
+ react: 'a React phone',
34
+ vue: 'a Vue phone',
35
+ svelte: 'a Svelte phone',
36
+ solid: 'a Solid phone',
37
+ macos: 'a desktop',
38
+ electron: 'an Electron',
39
+ expo: 'an Expo Desktop',
40
+ };
41
+ const MAX_CRASHES = 3;
42
+ const CRASH_WINDOW_MS = 60_000;
43
+ const RESTART_DELAY_MS = 1000;
10
44
  const [cmd = 'help', ...args] = process.argv.slice(2);
11
45
  /**
12
46
  * Editors and tools write temp, swap and backup files next to the real one
@@ -18,6 +52,23 @@ const flag = (name) => {
18
52
  const i = args.indexOf(`--${name}`);
19
53
  return i >= 0 ? args[i + 1] : undefined;
20
54
  };
55
+ const has = (name) => args.includes(`--${name}`);
56
+ /** The template --template, a framework flag or a desktop flag asks for, if any; asking for two is an error. */
57
+ function requestedTemplate() {
58
+ const asked = new Set();
59
+ const named = flag('template');
60
+ if (named)
61
+ asked.add(named);
62
+ for (const [template, names] of Object.entries(FRAMEWORK_FLAGS))
63
+ if (names.some((name) => has(name)))
64
+ asked.add(template);
65
+ for (const [template, names] of Object.entries(DESKTOP_FLAGS))
66
+ if (names.some((name) => has(name)))
67
+ asked.add(template);
68
+ if (asked.size > 1)
69
+ throw new Error(`Pick one kind of project: this asked for ${[...asked].join(' and ')}.`);
70
+ return [...asked][0];
71
+ }
21
72
  const root = process.cwd();
22
73
  async function loadRef() {
23
74
  let ref;
@@ -52,10 +103,172 @@ async function printPairing(ref) {
52
103
  console.log(` device ${device}`);
53
104
  console.log(` ide ${url}/#key=${ref.writeKey}`);
54
105
  }
106
+ /** This folder's project, if it has one the server still knows. */
107
+ /**
108
+ * The project `--from` names: a link to it (its IDE, read-only or device link),
109
+ * a bare id, or a sample's name on this CLI's server, with what it was made as.
110
+ */
111
+ async function sourceProject(from) {
112
+ let server = flag('server') ?? LIVE_SERVER;
113
+ let id = from;
114
+ if (!/^[0-9a-f]{32}$/.test(from)) {
115
+ if (URL.canParse(from) && /^https?:$/.test(new URL(from).protocol)) {
116
+ const link = new URL(from);
117
+ const match = link.pathname.match(/^\/p\/([0-9a-f]{32})(?:\/|$)/) ?? link.pathname.match(/^\/p\/([a-z0-9-]+)\/?$/);
118
+ if (!match)
119
+ throw new Error(`--from takes a sample's name, a project link (https://…/p/<id>) or its id, not '${from}'.`);
120
+ server = link.origin;
121
+ id = match[1];
122
+ }
123
+ if (!/^[0-9a-f]{32}$/.test(id))
124
+ id = await sampleId(server, id);
125
+ }
126
+ const res = await fetch(`${server}/p/${id}/details`).catch(() => null);
127
+ if (!res?.ok)
128
+ throw new Error(`There's no project ${id} on ${server} to start from.`);
129
+ const { template, title } = (await res.json());
130
+ return { server, id, template, title };
131
+ }
132
+ async function listSamples(server) {
133
+ const res = await fetch(`${server}/api/samples`).catch(() => null);
134
+ if (!res?.ok || !res.headers.get('content-type')?.includes('json'))
135
+ return null;
136
+ return (await res.json());
137
+ }
138
+ async function sampleId(server, name) {
139
+ const res = await fetch(`${server}/api/samples/${encodeURIComponent(name)}`).catch(() => null);
140
+ if (!res)
141
+ throw new Error(`Couldn't reach ${server} to look up the sample '${name}'.`);
142
+ if (res.ok && res.headers.get('content-type')?.includes('json'))
143
+ return (await res.json()).id;
144
+ const names = (await listSamples(server))?.map((s) => s.name) ?? [];
145
+ const known = names.length ? ` Its samples: ${names.join(', ')}.` : '';
146
+ throw new Error(`There's no sample named '${name}' on ${server}.${known} --from also takes a project link or its full 32-character id.`);
147
+ }
148
+ async function savedProject() {
149
+ if (!existsSync(join(root, CONFIG)))
150
+ return null;
151
+ const ref = JSON.parse(await readFile(join(root, CONFIG), 'utf8'));
152
+ if (!ref.writeKey)
153
+ return null;
154
+ const res = await fetch(`${projectUrl(ref)}/files`).catch(() => null);
155
+ return res?.ok ? ref : null;
156
+ }
157
+ function openInBrowser(url) {
158
+ const [command, ...rest] = process.platform === 'darwin' ? ['open', url] : process.platform === 'win32' ? ['cmd', '/c', 'start', '""', url.replace(/&/g, '^&')] : ['xdg-open', url];
159
+ spawn(command, rest, { stdio: 'ignore', detached: true }).on('error', () => { }).unref();
160
+ }
161
+ const COMPUTER = process.platform === 'win32' ? 'PC' : 'Mac';
162
+ /**
163
+ * How to run npx. On Windows it's npx.cmd, which Node won't spawn without a
164
+ * shell (and a shell would re-parse the arguments), so npm's own npx-cli.js
165
+ * runs with this Node instead when it's where Node's installer puts it.
166
+ */
167
+ function npx() {
168
+ if (process.platform !== 'win32')
169
+ return ['npx'];
170
+ const cli = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js');
171
+ return existsSync(cli) ? [process.execPath, cli] : ['npx.cmd'];
172
+ }
173
+ /**
174
+ * Runs the desktop host for a desktop project until it quits or Ctrl+C. A host
175
+ * that crashes is started again, since nothing in the browser can reach this
176
+ * computer to do it, unless it keeps crashing. The host says what joining allows.
177
+ */
178
+ async function runDesktopHost(ref) {
179
+ const mac = process.platform === 'darwin' && process.arch === 'arm64';
180
+ const windows = process.platform === 'win32' && (process.arch === 'x64' || process.arch === 'arm64');
181
+ if (ref.template === 'expo' && !mac && !(windows && process.arch === 'x64')) {
182
+ throw new Error('Expo Desktop projects run on an Apple Silicon Mac (macOS 14.4 or later) or a Windows x64 PC. Run the same command on one.');
183
+ }
184
+ if (!mac && !windows) {
185
+ throw new Error('Desktop projects run on an Apple Silicon Mac (macOS 14.4 or later) or a Windows 10 (1903 or later) or Windows 11 PC. Run the same command there.');
186
+ }
187
+ const device = `${projectUrl(ref)}#${ref.deviceKey}`;
188
+ const extra = has('allow-eval') ? ['--allow-eval'] : [];
189
+ const host = DESKTOP_HOSTS[ref.template ?? 'macos'] ?? DESKTOP_HOSTS.macos;
190
+ // NS_EDGE_HOST runs another spec of the host (a version, or file:<packed .tgz>) to test a release before publishing it.
191
+ const spec = process.env.NS_EDGE_HOST ?? host.spec;
192
+ let child;
193
+ let stopping = false;
194
+ for (const signal of ['SIGINT', 'SIGTERM']) {
195
+ process.on(signal, () => {
196
+ stopping = true;
197
+ child?.kill(signal);
198
+ });
199
+ }
200
+ const crashes = [];
201
+ for (;;) {
202
+ const [command, ...prefix] = npx();
203
+ child = spawn(command, [...prefix, '-y', '--package', spec, '--', host.bin, device, '--yes', ...extra], { stdio: 'inherit' });
204
+ const exit = await new Promise((resolve, reject) => {
205
+ child.on('error', reject);
206
+ child.on('exit', (code, signal) => resolve({ code, signal }));
207
+ });
208
+ if (stopping || exit.code === 0)
209
+ return;
210
+ const now = Date.now();
211
+ crashes.push(now);
212
+ while (crashes[0] < now - CRASH_WINDOW_MS)
213
+ crashes.shift();
214
+ const why = exit.signal ?? `code ${exit.code}`;
215
+ if (crashes.length > MAX_CRASHES) {
216
+ throw new Error(`The desktop host crashed ${crashes.length} times in a minute (last: ${why}), so it wasn't restarted. Fix the error above, then run this command again.`);
217
+ }
218
+ console.log(`\nThe desktop host stopped (${why}). Starting it again…\n`);
219
+ await new Promise((r) => setTimeout(r, RESTART_DELAY_MS));
220
+ }
221
+ }
55
222
  const commands = {
223
+ async live() {
224
+ for (const later of ['ios', 'android', 'all']) {
225
+ if (has(later))
226
+ throw new Error(`--${later} isn't available yet. Run \`live\` for a phone app, or \`live --desktop\`, \`--electron\` or \`--expo\` for a desktop app.`);
227
+ }
228
+ const fromArg = flag('from');
229
+ const source = fromArg ? await sourceProject(fromArg) : null;
230
+ let ref = has('new') || source ? null : await savedProject();
231
+ const requested = requestedTemplate();
232
+ if (source && requested && requested !== source.template) {
233
+ throw new Error(`--from names ${TEMPLATE_KINDS[source.template] ?? `a ${source.template}`} project, so leave out the flag asking for ${TEMPLATE_KINDS[requested] ?? `a ${requested}`} one.`);
234
+ }
235
+ // Without a template flag, this folder's project runs as whatever it was made as.
236
+ const template = source?.template ?? requested ?? ref?.template ?? 'core';
237
+ const desktop = DESKTOP_TEMPLATES.has(template);
238
+ if (ref && requested && (ref.template ?? 'core') !== requested) {
239
+ const current = TEMPLATE_KINDS[ref.template ?? 'core'] ?? `a ${ref.template}`;
240
+ throw new Error(`This folder's project (${CONFIG}) is ${current} project. Add --new to start ${TEMPLATE_KINDS[requested] ?? `a ${requested}`} one, or run this in another folder.`);
241
+ }
242
+ if (ref) {
243
+ console.log(`Opening this folder's project ${ref.id} (${CONFIG})`);
244
+ }
245
+ else {
246
+ ref = await createProject(source?.server ?? flag('server') ?? LIVE_SERVER, flag('token') ?? process.env.NS_EDGE_CREATE_TOKEN, template, source?.id);
247
+ await writeFile(join(root, CONFIG), JSON.stringify(ref, null, 2) + '\n');
248
+ const made = source ? `your copy of ${source.title ? `"${source.title}"` : `project ${source.id}`}` : `${TEMPLATE_KINDS[template] ?? `a ${template}`} project`;
249
+ console.log(`Created ${made}, saved to ${CONFIG} (it holds the project's keys: keep it private and out of git).`);
250
+ if (ref.free) {
251
+ console.log(`It's a free project: ${ref.free.agentTurnsPerDay} hosted agent turn${ref.free.agentTurnsPerDay === 1 ? '' : 's'} a day, deleted after ${ref.free.idleDays} days unused. ` +
252
+ 'For an unlimited agent, add your own API key in the agent panel or connect Claude Code from Connect agent.');
253
+ }
254
+ }
255
+ const ide = `${projectUrl(ref)}/#key=${ref.writeKey}`;
256
+ console.log(`\n IDE ${ide}\n`);
257
+ if (!has('no-open'))
258
+ openInBrowser(ide);
259
+ if (desktop) {
260
+ const first = template === 'electron' ? ' (the first run downloads Electron)' : template === 'expo' ? ' (the first run downloads the Expo Desktop shell)' : '';
261
+ console.log(`Starting the app on this ${COMPUTER}${first}. Its window streams to the IDE's Device pane. Press Ctrl+C to stop.\n`);
262
+ return runDesktopHost(ref);
263
+ }
264
+ const device = `${projectUrl(ref)}#${ref.deviceKey}`;
265
+ console.log(await QRCode.toString(`${ref.pairScheme ?? 'nsedge'}://pair?url=${encodeURIComponent(device)}`, { type: 'terminal', small: true }));
266
+ console.log(`Scan with your phone's camera to open it in ${ref.pairScheme === 'nspreview' ? 'NativeScript Preview' : 'the edge shell'}, then edit in the IDE.`);
267
+ console.log('Run this command again in this folder to reopen the project.');
268
+ },
56
269
  async create() {
57
270
  const server = flag('server') ?? 'http://localhost:5173';
58
- const ref = await createProject(server, flag('token') ?? process.env.NS_EDGE_CREATE_TOKEN);
271
+ const ref = await createProject(server, flag('token') ?? process.env.NS_EDGE_CREATE_TOKEN, requestedTemplate());
59
272
  await writeFile(join(root, CONFIG), JSON.stringify(ref, null, 2) + '\n');
60
273
  console.log(`Created project ${ref.id} (saved to ${CONFIG}; it holds the project keys, keep it out of git)`);
61
274
  await printPairing(ref);
@@ -122,15 +335,35 @@ const commands = {
122
335
  async qr() {
123
336
  await printPairing(await loadRef());
124
337
  },
338
+ async samples() {
339
+ const server = flag('server') ?? LIVE_SERVER;
340
+ const list = await listSamples(server);
341
+ if (!list)
342
+ throw new Error(`Couldn't list the samples on ${server}.`);
343
+ if (!list.length)
344
+ return console.log(`${server} has no named samples yet.`);
345
+ const width = Math.max(...list.map((s) => s.name.length));
346
+ for (const s of list)
347
+ console.log(` ${s.name.padEnd(width)} ${s.title}`);
348
+ console.log(`\nStart from one with: npx @nativescript/cloudflare-cli live --from <name>`);
349
+ },
125
350
  async help() {
126
351
  console.log(`ns-edge <command>
127
352
 
128
- create [--server <url>] [--token <t>]
353
+ live [--ng|--react|--vue|--svelte|--solid|--desktop|--electron|--expo] [--new] [--from <sample>] [--no-open] [--allow-eval]
354
+ create a project (or reopen this folder's), open its IDE, and print a QR code
355
+ for your phone; --ng, --react, --vue, --svelte or --solid picks the framework
356
+ (plain TypeScript with XML views otherwise); --desktop (or --mac, --windows)
357
+ or --electron runs it on this Mac or Windows PC instead, with that OS's own
358
+ controls; --expo runs an Expo Desktop app on this Mac or Windows x64 PC;
359
+ --from starts from a copy of a shared project: a sample's name, link or id
360
+ create [--server <url>] [--token <t>] [--ng|--react|--vue|--svelte|--solid|--template <name>]
129
361
  create an edge project and save .ns-edge.json
130
362
  push upload app/ and server/ in one transaction
131
363
  watch push, then stream every save to the edge
132
364
  pull download the project's files here
133
- qr print the pairing QR code`);
365
+ qr print the pairing QR code
366
+ samples list the samples --from can start from by name`);
134
367
  },
135
368
  };
136
369
  const run = commands[cmd] ?? commands.help;
package/dist/sync.d.ts CHANGED
@@ -5,6 +5,12 @@ export interface ProjectRef {
5
5
  deviceKey: string;
6
6
  /** URL scheme of the app the server pairs with, from its create response. */
7
7
  pairScheme?: string;
8
+ template?: string;
9
+ /** Set on free projects: their daily agent allowance and how long they last unused. */
10
+ free?: {
11
+ agentTurnsPerDay: number;
12
+ idleDays: number;
13
+ };
8
14
  }
9
15
  export interface ApplyResult {
10
16
  changed: string[];
@@ -17,7 +23,8 @@ export interface ApplyResult {
17
23
  /** Project-relative paths that are mirrored to the edge. */
18
24
  export declare const SYNCED: RegExp;
19
25
  export declare function projectUrl(ref: ProjectRef): string;
20
- export declare function createProject(server: string, token?: string): Promise<ProjectRef>;
26
+ /** With `from`, the project starts as a copy of that one, which must be a `template` project. */
27
+ export declare function createProject(server: string, token?: string, template?: string, from?: string): Promise<ProjectRef>;
21
28
  /** Sends a batch as one edge transaction, so devices see one consistent update. */
22
29
  export declare function applyChanges(ref: ProjectRef, changes: {
23
30
  path: string;
package/dist/sync.js CHANGED
@@ -1,19 +1,25 @@
1
1
  import { readFile, readdir, stat } from 'node:fs/promises';
2
2
  import { join, relative, sep } from 'node:path';
3
3
  /** Project-relative paths that are mirrored to the edge. */
4
- export const SYNCED = /^(app|server)\/.+\.(ts|mts|js|mjs|xml|css|json)$/;
4
+ export const SYNCED = /^(app|server)\/.+\.(ts|tsx|mts|js|jsx|mjs|vue|svelte|xml|html|css|json)$/;
5
5
  export function projectUrl(ref) {
6
6
  return `${ref.server.replace(/\/$/, '')}/p/${ref.id}`;
7
7
  }
8
- export async function createProject(server, token) {
9
- const res = await fetch(`${server.replace(/\/$/, '')}/api/projects`, {
8
+ /** With `from`, the project starts as a copy of that one, which must be a `template` project. */
9
+ export async function createProject(server, token, template, from) {
10
+ const query = from ? `?from=${encodeURIComponent(from)}` : template ? `?template=${encodeURIComponent(template)}` : '';
11
+ const res = await fetch(`${server.replace(/\/$/, '')}/api/projects${query}`, {
10
12
  method: 'POST',
11
13
  headers: token ? { authorization: `Bearer ${token}` } : {},
12
14
  });
15
+ if (res.status === 401)
16
+ throw new Error(`${server} creates projects only with a create token: pass --token or set NS_EDGE_CREATE_TOKEN.`);
17
+ if (res.status === 404 && from)
18
+ throw new Error(`There's no project ${from} on ${server} to start from.`);
13
19
  if (!res.ok)
14
- throw new Error(`create failed: ${res.status} ${await res.text()}`);
15
- const { id, writeKey, deviceKey, pair } = (await res.json());
16
- return { server, id, writeKey, deviceKey, pairScheme: pair?.split('://')[0] };
20
+ throw new Error(`Couldn't create a project (${res.status}): ${await res.text()}`);
21
+ const { id, writeKey, deviceKey, pair, free } = (await res.json());
22
+ return { server, id, writeKey, deviceKey, pairScheme: pair?.split('://')[0], template: template ?? 'core', ...(free && { free }) };
17
23
  }
18
24
  /** Sends a batch as one edge transaction, so devices see one consistent update. */
19
25
  export async function applyChanges(ref, changes) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nativescript/cloudflare-cli",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.11",
4
4
  "description": "Mirror a NativeScript project into an ns-edge project from a terminal or a Vite dev server",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",