@almateam/app-sdk 0.8.0 → 0.10.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,16 +1,254 @@
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 { mkdir as mkdir2, rm, writeFile as writeFile3 } from "fs/promises";
6
+ import { dirname as dirname2, join as join6, resolve } from "path";
5
7
  import { parseArgs } from "util";
6
8
 
9
+ // src/cli/convert.ts
10
+ class ConversionRefusal extends Error {
11
+ constructor(message) {
12
+ super(message);
13
+ this.name = "ConversionRefusal";
14
+ }
15
+ }
16
+ var SCRIPT_EXTENSIONS = ["ts", "tsx", "js", "jsx", "mjs"];
17
+ function freeModule(source, stems) {
18
+ const stem = stems.find((candidate) => SCRIPT_EXTENSIONS.every((extension) => !(`${candidate}.${extension}` in source)));
19
+ if (stem === undefined)
20
+ throw new ConversionRefusal(`The app already has ${stems.join(", ")}; rename one before converting.`);
21
+ return `${stem}.tsx`;
22
+ }
23
+ function siteEntryOf(manifest) {
24
+ const site = manifest["site"];
25
+ if (typeof site !== "object" || site === null)
26
+ return null;
27
+ const entry = site["entry"];
28
+ return typeof entry === "string" ? entry : null;
29
+ }
30
+ var ATTRIBUTE = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
31
+ function attributesOf(text) {
32
+ const attributes = {};
33
+ for (const [, name, double, single, bare] of text.matchAll(ATTRIBUTE))
34
+ if (name)
35
+ attributes[name.toLowerCase()] = double ?? single ?? bare ?? "";
36
+ return attributes;
37
+ }
38
+ function tagAttributes(html, tag) {
39
+ const found = new RegExp(`<${tag}\\b([^>]*)>`, "i").exec(html);
40
+ return found ? attributesOf(found[1] ?? "") : {};
41
+ }
42
+ function between(html, tag) {
43
+ const found = new RegExp(`<${tag}\\b[^>]*>([\\s\\S]*?)</${tag}\\s*>`, "i").exec(html);
44
+ return found ? found[1] ?? "" : null;
45
+ }
46
+ var SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
47
+ function sourcePath(reference) {
48
+ if (/^[a-z][a-z0-9+.-]*:|^\/\//i.test(reference))
49
+ return null;
50
+ const path = reference.replace(/^\.?\//, "");
51
+ if (path === "" || path.split("/").some((part) => part === ".."))
52
+ return null;
53
+ return path;
54
+ }
55
+ function scriptSource(path, source) {
56
+ if (path === null)
57
+ return null;
58
+ if (path in source)
59
+ return path;
60
+ const stem = path.replace(/\.(?:js|mjs)$/, "");
61
+ if (stem === path)
62
+ return null;
63
+ return [`${stem}.ts`, `${stem}.tsx`].find((each) => (each in source)) ?? null;
64
+ }
65
+ function importFromSrc(path) {
66
+ const parts = path.split("/");
67
+ const relative = parts[0] === "src" ? `./${parts.slice(1).join("/")}` : `../${path}`;
68
+ return relative.replace(/\.(tsx|ts|jsx|js|mjs)$/, "");
69
+ }
70
+ function readDocument(html, source) {
71
+ const problems = [];
72
+ const scripts = [];
73
+ const sheets = [];
74
+ const head = between(html, "head") ?? "";
75
+ const bodyText = between(html, "body");
76
+ for (const [, attributeText = "", inline = ""] of html.matchAll(SCRIPT)) {
77
+ const attributes = attributesOf(attributeText);
78
+ const src = attributes["src"];
79
+ if (src === undefined) {
80
+ if (inline.trim() !== "")
81
+ problems.push("index.html runs an inline script. Move it into a module the page loads.");
82
+ continue;
83
+ }
84
+ const path = scriptSource(sourcePath(src), source);
85
+ if (path === null)
86
+ problems.push(`index.html loads ${src}, which is not a file of the app's source.`);
87
+ else if (attributes["type"] !== "module")
88
+ problems.push(`index.html loads ${src} as a classic script; only a module script carries over.`);
89
+ else
90
+ scripts.push(path);
91
+ }
92
+ const headRest = head.replace(/<title\b[^>]*>[\s\S]*?<\/title\s*>/gi, "").replace(SCRIPT, "").replace(/<meta\b[^>]*>/gi, "").replace(/<!--[\s\S]*?-->/g, "");
93
+ for (const [element, attributeText = ""] of headRest.matchAll(/<link\b([^>]*)>/gi)) {
94
+ const attributes = attributesOf(attributeText);
95
+ const path = attributes["href"] === undefined ? null : sourcePath(attributes["href"]);
96
+ if (/\bstylesheet\b/i.test(attributes["rel"] ?? "") && path !== null && path in source)
97
+ sheets.push(path);
98
+ else
99
+ problems.push(`index.html's head has ${element.trim()}, which has no place in an app's screens.`);
100
+ }
101
+ const leftover = headRest.replace(/<link\b[^>]*>/gi, "").trim();
102
+ if (leftover !== "")
103
+ problems.push(`index.html's head has ${leftover.slice(0, 60)}, which has no place in an app's screens. Move styles into a stylesheet the page imports.`);
104
+ if (scripts.length === 0)
105
+ problems.push('index.html loads no module script (<script type="module" src="/src/main.tsx">).');
106
+ const markup = (bodyText ?? html.replace(/<!doctype[^>]*>/i, "")).replace(SCRIPT, "").replace(/<!--[\s\S]*?-->/g, "").trim();
107
+ return {
108
+ problems,
109
+ scripts,
110
+ sheets,
111
+ markup,
112
+ htmlAttributes: tagAttributes(html, "html"),
113
+ bodyAttributes: tagAttributes(html, "body")
114
+ };
115
+ }
116
+ function pageModule(read) {
117
+ const htmlAttributes = { ...read.htmlAttributes };
118
+ delete htmlAttributes["lang"];
119
+ return `/* The app's one page, as its index.html drew it: the page's body, then
120
+ its scripts, run once, after the body is in the document. */
121
+ import { useLayoutEffect, useRef } from "react";
122
+
123
+ const BODY = ${JSON.stringify(read.markup)};
124
+ const HTML_ATTRIBUTES: Record<string, string> = ${JSON.stringify(htmlAttributes)};
125
+ const BODY_ATTRIBUTES: Record<string, string> = ${JSON.stringify(read.bodyAttributes)};
126
+
127
+ // One body for the frame's life, so the page's own scripts, which run once,
128
+ // keep the elements they drew whichever screen shows it.
129
+ let page: HTMLDivElement | null = null;
130
+
131
+ export default function SinglePage() {
132
+ const holder = useRef<HTMLDivElement>(null);
133
+ useLayoutEffect(() => {
134
+ if (page) {
135
+ holder.current?.append(page);
136
+ return;
137
+ }
138
+ page = document.createElement("div");
139
+ page.style.display = "contents";
140
+ page.innerHTML = BODY;
141
+ holder.current?.append(page);
142
+ for (const [name, value] of Object.entries(HTML_ATTRIBUTES))
143
+ document.documentElement.setAttribute(name, value);
144
+ for (const [name, value] of Object.entries(BODY_ATTRIBUTES))
145
+ document.body.setAttribute(name, value);
146
+ ${read.scripts.map((path) => ` void import(${JSON.stringify(importFromSrc(path))});`).join(`
147
+ `)}
148
+ }, []);
149
+ return <div ref={holder} style={{ display: "contents" }} />;
150
+ }
151
+ `;
152
+ }
153
+ function appModule(read, siteEntry, pagePath) {
154
+ const sheets = read.sheets.map((path) => `import ${JSON.stringify(importFromSrc(path))};`);
155
+ const pageImport = `() => import(${JSON.stringify(importFromSrc(pagePath))})`;
156
+ const page = `{ path: "/", audience: "members", component: ${pageImport} }`;
157
+ const lines = [
158
+ "// Alma's look, which every app stood on before it chose for itself.",
159
+ 'import "@alma/app-ui/base.css";',
160
+ ...sheets,
161
+ 'import { defineApp } from "@alma/app-sdk";'
162
+ ];
163
+ if (siteEntry === null)
164
+ return [
165
+ ...lines,
166
+ "",
167
+ "export default defineApp({",
168
+ ` routes: [${page}],`,
169
+ ` notFound: { component: ${pageImport} },`,
170
+ "});",
171
+ ""
172
+ ].join(`
173
+ `);
174
+ return [
175
+ ...lines,
176
+ `import site from ${JSON.stringify(importFromSrc(siteEntry))};`,
177
+ "",
178
+ "export default defineApp({",
179
+ " ...site,",
180
+ " routes: [",
181
+ ` ${page},`,
182
+ ' ...site.routes.map((route) => ({ ...route, audience: route.audience ?? ("public" as const) })),',
183
+ " ],",
184
+ "});",
185
+ ""
186
+ ].join(`
187
+ `);
188
+ }
189
+ var RENAMES = [
190
+ [/(["'])@alma\/app-ui\/site\/render\1/g, "$1@alma/app-ui/render$1"],
191
+ [/(["'])@alma\/app-ui\/site\1/g, "$1@alma/app-ui$1"],
192
+ [/\bdefineSite\b/g, "defineApp"],
193
+ [/\bdefinePage\b/g, "defineRoute"],
194
+ [/\bstartSite\b/g, "startApp"],
195
+ [/\buseSite\b/g, "useApp"],
196
+ [/\bprerenderSite\b/g, "prerenderApp"],
197
+ [/\bsiteDefinitionProblems\b/g, "appDefinitionProblems"],
198
+ [/\bSiteDefinition\b/g, "AppDefinition"],
199
+ [/\bSitePage\b/g, "AppRoute"],
200
+ [/\bSiteLayout\b/g, "AppLayout"],
201
+ [/\bSiteMeta\b/g, "AppMeta"],
202
+ [/\bSiteParams\b/g, "RouteParams"],
203
+ [/\bPageMetaContext\b/g, "RouteMetaContext"],
204
+ [/\bPageMeta\b/g, "RouteMeta"],
205
+ [/\bPageProps\b/g, "RouteProps"],
206
+ [/\bPageComponent\b/g, "RouteComponent"],
207
+ [/\bSiteInfo\b/g, "AppInfo"],
208
+ [/\bNOT_FOUND_PAGE_ID\b/g, "NOT_FOUND_ROUTE_ID"]
209
+ ];
210
+ var SCRIPT_FILE = /\.(?:tsx|ts|jsx|js|mjs)$/;
211
+ function convertSinglePageApp(app) {
212
+ const html = app.source["index.html"];
213
+ if (html === undefined)
214
+ throw new ConversionRefusal("The app has no index.html, so it is not in the single-page shape.");
215
+ const entry = freeModule(app.source, ["src/app", "src/screens"]);
216
+ const pagePath = freeModule(app.source, ["src/singlePage", "src/onePage"]);
217
+ const read = readDocument(html, app.source);
218
+ if (read.problems.length > 0)
219
+ throw new ConversionRefusal(read.problems.join(`
220
+ `));
221
+ const siteEntry = siteEntryOf(app.manifest);
222
+ if (siteEntry !== null && !(siteEntry in app.source))
223
+ throw new ConversionRefusal(`The manifest's site.entry is ${siteEntry}, which is not in the source.`);
224
+ const source = {};
225
+ for (const [path, text] of Object.entries(app.source)) {
226
+ if (path === "index.html")
227
+ continue;
228
+ let renamed = text;
229
+ if (SCRIPT_FILE.test(path))
230
+ for (const [pattern, name] of RENAMES)
231
+ renamed = renamed.replace(pattern, name);
232
+ if (path === siteEntry)
233
+ renamed = renamed.replace(/\bpages(\s*:)/, "routes$1");
234
+ source[path] = renamed;
235
+ }
236
+ source[entry] = appModule(read, siteEntry, pagePath);
237
+ source[pagePath] = pageModule(read);
238
+ const manifest = { ...app.manifest };
239
+ delete manifest["entry"];
240
+ delete manifest["site"];
241
+ return { manifest: { ...manifest, screens: { entry } }, source };
242
+ }
243
+
7
244
  // src/cli/dev.ts
8
- import { watch } from "node:fs";
245
+ import { existsSync, watch } from "node:fs";
246
+ import { join as join3 } from "node:path";
9
247
 
10
248
  // src/cli/project.ts
11
249
  import { readdir, readFile } from "node:fs/promises";
12
250
  import { join, relative, sep } from "node:path";
13
- var SOURCE_FILE = /\.(?:tsx|ts|jsx|js|mjs|css|html|svg|json)$/;
251
+ var SOURCE_FILE = /\.(?:tsx|ts|jsx|js|mjs|css|html|svg|json|md|txt)$/;
14
252
  var LOCKFILES = new Set([
15
253
  "package-lock.json",
16
254
  "npm-shrinkwrap.json",
@@ -26,7 +264,7 @@ function isProjectPath(path) {
26
264
  }
27
265
  async function readProject(directory) {
28
266
  const manifestText = await readFile(join(directory, "manifest.json"), "utf8").catch(() => {
29
- throw new Error(`No manifest.json in ${directory}. An app's folder holds its manifest beside index.html.`);
267
+ throw new Error(`No manifest.json in ${directory}. An app's folder holds its manifest beside its source.`);
30
268
  });
31
269
  const manifest = JSON.parse(manifestText);
32
270
  if (typeof manifest !== "object" || manifest === null)
@@ -119,9 +357,288 @@ async function pushVersion(connection, project, appId, signal) {
119
357
  }
120
358
  }
121
359
 
360
+ // src/cli/siteFiles.ts
361
+ import { createHash } from "node:crypto";
362
+ import { createReadStream } from "node:fs";
363
+ import { readdir as readdir2, readFile as readFile2, rename, stat, writeFile } from "node:fs/promises";
364
+ import { request as httpRequest } from "node:http";
365
+ import { request as httpsRequest } from "node:https";
366
+ import { join as join2 } from "node:path";
367
+ import { pipeline } from "node:stream/promises";
368
+ var DEFAULT_SITE_FILES_FOLDER = "_site-files";
369
+ var SITE_FILES_MANIFEST = "site-files.json";
370
+ var SITE_FILE_LIMITS = {
371
+ files: 200,
372
+ fileBytes: 50 * 1024 * 1024,
373
+ totalBytes: 200 * 1024 * 1024
374
+ };
375
+ var SITE_FILE_TYPES = {
376
+ png: "image/png",
377
+ jpg: "image/jpeg",
378
+ jpeg: "image/jpeg",
379
+ gif: "image/gif",
380
+ webp: "image/webp",
381
+ avif: "image/avif",
382
+ ico: "image/x-icon",
383
+ woff2: "font/woff2",
384
+ woff: "font/woff",
385
+ ttf: "font/ttf",
386
+ otf: "font/otf",
387
+ pdf: "application/pdf",
388
+ mp3: "audio/mpeg",
389
+ m4a: "audio/mp4",
390
+ aac: "audio/aac",
391
+ ogg: "audio/ogg",
392
+ oga: "audio/ogg",
393
+ opus: "audio/ogg",
394
+ wav: "audio/wav",
395
+ weba: "audio/webm",
396
+ flac: "audio/flac"
397
+ };
398
+ var SITE_FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
399
+ function isSiteFileName(name) {
400
+ return SITE_FILE_NAME.test(name) && !name.includes("..");
401
+ }
402
+ var MB = 1024 * 1024;
403
+
404
+ class SiteFilesRefusal extends Error {
405
+ createdAppId;
406
+ constructor(message, createdAppId) {
407
+ super(message);
408
+ this.createdAppId = createdAppId;
409
+ }
410
+ }
411
+ async function sha256Of(path) {
412
+ const hash = createHash("sha256");
413
+ await pipeline(createReadStream(path), hash);
414
+ return hash.digest("hex");
415
+ }
416
+ async function readSiteFiles(folder) {
417
+ const entries = await readdir2(folder, { withFileTypes: true }).catch((error) => {
418
+ if (error.code === "ENOENT")
419
+ return null;
420
+ throw error;
421
+ });
422
+ if (!entries)
423
+ return null;
424
+ const files = [];
425
+ let total = 0;
426
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
427
+ if (entry.name.startsWith("."))
428
+ continue;
429
+ if (entry.isDirectory())
430
+ 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>).`);
431
+ if (!entry.isFile())
432
+ continue;
433
+ if (!isSiteFileName(entry.name))
434
+ 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.`);
435
+ const extension = entry.name.split(".").pop()?.toLowerCase() ?? "";
436
+ const mediaType = entry.name.includes(".") ? SITE_FILE_TYPES[extension] : undefined;
437
+ if (!mediaType)
438
+ 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.`);
439
+ const path = join2(folder, entry.name);
440
+ const { size } = await stat(path);
441
+ if (size === 0)
442
+ throw new SiteFilesRefusal(`${entry.name} is empty.`);
443
+ if (size > SITE_FILE_LIMITS.fileBytes)
444
+ throw new SiteFilesRefusal(`${entry.name} is ${(size / MB).toFixed(1)} MB; a site file is at most ${SITE_FILE_LIMITS.fileBytes / MB} MB.`);
445
+ total += size;
446
+ files.push({
447
+ name: entry.name,
448
+ path,
449
+ entry: {
450
+ sha256: await sha256Of(path),
451
+ bytes: size,
452
+ media_type: mediaType
453
+ }
454
+ });
455
+ }
456
+ if (files.length > SITE_FILE_LIMITS.files)
457
+ throw new SiteFilesRefusal(`${folder} holds ${files.length} files; a site has at most ${SITE_FILE_LIMITS.files}.`);
458
+ if (total > SITE_FILE_LIMITS.totalBytes)
459
+ throw new SiteFilesRefusal(`${folder} holds ${(total / MB).toFixed(1)} MB; a site's files come to at most ${SITE_FILE_LIMITS.totalBytes / MB} MB.`);
460
+ return files;
461
+ }
462
+ var MEDIA_TYPES = new Set(Object.values(SITE_FILE_TYPES));
463
+ function isEntry(value) {
464
+ if (typeof value !== "object" || value === null)
465
+ return false;
466
+ const entry = value;
467
+ 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"]);
468
+ }
469
+ async function readRecorded(appDirectory) {
470
+ const text = await readFile2(join2(appDirectory, SITE_FILES_MANIFEST), "utf8").catch((error) => {
471
+ if (error.code === "ENOENT")
472
+ return null;
473
+ throw error;
474
+ });
475
+ if (text === null)
476
+ return { entries: {}, text };
477
+ let parsed = null;
478
+ try {
479
+ parsed = JSON.parse(text);
480
+ } catch {}
481
+ const entries = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? Object.fromEntries(Object.entries(parsed).filter(([name, entry]) => isSiteFileName(name) && isEntry(entry))) : {};
482
+ return { entries, text };
483
+ }
484
+ var sameEntry = (a, b) => a !== undefined && a.sha256 === b.sha256 && a.bytes === b.bytes && a.media_type === b.media_type;
485
+ async function writeRecorded(appDirectory, onDisk, after) {
486
+ const text = `${JSON.stringify(after, null, 2)}
487
+ `;
488
+ if (text === onDisk)
489
+ return onDisk;
490
+ if (onDisk === null && Object.keys(after).length === 0)
491
+ return null;
492
+ const path = join2(appDirectory, SITE_FILES_MANIFEST);
493
+ const temporary = `${path}.${process.pid}.tmp`;
494
+ await writeFile(temporary, text);
495
+ await rename(temporary, path);
496
+ return text;
497
+ }
498
+ var APP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
499
+ function isAppId(id) {
500
+ return APP_ID.test(id);
501
+ }
502
+ var LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]"]);
503
+ function uploadAllowed(uploadUrl, endpoint) {
504
+ if (uploadUrl.protocol === "https:")
505
+ return true;
506
+ const server = new URL(endpoint);
507
+ return uploadUrl.protocol === "http:" && server.protocol === "http:" && LOOPBACK_HOSTS.has(server.hostname);
508
+ }
509
+ function refusalText(name, status, body) {
510
+ const said = typeof body?.error === "string" ? body.error : null;
511
+ if (body?.code === "site.workspace_not_allowed")
512
+ 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.`;
513
+ if (body?.code === "workspace_unresolved")
514
+ return "You belong to more than one workspace (or none): name the app's with --org <organization id>.";
515
+ if (status === 503)
516
+ return "This Alma does not serve web sites, so site files cannot be uploaded to it.";
517
+ if (status === 404)
518
+ return "No app with that id is yours to change. Check --app, and that you own or edit the app.";
519
+ if (status === 413 || status === 415 || status === 422)
520
+ return `${name}: ${said ?? `Alma answered ${status}`}`;
521
+ return said ?? `Alma answered ${status} for ${name}`;
522
+ }
523
+ async function askForUpload(connection, appId, file, retried = false) {
524
+ if (!isAppId(appId))
525
+ throw new SiteFilesRefusal(`${appId} is not an app id. The first push prints it.`);
526
+ const request = connection.fetch ?? fetch;
527
+ const response = await request(new URL(`/apps/${appId}/site-files`, connection.endpoint), {
528
+ method: "POST",
529
+ headers: {
530
+ authorization: `Bearer ${await connection.token()}`,
531
+ "content-type": "application/json",
532
+ ...connection.organizationId ? { "x-organization-id": connection.organizationId } : {}
533
+ },
534
+ body: JSON.stringify({ name: file.name, ...file.entry })
535
+ });
536
+ if (response.status === 401) {
537
+ if (retried)
538
+ throw new SiteFilesRefusal("Alma refused the sign-in. Sign in again.");
539
+ await connection.reauthorize();
540
+ return askForUpload(connection, appId, file, true);
541
+ }
542
+ const body = await response.json().catch(() => null);
543
+ if (!response.ok || !body?.data)
544
+ throw new SiteFilesRefusal(refusalText(file.name, response.status, body));
545
+ return body.data;
546
+ }
547
+ function putFile(file, upload, endpoint) {
548
+ let url;
549
+ try {
550
+ url = new URL(upload.url);
551
+ } catch {
552
+ return Promise.reject(new SiteFilesRefusal(`${file.name}: Alma answered no upload address.`));
553
+ }
554
+ if (!uploadAllowed(url, endpoint))
555
+ return Promise.reject(new SiteFilesRefusal(`${file.name}: Alma answered an upload address that is not https, so nothing was sent.`));
556
+ const send = url.protocol === "http:" ? httpRequest : httpsRequest;
557
+ return new Promise((resolve, reject) => {
558
+ const put = send(url, {
559
+ method: "PUT",
560
+ headers: {
561
+ ...upload.headers,
562
+ "content-length": String(file.entry.bytes)
563
+ }
564
+ }, (response) => {
565
+ const chunks = [];
566
+ response.on("data", (chunk) => chunks.push(chunk));
567
+ response.on("end", () => {
568
+ const status = response.statusCode ?? 0;
569
+ if (status >= 200 && status < 300)
570
+ resolve();
571
+ else
572
+ reject(new SiteFilesRefusal(`${file.name}: the file store refused the upload (${status}). ${Buffer.concat(chunks).toString("utf8").slice(0, 300)}`.trim()));
573
+ });
574
+ response.on("error", reject);
575
+ });
576
+ put.on("error", reject);
577
+ createReadStream(file.path).on("error", reject).pipe(put);
578
+ });
579
+ }
580
+ async function uploadEach(connection, appId, files, onUploaded) {
581
+ for (const file of files) {
582
+ const upload = await askForUpload(connection, appId, file);
583
+ await putFile(file, upload, connection.endpoint);
584
+ onUploaded(file);
585
+ }
586
+ }
587
+ async function withSiteFiles(input) {
588
+ const files = await readSiteFiles(input.filesDirectory);
589
+ if (!files)
590
+ return input.push();
591
+ if (input.appId !== null && !isAppId(input.appId))
592
+ throw new SiteFilesRefusal(`${input.appId} is not an app id (--app). The first push prints it.`);
593
+ const { entries: before, text: onDisk } = await readRecorded(input.appDirectory);
594
+ const target = Object.fromEntries(files.map((f) => [f.name, f.entry]));
595
+ const changed = input.appId ? files.filter((f) => !sameEntry(before[f.name], f.entry)) : files;
596
+ input.onPlan?.({
597
+ changed: changed.map((f) => f.name),
598
+ unchanged: files.filter((f) => !changed.includes(f)).map((f) => f.name)
599
+ });
600
+ if (input.appId) {
601
+ const recorded = { ...before };
602
+ try {
603
+ await uploadEach(input.connection, input.appId, changed, (f) => {
604
+ recorded[f.name] = f.entry;
605
+ });
606
+ } catch (error) {
607
+ await writeRecorded(input.appDirectory, onDisk, recorded);
608
+ throw error;
609
+ }
610
+ await writeRecorded(input.appDirectory, onDisk, target);
611
+ return input.push();
612
+ }
613
+ const written = await writeRecorded(input.appDirectory, onDisk, target);
614
+ const pushed = await input.push();
615
+ const sent = new Set;
616
+ try {
617
+ await uploadEach(input.connection, pushed.app_id, changed, (f) => {
618
+ sent.add(f.name);
619
+ });
620
+ } catch (error) {
621
+ await writeRecorded(input.appDirectory, written, Object.fromEntries(Object.entries(target).filter(([name]) => sent.has(name))));
622
+ throw new SiteFilesRefusal(`${error instanceof Error ? error.message : String(error)}
623
+ The app was created (--app ${pushed.app_id}); push again with it to upload the rest.`, pushed.app_id);
624
+ }
625
+ return pushed;
626
+ }
627
+
122
628
  // src/cli/dev.ts
629
+ function pushOnce(input) {
630
+ return withSiteFiles({
631
+ connection: input.connection,
632
+ appDirectory: input.directory,
633
+ filesDirectory: input.filesDirectory,
634
+ appId: input.appId,
635
+ onPlan: (plan) => input.onEvent({ kind: "files", plan }),
636
+ push: async () => pushVersion(input.connection, await readProject(input.directory), input.appId, input.signal)
637
+ });
638
+ }
123
639
  async function runDev(options) {
124
640
  const { directory, connection, onEvent, signal } = options;
641
+ const filesDirectory = options.filesDirectory ?? join3(directory, DEFAULT_SITE_FILES_FOLDER);
125
642
  let appId = options.appId;
126
643
  let pending = true;
127
644
  let pushing = null;
@@ -131,12 +648,21 @@ async function runDev(options) {
131
648
  pending = false;
132
649
  onEvent({ kind: "pushing" });
133
650
  try {
134
- const version = await pushVersion(connection, await readProject(directory), appId, signal);
651
+ const version = await pushOnce({
652
+ directory,
653
+ filesDirectory,
654
+ connection,
655
+ appId,
656
+ signal,
657
+ onEvent
658
+ });
135
659
  appId = version.app_id;
136
660
  onEvent({ kind: "pushed", version });
137
661
  } catch (error) {
138
662
  if (signal.aborted)
139
663
  return;
664
+ if (error instanceof SiteFilesRefusal && error.createdAppId)
665
+ appId = error.createdAppId;
140
666
  onEvent({
141
667
  kind: "failed",
142
668
  message: error instanceof Error ? error.message : String(error)
@@ -161,6 +687,7 @@ async function runDev(options) {
161
687
  if (path && isProjectPath(String(path)))
162
688
  schedule();
163
689
  });
690
+ const filesWatcher = existsSync(filesDirectory) ? watch(filesDirectory, () => schedule()) : null;
164
691
  try {
165
692
  pushing = push().finally(() => {
166
693
  pushing = null;
@@ -172,39 +699,117 @@ async function runDev(options) {
172
699
  });
173
700
  } finally {
174
701
  watcher.close();
702
+ filesWatcher?.close();
175
703
  if (timer)
176
704
  clearTimeout(timer);
177
705
  await pushing?.catch(() => {});
178
706
  }
179
707
  }
180
708
 
709
+ // src/cli/project.ts
710
+ import { readdir as readdir3, readFile as readFile3 } from "node:fs/promises";
711
+ import { join as join4, relative as relative2, sep as sep2 } from "node:path";
712
+ var SOURCE_FILE2 = /\.(?:tsx|ts|jsx|js|mjs|css|html|svg|json|md|txt)$/;
713
+ var LOCKFILES2 = new Set([
714
+ "package-lock.json",
715
+ "npm-shrinkwrap.json",
716
+ "bun.lock",
717
+ "bun.lockb",
718
+ "yarn.lock",
719
+ "pnpm-lock.yaml"
720
+ ]);
721
+ var SKIPPED_DIRECTORIES2 = new Set(["node_modules", "dist", "build"]);
722
+ function isProjectPath2(path) {
723
+ const parts = path.split(/[\\/]/);
724
+ return SOURCE_FILE2.test(path) && !LOCKFILES2.has(parts.at(-1) ?? "") && parts.every((part) => !part.startsWith(".") && !SKIPPED_DIRECTORIES2.has(part));
725
+ }
726
+ async function readProject2(directory) {
727
+ const manifestText = await readFile3(join4(directory, "manifest.json"), "utf8").catch(() => {
728
+ throw new Error(`No manifest.json in ${directory}. An app's folder holds its manifest beside its source.`);
729
+ });
730
+ const manifest = JSON.parse(manifestText);
731
+ if (typeof manifest !== "object" || manifest === null)
732
+ throw new Error("manifest.json is not an object");
733
+ const source = {};
734
+ for (const entry of await readdir3(directory, {
735
+ recursive: true,
736
+ withFileTypes: true
737
+ })) {
738
+ if (!entry.isFile())
739
+ continue;
740
+ const path = relative2(directory, join4(entry.parentPath, entry.name)).split(sep2).join("/");
741
+ if (path === "manifest.json" || !isProjectPath2(path))
742
+ continue;
743
+ source[path] = await readFile3(join4(directory, path), "utf8");
744
+ }
745
+ return { manifest, source };
746
+ }
747
+
748
+ // src/cli/siteFiles.ts
749
+ var DEFAULT_SITE_FILES_FOLDER2 = "_site-files";
750
+ var SITE_FILE_LIMITS2 = {
751
+ files: 200,
752
+ fileBytes: 50 * 1024 * 1024,
753
+ totalBytes: 200 * 1024 * 1024
754
+ };
755
+ var SITE_FILE_TYPES2 = {
756
+ png: "image/png",
757
+ jpg: "image/jpeg",
758
+ jpeg: "image/jpeg",
759
+ gif: "image/gif",
760
+ webp: "image/webp",
761
+ avif: "image/avif",
762
+ ico: "image/x-icon",
763
+ woff2: "font/woff2",
764
+ woff: "font/woff",
765
+ ttf: "font/ttf",
766
+ otf: "font/otf",
767
+ pdf: "application/pdf",
768
+ mp3: "audio/mpeg",
769
+ m4a: "audio/mp4",
770
+ aac: "audio/aac",
771
+ ogg: "audio/ogg",
772
+ oga: "audio/ogg",
773
+ opus: "audio/ogg",
774
+ wav: "audio/wav",
775
+ weba: "audio/webm",
776
+ flac: "audio/flac"
777
+ };
778
+ var MB2 = 1024 * 1024;
779
+ var MEDIA_TYPES2 = new Set(Object.values(SITE_FILE_TYPES2));
780
+ var APP_ID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
781
+ function isAppId2(id) {
782
+ return APP_ID2.test(id);
783
+ }
784
+ var LOOPBACK_HOSTS2 = new Set(["127.0.0.1", "localhost", "[::1]"]);
785
+
181
786
  // src/cli/signIn.ts
182
787
  import { spawn } from "node:child_process";
183
- import { chmod, mkdir, readFile as readFile2, rename, writeFile } from "node:fs/promises";
788
+ import { chmod, mkdir, readFile as readFile4, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
184
789
  import { createServer } from "node:http";
185
790
  import { homedir } from "node:os";
186
- import { dirname, join as join2 } from "node:path";
791
+ import { dirname, join as join5 } from "node:path";
187
792
  import {
188
793
  auth
189
794
  } from "@modelcontextprotocol/sdk/client/auth.js";
190
- var STORE = join2(homedir(), ".config", "alma", "app-cli.json");
795
+ var STORE = join5(homedir(), ".config", "alma", "app-cli.json");
191
796
  var CALLBACK_PORT = 53682;
192
797
  var CALLBACK_TIMEOUT_MS = 5 * 60000;
193
798
  var SCOPE = "openid email profile offline_access";
194
799
  async function load(server) {
195
- const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
800
+ const all = await readFile4(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
196
801
  return all[server] ?? {};
197
802
  }
198
803
  async function save(server, stored) {
199
- const all = await readFile2(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
804
+ const all = await readFile4(STORE, "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
200
805
  all[server] = stored;
201
806
  const folder = dirname(STORE);
202
807
  await mkdir(folder, { recursive: true, mode: 448 });
203
808
  await chmod(folder, 448);
204
809
  const temporary = `${STORE}.${process.pid}.tmp`;
205
- await writeFile(temporary, JSON.stringify(all, null, 2), { mode: 384 });
810
+ await writeFile2(temporary, JSON.stringify(all, null, 2), { mode: 384 });
206
811
  await chmod(temporary, 384);
207
- await rename(temporary, STORE);
812
+ await rename2(temporary, STORE);
208
813
  }
209
814
  function openBrowser(url) {
210
815
  const [command, ...args] = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
@@ -315,10 +920,16 @@ function signedInAuthor(server) {
315
920
  }
316
921
 
317
922
  // src/cli/main.ts
318
- var USAGE = `Usage: alma-app dev [folder] [--app <app id>] [--org <organization id>] [--server <MCP url>]
923
+ var USAGE = `Usage: alma-app dev|push [folder] [--app <app id>] [--org <organization id>]
924
+ [--files <folder>] [--server <MCP url>]
925
+ alma-app convert [folder]
319
926
 
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.`;
927
+ Pushes the app in [folder] (default: here) to Alma as a new draft version,
928
+ signed in to Alma in your browser: dev now and on every save, push once.
929
+ A web site's pictures, fonts, PDFs and audio are uploaded from --files
930
+ (default: ${DEFAULT_SITE_FILES_FOLDER2} in the folder) and listed in site-files.json first.
931
+ convert rewrites an app whose page is index.html as an app with screens
932
+ (src/app.tsx), showing members what it showed before.`;
322
933
  var { values, positionals } = parseArgs({
323
934
  args: process.argv.slice(2),
324
935
  allowPositionals: true,
@@ -326,6 +937,7 @@ var { values, positionals } = parseArgs({
326
937
  help: { type: "boolean", short: "h" },
327
938
  app: { type: "string" },
328
939
  org: { type: "string" },
940
+ files: { type: "string" },
329
941
  server: { type: "string", default: "https://mcp.alma.team/mcp" }
330
942
  }
331
943
  });
@@ -333,33 +945,87 @@ if (values.help || positionals[0] === "help") {
333
945
  console.info(USAGE);
334
946
  process.exit(0);
335
947
  }
336
- if (positionals[0] !== "dev") {
948
+ var command = positionals[0];
949
+ if (command === "convert") {
950
+ const folder = resolve(positionals[1] ?? ".");
951
+ try {
952
+ const converted = convertSinglePageApp(await readProject2(folder));
953
+ for (const [path, text] of Object.entries(converted.source)) {
954
+ await mkdir2(dirname2(join6(folder, path)), { recursive: true });
955
+ await writeFile3(join6(folder, path), text);
956
+ }
957
+ await rm(join6(folder, "index.html"));
958
+ await writeFile3(join6(folder, "manifest.json"), `${JSON.stringify(converted.manifest, null, 2)}
959
+ `);
960
+ console.info(`Converted ${folder}.`);
961
+ process.exit(0);
962
+ } catch (error) {
963
+ console.error(error instanceof ConversionRefusal ? `Not converted:
964
+ ${error.message}` : error instanceof Error ? error.message : String(error));
965
+ process.exit(1);
966
+ }
967
+ }
968
+ if (command !== "dev" && command !== "push") {
337
969
  console.error(USAGE);
338
970
  process.exit(1);
339
971
  }
340
972
  var directory = resolve(positionals[1] ?? ".");
973
+ var filesDirectory = values.files ? resolve(values.files) : join6(directory, DEFAULT_SITE_FILES_FOLDER2);
974
+ if (values.app && !isAppId2(values.app)) {
975
+ console.error(`--app ${values.app} is not an app id. The first push without --app prints it.`);
976
+ process.exit(1);
977
+ }
978
+ if (values.files && !existsSync2(filesDirectory)) {
979
+ console.error(`No folder at ${filesDirectory} (--files).`);
980
+ process.exit(1);
981
+ }
341
982
  var endpoint = values.server ?? "https://mcp.alma.team/mcp";
342
983
  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 ? "" : `
984
+ var connection = {
985
+ endpoint,
986
+ token: author.token,
987
+ reauthorize: author.reauthorize,
988
+ ...values.org ? { organizationId: values.org } : {}
989
+ };
990
+ var report = (event) => {
991
+ if (event.kind === "pushing")
992
+ console.info("Building a new draft\u2026");
993
+ else if (event.kind === "files") {
994
+ if (event.plan.changed.length > 0)
995
+ console.info(`Uploading ${event.plan.changed.length} site file(s)` + (event.plan.unchanged.length > 0 ? ` (${event.plan.unchanged.length} unchanged)` : ""));
996
+ } else if (event.kind === "failed")
997
+ console.error(event.message);
998
+ else
999
+ console.info(event.version.new_version ? `Draft updated. Open it: ${event.version.draft_url}` + (values.app ? "" : `
363
1000
  (--app ${event.version.app_id})`) : "No change since the last version.");
1001
+ };
1002
+ if (command === "push") {
1003
+ report({ kind: "pushing" });
1004
+ try {
1005
+ report({
1006
+ kind: "pushed",
1007
+ version: await pushOnce({
1008
+ directory,
1009
+ filesDirectory,
1010
+ connection,
1011
+ appId: values.app ?? null,
1012
+ onEvent: report
1013
+ })
1014
+ });
1015
+ } catch (error) {
1016
+ console.error(error instanceof Error ? error.message : String(error));
1017
+ process.exit(1);
364
1018
  }
365
- });
1019
+ } else {
1020
+ const controller = new AbortController;
1021
+ process.on("SIGINT", () => controller.abort());
1022
+ console.info(`Watching ${directory}. Ctrl-C stops.`);
1023
+ await runDev({
1024
+ directory,
1025
+ filesDirectory,
1026
+ appId: values.app ?? null,
1027
+ connection,
1028
+ signal: controller.signal,
1029
+ onEvent: report
1030
+ });
1031
+ }