@almateam/app-sdk 0.8.0 → 0.9.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/cli.js CHANGED
@@ -1,11 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/main.ts
4
- import { resolve } from "path";
4
+ import { existsSync as existsSync2 } from "fs";
5
+ import { join as join5, resolve } from "path";
5
6
  import { parseArgs } from "util";
6
7
 
7
8
  // src/cli/dev.ts
8
- import { watch } from "node:fs";
9
+ import { existsSync, watch } from "node:fs";
10
+ import { join as join3 } from "node:path";
9
11
 
10
12
  // src/cli/project.ts
11
13
  import { readdir, readFile } from "node:fs/promises";
@@ -119,9 +121,288 @@ async function pushVersion(connection, project, appId, signal) {
119
121
  }
120
122
  }
121
123
 
124
+ // src/cli/siteFiles.ts
125
+ import { createHash } from "node:crypto";
126
+ import { createReadStream } from "node:fs";
127
+ import { readdir as readdir2, readFile as readFile2, rename, stat, writeFile } from "node:fs/promises";
128
+ import { request as httpRequest } from "node:http";
129
+ import { request as httpsRequest } from "node:https";
130
+ import { join as join2 } from "node:path";
131
+ import { pipeline } from "node:stream/promises";
132
+ var DEFAULT_SITE_FILES_FOLDER = "_site-files";
133
+ var SITE_FILES_MANIFEST = "site-files.json";
134
+ var SITE_FILE_LIMITS = {
135
+ files: 200,
136
+ fileBytes: 50 * 1024 * 1024,
137
+ totalBytes: 200 * 1024 * 1024
138
+ };
139
+ var SITE_FILE_TYPES = {
140
+ png: "image/png",
141
+ jpg: "image/jpeg",
142
+ jpeg: "image/jpeg",
143
+ gif: "image/gif",
144
+ webp: "image/webp",
145
+ avif: "image/avif",
146
+ ico: "image/x-icon",
147
+ woff2: "font/woff2",
148
+ woff: "font/woff",
149
+ ttf: "font/ttf",
150
+ otf: "font/otf",
151
+ pdf: "application/pdf",
152
+ mp3: "audio/mpeg",
153
+ m4a: "audio/mp4",
154
+ aac: "audio/aac",
155
+ ogg: "audio/ogg",
156
+ oga: "audio/ogg",
157
+ opus: "audio/ogg",
158
+ wav: "audio/wav",
159
+ weba: "audio/webm",
160
+ flac: "audio/flac"
161
+ };
162
+ var SITE_FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
163
+ function isSiteFileName(name) {
164
+ return SITE_FILE_NAME.test(name) && !name.includes("..");
165
+ }
166
+ var MB = 1024 * 1024;
167
+
168
+ class SiteFilesRefusal extends Error {
169
+ createdAppId;
170
+ constructor(message, createdAppId) {
171
+ super(message);
172
+ this.createdAppId = createdAppId;
173
+ }
174
+ }
175
+ async function sha256Of(path) {
176
+ const hash = createHash("sha256");
177
+ await pipeline(createReadStream(path), hash);
178
+ return hash.digest("hex");
179
+ }
180
+ async function readSiteFiles(folder) {
181
+ const entries = await readdir2(folder, { withFileTypes: true }).catch((error) => {
182
+ if (error.code === "ENOENT")
183
+ return null;
184
+ throw error;
185
+ });
186
+ if (!entries)
187
+ return null;
188
+ const files = [];
189
+ let total = 0;
190
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
191
+ if (entry.name.startsWith("."))
192
+ continue;
193
+ if (entry.isDirectory())
194
+ throw new SiteFilesRefusal(`${entry.name}/ is a folder. Site files are flat: put each file directly in ${folder}, named as pages refer to it (/_files/<name>).`);
195
+ if (!entry.isFile())
196
+ continue;
197
+ if (!isSiteFileName(entry.name))
198
+ throw new SiteFilesRefusal(`${entry.name}: a site file's name is letters, digits, dots, dashes and underscores, at most 128, starting with a letter or digit.`);
199
+ const extension = entry.name.split(".").pop()?.toLowerCase() ?? "";
200
+ const mediaType = entry.name.includes(".") ? SITE_FILE_TYPES[extension] : undefined;
201
+ if (!mediaType)
202
+ throw new SiteFilesRefusal(`${entry.name}: a site file is a picture, a font, a PDF or audio (${Object.keys(SITE_FILE_TYPES).join(", ")}). Import an SVG from the source instead.`);
203
+ const path = join2(folder, entry.name);
204
+ const { size } = await stat(path);
205
+ if (size === 0)
206
+ throw new SiteFilesRefusal(`${entry.name} is empty.`);
207
+ if (size > SITE_FILE_LIMITS.fileBytes)
208
+ throw new SiteFilesRefusal(`${entry.name} is ${(size / MB).toFixed(1)} MB; a site file is at most ${SITE_FILE_LIMITS.fileBytes / MB} MB.`);
209
+ total += size;
210
+ files.push({
211
+ name: entry.name,
212
+ path,
213
+ entry: {
214
+ sha256: await sha256Of(path),
215
+ bytes: size,
216
+ media_type: mediaType
217
+ }
218
+ });
219
+ }
220
+ if (files.length > SITE_FILE_LIMITS.files)
221
+ throw new SiteFilesRefusal(`${folder} holds ${files.length} files; a site has at most ${SITE_FILE_LIMITS.files}.`);
222
+ if (total > SITE_FILE_LIMITS.totalBytes)
223
+ throw new SiteFilesRefusal(`${folder} holds ${(total / MB).toFixed(1)} MB; a site's files come to at most ${SITE_FILE_LIMITS.totalBytes / MB} MB.`);
224
+ return files;
225
+ }
226
+ var MEDIA_TYPES = new Set(Object.values(SITE_FILE_TYPES));
227
+ function isEntry(value) {
228
+ if (typeof value !== "object" || value === null)
229
+ return false;
230
+ const entry = value;
231
+ return Object.keys(entry).length === 3 && typeof entry["sha256"] === "string" && /^[0-9a-f]{64}$/.test(entry["sha256"]) && typeof entry["bytes"] === "number" && Number.isInteger(entry["bytes"]) && entry["bytes"] > 0 && entry["bytes"] <= SITE_FILE_LIMITS.fileBytes && typeof entry["media_type"] === "string" && MEDIA_TYPES.has(entry["media_type"]);
232
+ }
233
+ async function readRecorded(appDirectory) {
234
+ const text = await readFile2(join2(appDirectory, SITE_FILES_MANIFEST), "utf8").catch((error) => {
235
+ if (error.code === "ENOENT")
236
+ return null;
237
+ throw error;
238
+ });
239
+ if (text === null)
240
+ return { entries: {}, text };
241
+ let parsed = null;
242
+ try {
243
+ parsed = JSON.parse(text);
244
+ } catch {}
245
+ const entries = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? Object.fromEntries(Object.entries(parsed).filter(([name, entry]) => isSiteFileName(name) && isEntry(entry))) : {};
246
+ return { entries, text };
247
+ }
248
+ var sameEntry = (a, b) => a !== undefined && a.sha256 === b.sha256 && a.bytes === b.bytes && a.media_type === b.media_type;
249
+ async function writeRecorded(appDirectory, onDisk, after) {
250
+ const text = `${JSON.stringify(after, null, 2)}
251
+ `;
252
+ if (text === onDisk)
253
+ return onDisk;
254
+ if (onDisk === null && Object.keys(after).length === 0)
255
+ return null;
256
+ const path = join2(appDirectory, SITE_FILES_MANIFEST);
257
+ const temporary = `${path}.${process.pid}.tmp`;
258
+ await writeFile(temporary, text);
259
+ await rename(temporary, path);
260
+ return text;
261
+ }
262
+ var APP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
263
+ function isAppId(id) {
264
+ return APP_ID.test(id);
265
+ }
266
+ var LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
267
+ function uploadAllowed(uploadUrl, endpoint) {
268
+ if (uploadUrl.protocol === "https:")
269
+ return true;
270
+ const server = new URL(endpoint);
271
+ return uploadUrl.protocol === "http:" && server.protocol === "http:" && LOOPBACK_HOSTS.has(server.hostname);
272
+ }
273
+ function refusalText(name, status, body) {
274
+ const said = typeof body?.error === "string" ? body.error : null;
275
+ if (body?.code === "site.workspace_not_allowed")
276
+ return `This workspace may not publish apps to the web, so its apps keep no site files. A workspace Owner can ask Alma to allow it.`;
277
+ if (body?.code === "workspace_unresolved")
278
+ return "You belong to more than one workspace (or none): name the app's with --org <organization id>.";
279
+ if (status === 503)
280
+ return "This Alma does not serve web sites, so site files cannot be uploaded to it.";
281
+ if (status === 404)
282
+ return "No app with that id is yours to change. Check --app, and that you own or edit the app.";
283
+ if (status === 413 || status === 415 || status === 422)
284
+ return `${name}: ${said ?? `Alma answered ${status}`}`;
285
+ return said ?? `Alma answered ${status} for ${name}`;
286
+ }
287
+ async function askForUpload(connection, appId, file, retried = false) {
288
+ if (!isAppId(appId))
289
+ throw new SiteFilesRefusal(`${appId} is not an app id. The first push prints it.`);
290
+ const request = connection.fetch ?? fetch;
291
+ const response = await request(new URL(`/apps/${appId}/site-files`, connection.endpoint), {
292
+ method: "POST",
293
+ headers: {
294
+ authorization: `Bearer ${await connection.token()}`,
295
+ "content-type": "application/json",
296
+ ...connection.organizationId ? { "x-organization-id": connection.organizationId } : {}
297
+ },
298
+ body: JSON.stringify({ name: file.name, ...file.entry })
299
+ });
300
+ if (response.status === 401) {
301
+ if (retried)
302
+ throw new SiteFilesRefusal("Alma refused the sign-in. Sign in again.");
303
+ await connection.reauthorize();
304
+ return askForUpload(connection, appId, file, true);
305
+ }
306
+ const body = await response.json().catch(() => null);
307
+ if (!response.ok || !body?.data)
308
+ throw new SiteFilesRefusal(refusalText(file.name, response.status, body));
309
+ return body.data;
310
+ }
311
+ function putFile(file, upload, endpoint) {
312
+ let url;
313
+ try {
314
+ url = new URL(upload.url);
315
+ } catch {
316
+ return Promise.reject(new SiteFilesRefusal(`${file.name}: Alma answered no upload address.`));
317
+ }
318
+ if (!uploadAllowed(url, endpoint))
319
+ return Promise.reject(new SiteFilesRefusal(`${file.name}: Alma answered an upload address that is not https, so nothing was sent.`));
320
+ const send = url.protocol === "http:" ? httpRequest : httpsRequest;
321
+ return new Promise((resolve, reject) => {
322
+ const put = send(url, {
323
+ method: "PUT",
324
+ headers: {
325
+ ...upload.headers,
326
+ "content-length": String(file.entry.bytes)
327
+ }
328
+ }, (response) => {
329
+ const chunks = [];
330
+ response.on("data", (chunk) => chunks.push(chunk));
331
+ response.on("end", () => {
332
+ const status = response.statusCode ?? 0;
333
+ if (status >= 200 && status < 300)
334
+ resolve();
335
+ else
336
+ reject(new SiteFilesRefusal(`${file.name}: the file store refused the upload (${status}). ${Buffer.concat(chunks).toString("utf8").slice(0, 300)}`.trim()));
337
+ });
338
+ response.on("error", reject);
339
+ });
340
+ put.on("error", reject);
341
+ createReadStream(file.path).on("error", reject).pipe(put);
342
+ });
343
+ }
344
+ async function uploadEach(connection, appId, files, onUploaded) {
345
+ for (const file of files) {
346
+ const upload = await askForUpload(connection, appId, file);
347
+ await putFile(file, upload, connection.endpoint);
348
+ onUploaded(file);
349
+ }
350
+ }
351
+ async function withSiteFiles(input) {
352
+ const files = await readSiteFiles(input.filesDirectory);
353
+ if (!files)
354
+ return input.push();
355
+ if (input.appId !== null && !isAppId(input.appId))
356
+ throw new SiteFilesRefusal(`${input.appId} is not an app id (--app). The first push prints it.`);
357
+ const { entries: before, text: onDisk } = await readRecorded(input.appDirectory);
358
+ const target = Object.fromEntries(files.map((f) => [f.name, f.entry]));
359
+ const changed = input.appId ? files.filter((f) => !sameEntry(before[f.name], f.entry)) : files;
360
+ input.onPlan?.({
361
+ changed: changed.map((f) => f.name),
362
+ unchanged: files.filter((f) => !changed.includes(f)).map((f) => f.name)
363
+ });
364
+ if (input.appId) {
365
+ const recorded = { ...before };
366
+ try {
367
+ await uploadEach(input.connection, input.appId, changed, (f) => {
368
+ recorded[f.name] = f.entry;
369
+ });
370
+ } catch (error) {
371
+ await writeRecorded(input.appDirectory, onDisk, recorded);
372
+ throw error;
373
+ }
374
+ await writeRecorded(input.appDirectory, onDisk, target);
375
+ return input.push();
376
+ }
377
+ const written = await writeRecorded(input.appDirectory, onDisk, target);
378
+ const pushed = await input.push();
379
+ const sent = new Set;
380
+ try {
381
+ await uploadEach(input.connection, pushed.app_id, changed, (f) => {
382
+ sent.add(f.name);
383
+ });
384
+ } catch (error) {
385
+ await writeRecorded(input.appDirectory, written, Object.fromEntries(Object.entries(target).filter(([name]) => sent.has(name))));
386
+ throw new SiteFilesRefusal(`${error instanceof Error ? error.message : String(error)}
387
+ The app was created (--app ${pushed.app_id}); push again with it to upload the rest.`, pushed.app_id);
388
+ }
389
+ return pushed;
390
+ }
391
+
122
392
  // src/cli/dev.ts
393
+ function pushOnce(input) {
394
+ return withSiteFiles({
395
+ connection: input.connection,
396
+ appDirectory: input.directory,
397
+ filesDirectory: input.filesDirectory,
398
+ appId: input.appId,
399
+ onPlan: (plan) => input.onEvent({ kind: "files", plan }),
400
+ push: async () => pushVersion(input.connection, await readProject(input.directory), input.appId, input.signal)
401
+ });
402
+ }
123
403
  async function runDev(options) {
124
404
  const { directory, connection, onEvent, signal } = options;
405
+ const filesDirectory = options.filesDirectory ?? join3(directory, DEFAULT_SITE_FILES_FOLDER);
125
406
  let appId = options.appId;
126
407
  let pending = true;
127
408
  let pushing = null;
@@ -131,12 +412,21 @@ async function runDev(options) {
131
412
  pending = false;
132
413
  onEvent({ kind: "pushing" });
133
414
  try {
134
- const version = await pushVersion(connection, await readProject(directory), appId, signal);
415
+ const version = await pushOnce({
416
+ directory,
417
+ filesDirectory,
418
+ connection,
419
+ appId,
420
+ signal,
421
+ onEvent
422
+ });
135
423
  appId = version.app_id;
136
424
  onEvent({ kind: "pushed", version });
137
425
  } catch (error) {
138
426
  if (signal.aborted)
139
427
  return;
428
+ if (error instanceof SiteFilesRefusal && error.createdAppId)
429
+ appId = error.createdAppId;
140
430
  onEvent({
141
431
  kind: "failed",
142
432
  message: error instanceof Error ? error.message : String(error)
@@ -161,6 +451,7 @@ async function runDev(options) {
161
451
  if (path && isProjectPath(String(path)))
162
452
  schedule();
163
453
  });
454
+ const filesWatcher = existsSync(filesDirectory) ? watch(filesDirectory, () => schedule()) : null;
164
455
  try {
165
456
  pushing = push().finally(() => {
166
457
  pushing = null;
@@ -172,39 +463,78 @@ async function runDev(options) {
172
463
  });
173
464
  } finally {
174
465
  watcher.close();
466
+ filesWatcher?.close();
175
467
  if (timer)
176
468
  clearTimeout(timer);
177
469
  await pushing?.catch(() => {});
178
470
  }
179
471
  }
180
472
 
473
+ // src/cli/siteFiles.ts
474
+ var DEFAULT_SITE_FILES_FOLDER2 = "_site-files";
475
+ var SITE_FILE_LIMITS2 = {
476
+ files: 200,
477
+ fileBytes: 50 * 1024 * 1024,
478
+ totalBytes: 200 * 1024 * 1024
479
+ };
480
+ var SITE_FILE_TYPES2 = {
481
+ png: "image/png",
482
+ jpg: "image/jpeg",
483
+ jpeg: "image/jpeg",
484
+ gif: "image/gif",
485
+ webp: "image/webp",
486
+ avif: "image/avif",
487
+ ico: "image/x-icon",
488
+ woff2: "font/woff2",
489
+ woff: "font/woff",
490
+ ttf: "font/ttf",
491
+ otf: "font/otf",
492
+ pdf: "application/pdf",
493
+ mp3: "audio/mpeg",
494
+ m4a: "audio/mp4",
495
+ aac: "audio/aac",
496
+ ogg: "audio/ogg",
497
+ oga: "audio/ogg",
498
+ opus: "audio/ogg",
499
+ wav: "audio/wav",
500
+ weba: "audio/webm",
501
+ flac: "audio/flac"
502
+ };
503
+ var MB2 = 1024 * 1024;
504
+ var MEDIA_TYPES2 = new Set(Object.values(SITE_FILE_TYPES2));
505
+ var APP_ID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
506
+ function isAppId2(id) {
507
+ return APP_ID2.test(id);
508
+ }
509
+ var LOOPBACK_HOSTS2 = new Set(["127.0.0.1", "localhost", "[::1]"]);
510
+
181
511
  // src/cli/signIn.ts
182
512
  import { spawn } from "node:child_process";
183
- import { chmod, mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
513
+ import { chmod, mkdir, readFile as readFile3, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
184
514
  import { createServer } from "node:http";
185
515
  import { homedir } from "node:os";
186
- import { dirname, join as join2 } from "node:path";
516
+ import { dirname, join as join4 } from "node:path";
187
517
  import {
188
518
  auth
189
519
  } from "@modelcontextprotocol/sdk/client/auth.js";
190
- var STORE = join2(homedir(), ".config", "alma", "app-cli.json");
520
+ var STORE = join4(homedir(), ".config", "alma", "app-cli.json");
191
521
  var CALLBACK_PORT = 53682;
192
522
  var CALLBACK_TIMEOUT_MS = 5 * 60000;
193
523
  var SCOPE = "openid email profile offline_access";
194
524
  async function load(server) {
195
- const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
525
+ const all = await readFile3(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
196
526
  return all[server] ?? {};
197
527
  }
198
528
  async function save(server, stored) {
199
- const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
529
+ const all = await readFile3(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
200
530
  all[server] = stored;
201
531
  const folder = dirname(STORE);
202
532
  await mkdir(folder, { recursive: true, mode: 448 });
203
533
  await chmod(folder, 448);
204
534
  const temporary = `${STORE}.${process.pid}.tmp`;
205
- await writeFile(temporary, JSON.stringify(all, null, 2), { mode: 384 });
535
+ await writeFile2(temporary, JSON.stringify(all, null, 2), { mode: 384 });
206
536
  await chmod(temporary, 384);
207
- await rename(temporary, STORE);
537
+ await rename2(temporary, STORE);
208
538
  }
209
539
  function openBrowser(url) {
210
540
  const [command, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
@@ -315,10 +645,13 @@ function signedInAuthor(server) {
315
645
  }
316
646
 
317
647
  // src/cli/main.ts
318
- var USAGE = `Usage: alma-app dev [folder] [--app <app id>] [--org <organization id>] [--server <MCP url>]
648
+ var USAGE = `Usage: alma-app dev|push [folder] [--app <app id>] [--org <organization id>]
649
+ [--files <folder>] [--server <MCP url>]
319
650
 
320
- Pushes the app in [folder] (default: here) to Alma as a new draft version, now
321
- and on every save, signed in to Alma in your browser.`;
651
+ Pushes the app in [folder] (default: here) to Alma as a new draft version,
652
+ signed in to Alma in your browser: dev now and on every save, push once.
653
+ A web site's pictures, fonts, PDFs and audio are uploaded from --files
654
+ (default: ${DEFAULT_SITE_FILES_FOLDER2} in the folder) and listed in site-files.json first.`;
322
655
  var { values, positionals } = parseArgs({
323
656
  args: process.argv.slice(2),
324
657
  allowPositionals: true,
@@ -326,6 +659,7 @@ var { values, positionals } = parseArgs({
326
659
  help: { type: "boolean", short: "h" },
327
660
  app: { type: "string" },
328
661
  org: { type: "string" },
662
+ files: { type: "string" },
329
663
  server: { type: "string", default: "https://mcp.alma.team/mcp" }
330
664
  }
331
665
  });
@@ -333,33 +667,68 @@ if (values.help || positionals[0] === "help") {
333
667
  console.info(USAGE);
334
668
  process.exit(0);
335
669
  }
336
- if (positionals[0] !== "dev") {
670
+ var command = positionals[0];
671
+ if (command !== "dev" && command !== "push") {
337
672
  console.error(USAGE);
338
673
  process.exit(1);
339
674
  }
340
675
  var directory = resolve(positionals[1] ?? ".");
676
+ var filesDirectory = values.files ? resolve(values.files) : join5(directory, DEFAULT_SITE_FILES_FOLDER2);
677
+ if (values.app && !isAppId2(values.app)) {
678
+ console.error(`--app ${values.app} is not an app id. The first push without --app prints it.`);
679
+ process.exit(1);
680
+ }
681
+ if (values.files && !existsSync2(filesDirectory)) {
682
+ console.error(`No folder at ${filesDirectory} (--files).`);
683
+ process.exit(1);
684
+ }
341
685
  var endpoint = values.server ?? "https://mcp.alma.team/mcp";
342
686
  var author = signedInAuthor(endpoint);
343
- var controller = new AbortController;
344
- process.on("SIGINT", () => controller.abort());
345
- console.info(`Watching ${directory}. Ctrl-C stops.`);
346
- await runDev({
347
- directory,
348
- appId: values.app ?? null,
349
- connection: {
350
- endpoint,
351
- token: author.token,
352
- reauthorize: author.reauthorize,
353
- ...values.org ? { organizationId: values.org } : {}
354
- },
355
- signal: controller.signal,
356
- onEvent: (event) => {
357
- if (event.kind === "pushing")
358
- console.info("Building a new draft\u2026");
359
- else if (event.kind === "failed")
360
- console.error(event.message);
361
- else
362
- console.info(event.version.new_version ? `Draft updated. Open it: ${event.version.draft_url}` + (values.app ? "" : `
687
+ var connection = {
688
+ endpoint,
689
+ token: author.token,
690
+ reauthorize: author.reauthorize,
691
+ ...values.org ? { organizationId: values.org } : {}
692
+ };
693
+ var report = (event) => {
694
+ if (event.kind === "pushing")
695
+ console.info("Building a new draft\u2026");
696
+ else if (event.kind === "files") {
697
+ if (event.plan.changed.length > 0)
698
+ console.info(`Uploading ${event.plan.changed.length} site file(s)` + (event.plan.unchanged.length > 0 ? ` (${event.plan.unchanged.length} unchanged)` : ""));
699
+ } else if (event.kind === "failed")
700
+ console.error(event.message);
701
+ else
702
+ console.info(event.version.new_version ? `Draft updated. Open it: ${event.version.draft_url}` + (values.app ? "" : `
363
703
  (--app ${event.version.app_id})`) : "No change since the last version.");
704
+ };
705
+ if (command === "push") {
706
+ report({ kind: "pushing" });
707
+ try {
708
+ report({
709
+ kind: "pushed",
710
+ version: await pushOnce({
711
+ directory,
712
+ filesDirectory,
713
+ connection,
714
+ appId: values.app ?? null,
715
+ onEvent: report
716
+ })
717
+ });
718
+ } catch (error) {
719
+ console.error(error instanceof Error ? error.message : String(error));
720
+ process.exit(1);
364
721
  }
365
- });
722
+ } else {
723
+ const controller = new AbortController;
724
+ process.on("SIGINT", () => controller.abort());
725
+ console.info(`Watching ${directory}. Ctrl-C stops.`);
726
+ await runDev({
727
+ directory,
728
+ filesDirectory,
729
+ appId: values.app ?? null,
730
+ connection,
731
+ signal: controller.signal,
732
+ onEvent: report
733
+ });
734
+ }
package/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
+ import { AppCallError, type FieldState } from "./callError";
1
2
  import type * as Api from "./generated/apiTypes";
3
+ import type { EventResult, EventResultTicket, WaitForResultOptions } from "./siteRuntime";
4
+ export { AppCallError, type FieldState } from "./callError";
2
5
  export * from "./navigation";
6
+ export * from "./site";
7
+ export * from "./siteRuntime";
3
8
  export type * from "./generated/apiTypes";
4
9
  /** Which records `listTopics` reads. `schema` is the `schema.id` of a `type`
5
10
  * another app keeps. A field filter is `<field>:<op>:<value>` (op: eq, ne,
@@ -104,26 +109,6 @@ export interface AppRequest {
104
109
  * arrived) answers with what the first attempt did and changes nothing. */
105
110
  idempotencyKey?: string;
106
111
  }
107
- /** A field as it stands: its revision and the values it holds. */
108
- export interface FieldState {
109
- revision: string;
110
- values: {
111
- text: string;
112
- typed: Api.TypedValue | null;
113
- }[];
114
- }
115
- /** A refused call. `message` is the refusal's words, to show as they are.
116
- * A refusal a program can act on also carries its `code`; `field.changed`
117
- * carries the field as it stands in `current`, and
118
- * `app_shared_state.revision_conflict` the shared key. */
119
- export declare class AppCallError extends Error {
120
- readonly code: string | undefined;
121
- readonly current: FieldState | Api.AppSharedStateEntry | undefined;
122
- constructor(message: string, detail?: {
123
- code?: string;
124
- current?: FieldState | Api.AppSharedStateEntry;
125
- });
126
- }
127
112
  /** A field write refused because the field changed after the app read it.
128
113
  * Nothing was written; `current` is what the field holds now. */
129
114
  export type FieldChangedError = AppCallError & {
@@ -273,18 +258,23 @@ export type SharedStateTold = {
273
258
  missed: true;
274
259
  };
275
260
  /** What a host answers a shared-state watch with: whether it will tell
276
- * changes, and how to stop hearing them. */
261
+ * changes, whether it is still joining (it tells `missed` once it is in,
262
+ * and changes from then on), and how to stop hearing them. */
277
263
  export interface SharedStateWatch {
278
264
  watching: boolean;
265
+ joining?: boolean;
279
266
  stop(): void;
280
267
  }
281
268
  /** A quick message as a host tells it: its event, its payload, and whether
282
- * this open copy of the app sent it. */
283
- export interface BroadcastTold {
269
+ * this open copy of the app sent it; or that messages may have passed
270
+ * unheard. */
271
+ export type BroadcastTold = {
284
272
  event: string;
285
273
  payload: unknown;
286
274
  self: boolean;
287
- }
275
+ } | {
276
+ missed: true;
277
+ };
288
278
  /** What a host answers a broadcast watch with: whether it will tell
289
279
  * messages, and how to stop hearing them. */
290
280
  export interface BroadcastWatch {
@@ -320,6 +310,10 @@ export interface AppTransport {
320
310
  /** Be told each quick message sent to everyone with the app open. A
321
311
  * transport without it tells nothing. */
322
312
  watchBroadcasts?(told: (message: BroadcastTold) => void): Promise<BroadcastWatch>;
313
+ /** What a raised event's workflow has answered so far, by the `token` a
314
+ * published site's raise returned. A transport without it has no
315
+ * results to read. */
316
+ result?(token: string): Promise<EventResult>;
323
317
  }
324
318
  export declare function createAppSdk(transport: AppTransport): {
325
319
  call: <T>(operationId: AppOperationId, request?: AppRequest) => Promise<T>;
@@ -568,8 +562,23 @@ export declare function createAppSdk(transport: AppTransport): {
568
562
  * with `payload` as data it does not trust. The answer is the same
569
563
  * whether or not a workflow listens. An event the shared version does
570
564
  * not declare rejects with `event.undeclared`; past the app's events for
571
- * the hour, with `event.rate_limited` and when to try again. */
572
- raiseEvent: (event: string, payload?: Record<string, unknown>, options?: ChangeOptions) => Promise<Api.AppEventRaised>;
565
+ * the hour, with `event.rate_limited` and when to try again. On a
566
+ * published site the answer also carries `result` when the event's
567
+ * workflow answers the visitor, and a refusal for now is a
568
+ * `SiteRefusalError` (`visitor.rate_limited`, `site.paused`). */
569
+ raiseEvent: (event: string, payload?: Record<string, unknown>, options?: ChangeOptions) => Promise<Api.AppEventRaised & {
570
+ result?: EventResultTicket;
571
+ }>;
572
+ /** On a published site, what the workflow a raise started has answered
573
+ * so far, by the `result.token` the raise returned (or the token a
574
+ * result page reads from its address with `readResultToken`). Rejects
575
+ * with `result.unavailable` where the transport has no results. */
576
+ result: (token: string) => Promise<EventResult>;
577
+ /** Reads a result until it is ready, after 1, 2, 4 and then every 8
578
+ * seconds, and resolves with what the workflow answered. Rejects with
579
+ * `result.timeout` once `timeoutMs` (default two minutes) passes with
580
+ * the result still pending. */
581
+ waitForResult: (token: string, options?: WaitForResultOptions) => Promise<unknown>;
573
582
  /** This app's own state for its viewer: a small store for what only
574
583
  * this person's screen of this app needs between visits, such as a
575
584
  * filter, a collapsed column or a half-written draft. It needs no scope
@@ -616,9 +625,10 @@ export declare function createAppSdk(transport: AppTransport): {
616
625
  * is written; where the workspace keeps values off the push, the SDK
617
626
  * reads the key first. Every key is read again every five minutes, and
618
627
  * whenever the host may have missed a change. Where the host tells
619
- * nothing (a host from before it, or a channel the server refuses), the
620
- * SDK polls on `intervalMs` (default 5 seconds, doubling to a minute
621
- * while nothing changes). Returns the unsubscribe.
628
+ * nothing (a host from before it, or a channel the server refuses), and
629
+ * while the host is still joining, the SDK polls on `intervalMs`
630
+ * (default 5 seconds, doubling to a minute while nothing changes).
631
+ * Returns the unsubscribe.
622
632
  */
623
633
  watch: (listener: (entry: Api.AppSharedStateEntry) => void, options?: {
624
634
  intervalMs?: number;
@@ -640,20 +650,24 @@ export declare function createAppSdk(transport: AppTransport): {
640
650
  * cursor, a ping, a reaction. It reaches each open copy's `onBroadcast`
641
651
  * listeners for `event` within about a second and is never stored, so a
642
652
  * copy that opens later never hears it; keep what it needs in `shared`.
643
- * Needs `shared_state:write`. A payload over 8 KiB of JSON, or more than
644
- * 10 messages a second after a burst of 20, rejects with an
645
- * `AppCallError` whose `code` says which.
653
+ * Needs `shared_state:write`. A payload over 8 KiB of JSON, more than
654
+ * 10 messages a second from one person after a burst of 20, or more than
655
+ * 30 a second from everyone using the installation together after a
656
+ * burst of 60, rejects with an `AppCallError` whose `code` says which.
646
657
  */
647
658
  broadcast: (event: string, payload?: unknown) => Promise<void>;
648
659
  /**
649
660
  * Calls `listener` with the payload of each quick message sent for
650
661
  * `event` while the app is open. Messages this copy sent are left out
651
- * unless `self` is set. Where the host tells nothing (a host from before
652
- * it, an app without `shared_state:write`, or a channel the server
653
- * refuses), `listener` is never called. Returns the unsubscribe.
662
+ * unless `self` is set. `missed` is called when messages may have passed
663
+ * unheard: the host's channel joined late, or was lost and is back. Where
664
+ * the host tells nothing (a host from before it, an app without
665
+ * `shared_state:write`, or a channel the server refuses), neither is
666
+ * ever called. Returns the unsubscribe.
654
667
  */
655
668
  onBroadcast: (event: string, listener: (payload: unknown) => void, options?: {
656
669
  self?: boolean;
670
+ missed?: () => void;
657
671
  }) => (() => void);
658
672
  /** What changed in a record since its viewer last looked at it in this
659
673
  * app. `mark` notes a record as they see it now (from `getTopicRecord`