addtohome 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.js +570 -0
  2. package/package.json +29 -3
  3. package/README.md +0 -3
package/dist/cli.js ADDED
@@ -0,0 +1,570 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/run.ts
4
+ import { parseArgs } from "node:util";
5
+
6
+ // ../shared/src/index.ts
7
+ var NO_GUIDE_REASON = {
8
+ Installed: "installed",
9
+ InApp: "in-app",
10
+ Unsupported: "unsupported"
11
+ };
12
+ var SHOWN_REASON = {
13
+ Guide: "guide",
14
+ /** Android: the browser's own install dialog, behind our Install button. */
15
+ NativePrompt: "native_prompt",
16
+ /** Android with no install dialog available: point to the browser menu. */
17
+ MenuHint: "menu_hint",
18
+ /** Android, inside an app's own browser: a button that reopens the page in Chrome. */
19
+ OpenInBrowser: "open_in_browser",
20
+ ...NO_GUIDE_REASON
21
+ };
22
+ var EVENT_NAME = {
23
+ Shown: "shown",
24
+ Step: "step",
25
+ Complete: "complete",
26
+ LayoutChanged: "layout_changed",
27
+ ButtonShown: "button_shown",
28
+ Opened: "opened",
29
+ Closed: "closed",
30
+ Dismissed: "dismissed",
31
+ LaunchedFromHomeScreen: "launched_from_home_screen",
32
+ /** Android: the visitor tapped Install and the browser's dialog opened. */
33
+ InstallPrompted: "install_prompted",
34
+ InstallAccepted: "install_accepted",
35
+ InstallDismissed: "install_dismissed",
36
+ /** The browser reported the app was installed (Android `appinstalled`). */
37
+ AppInstalled: "app_installed",
38
+ /** Android: the visitor tapped to leave an app's own browser. The detail says which browser they chose. */
39
+ OpenInBrowser: "open_in_browser",
40
+ /**
41
+ * A visit on a phone, in the browser, to pages with the loader: once per browser session, or per page when storage
42
+ * is blocked. Counted on addtohome.com only, never sent to the site's analytics.
43
+ */
44
+ PhoneVisit: "phone_visit",
45
+ /** An install reason was put on screen. Reason events carry `reasonDetail(key, variant)`. */
46
+ ReasonShown: "reason_shown",
47
+ /** The visitor tapped the reason's button. */
48
+ ReasonAccepted: "reason_accepted",
49
+ /** The visitor tapped Not now, or closed the reason. */
50
+ ReasonDismissed: "reason_dismissed",
51
+ /** After a reason: the walkthrough reached its last step, or Android's install dialog was accepted. */
52
+ ReasonComplete: "reason_complete",
53
+ /** The welcome-back card was shown on the first open from the Home Screen. */
54
+ WelcomeShown: "welcome_shown",
55
+ /** The visitor tapped the welcome-back card's button. */
56
+ WelcomeAccepted: "welcome_accepted"
57
+ };
58
+ var COUNTED_EVENT = {
59
+ ButtonShown: EVENT_NAME.ButtonShown,
60
+ Opened: EVENT_NAME.Opened,
61
+ Shown: EVENT_NAME.Shown,
62
+ Step: EVENT_NAME.Step,
63
+ Complete: EVENT_NAME.Complete,
64
+ InstallPrompted: EVENT_NAME.InstallPrompted,
65
+ InstallAccepted: EVENT_NAME.InstallAccepted,
66
+ InstallDismissed: EVENT_NAME.InstallDismissed,
67
+ AppInstalled: EVENT_NAME.AppInstalled,
68
+ OpenInBrowser: EVENT_NAME.OpenInBrowser,
69
+ LaunchedFromHomeScreen: EVENT_NAME.LaunchedFromHomeScreen,
70
+ PhoneVisit: EVENT_NAME.PhoneVisit,
71
+ ReasonShown: EVENT_NAME.ReasonShown,
72
+ ReasonAccepted: EVENT_NAME.ReasonAccepted,
73
+ ReasonDismissed: EVENT_NAME.ReasonDismissed,
74
+ ReasonComplete: EVENT_NAME.ReasonComplete,
75
+ WelcomeShown: EVENT_NAME.WelcomeShown,
76
+ WelcomeAccepted: EVENT_NAME.WelcomeAccepted
77
+ };
78
+ var INSTALL_UNLOCK = {
79
+ /** Web push. iPhone and iPad only: Android can send alerts to a site in the browser. */
80
+ Alerts: "alerts",
81
+ OneTap: "one_tap",
82
+ FullScreen: "full_screen"
83
+ };
84
+ var UNLOCK_FACT = {
85
+ [INSTALL_UNLOCK.Alerts]: "iPhone sends alerts only to apps on your Home Screen.",
86
+ [INSTALL_UNLOCK.OneTap]: "It opens from its own icon, like any app.",
87
+ [INSTALL_UNLOCK.FullScreen]: "From the Home Screen it opens with no address bar or tabs."
88
+ };
89
+ var AUDIT_LEVEL = {
90
+ Pass: "pass",
91
+ Warn: "warn",
92
+ Fail: "fail"
93
+ };
94
+ var AUDIT_GROUP = {
95
+ Manifest: "manifest",
96
+ Icons: "icons",
97
+ IPhone: "iphone",
98
+ ServiceWorker: "service-worker"
99
+ };
100
+ var AUDIT_CHECK = {
101
+ Https: "https",
102
+ ManifestLinked: "manifest-linked",
103
+ ManifestLoads: "manifest-loads",
104
+ ManifestName: "manifest-name",
105
+ ManifestShortName: "manifest-short-name",
106
+ ManifestStartUrl: "manifest-start-url",
107
+ ManifestDisplay: "manifest-display",
108
+ ManifestThemeColor: "manifest-theme-color",
109
+ Icon192: "icon-192",
110
+ Icon512: "icon-512",
111
+ IconMaskable: "icon-maskable",
112
+ AppleTouchIcon: "apple-touch-icon",
113
+ AppleTitle: "apple-title",
114
+ AppleStatusBar: "apple-status-bar",
115
+ ViewportFit: "viewport-fit",
116
+ ServiceWorker: "service-worker"
117
+ };
118
+
119
+ // ../audit/src/head.ts
120
+ var ATTRIBUTE = /([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g;
121
+ function readAttributes(source) {
122
+ const attrs = {};
123
+ for (const [, name = "", double, single, bare] of source.matchAll(ATTRIBUTE)) {
124
+ attrs[name.toLowerCase()] ??= double ?? single ?? bare ?? "";
125
+ }
126
+ return attrs;
127
+ }
128
+ var HEAD_TAGS = ["link", "meta", "base"];
129
+ var TEXT_ONLY = ["script", "style", "textarea", "title"];
130
+ var FOREIGN = ["svg", "math"];
131
+ var SELF_CLOSING = /(?:^|[\s"'])\/$/;
132
+ function readHead(html) {
133
+ const token = /<!--(?:-?>|[\s\S]*?(?:--!?>|$))|<(\/?)([a-z][^\s/>]*)((?:[^>=]+|=(?:\s*(?:"[^"]*(?:"|$)|'[^']*(?:'|$)|[^\s>"'][^\s>]*))?)*)(>?)/gi;
134
+ const tags = [];
135
+ let registersServiceWorker = false;
136
+ let foreignDepth = 0;
137
+ for (let match = token.exec(html); match; match = token.exec(html)) {
138
+ const [, slash, rawName = "", attributes = "", end] = match;
139
+ const name = rawName.toLowerCase();
140
+ if (!end) continue;
141
+ const selfClosed = SELF_CLOSING.test(attributes);
142
+ if (FOREIGN.includes(name)) {
143
+ if (slash) foreignDepth = Math.max(0, foreignDepth - 1);
144
+ else if (!selfClosed) foreignDepth++;
145
+ }
146
+ if (slash) continue;
147
+ if (HEAD_TAGS.includes(name)) tags.push({ tag: name, attrs: readAttributes(attributes) });
148
+ if (!TEXT_ONLY.includes(name)) continue;
149
+ if (name !== "script" && selfClosed && foreignDepth > 0) continue;
150
+ const closing = new RegExp(`</${name}(?=[\\s/>])`, "gi");
151
+ closing.lastIndex = token.lastIndex;
152
+ const stop = closing.exec(html)?.index ?? html.length;
153
+ if (name === "script" && html.slice(token.lastIndex, stop).includes("serviceWorker.register")) registersServiceWorker = true;
154
+ token.lastIndex = stop;
155
+ }
156
+ return { tags, registersServiceWorker };
157
+ }
158
+
159
+ // ../audit/src/png.ts
160
+ var SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
161
+ var IHDR = [73, 72, 68, 82];
162
+ var hasBytesAt = (bytes, offset, expected) => expected.every((byte, i) => bytes[offset + i] === byte);
163
+ function pngSize(bytes) {
164
+ if (bytes.length < 24 || !hasBytesAt(bytes, 0, SIGNATURE) || !hasBytesAt(bytes, 12, IHDR)) return null;
165
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
166
+ return { width: view.getUint32(16), height: view.getUint32(20) };
167
+ }
168
+
169
+ // ../audit/src/text.ts
170
+ var AUDIT_GROUP_TEXT = {
171
+ [AUDIT_GROUP.Manifest]: "Manifest",
172
+ [AUDIT_GROUP.Icons]: "Icons",
173
+ [AUDIT_GROUP.IPhone]: "iPhone",
174
+ [AUDIT_GROUP.ServiceWorker]: "Service worker"
175
+ };
176
+ var unreachableText = (detail) => detail ? `The page answered with ${detail}, so there's nothing to check. A firewall or bot protection may be blocking the check.` : "The page didn't answer, so there's nothing to check. Make sure the address opens in a browser.";
177
+ var AUDIT_TEXT = {
178
+ [AUDIT_CHECK.Https]: {
179
+ title: "Secure connection (HTTPS)",
180
+ fix: "Serve the site over HTTPS, so visitors don't see a Not Secure warning and Android can offer one-tap install."
181
+ },
182
+ [AUDIT_CHECK.ManifestLinked]: {
183
+ title: "App manifest linked",
184
+ fix: `Add <link rel="manifest" href="/manifest.json"> to the page's head, so a visitor's phone can find your site's name, icons and how to open it.`
185
+ },
186
+ [AUDIT_CHECK.ManifestLoads]: {
187
+ title: "App manifest file",
188
+ fix: "Serve a JSON manifest at the linked address, because a phone can't read your site's name or icons from a missing or broken file."
189
+ },
190
+ [AUDIT_CHECK.ManifestName]: {
191
+ title: "Site name",
192
+ fix: "Add name to the manifest, so visitors see your name when they add your site to the Home Screen."
193
+ },
194
+ [AUDIT_CHECK.ManifestShortName]: {
195
+ title: "Short name",
196
+ fix: "Add a short_name of 12 characters or fewer to the manifest, so the name under your icon isn't cut off."
197
+ },
198
+ [AUDIT_CHECK.ManifestStartUrl]: {
199
+ title: "Start address",
200
+ fix: "Set start_url in the manifest to a page of your site inside its scope, so your icon opens the right place."
201
+ },
202
+ [AUDIT_CHECK.ManifestDisplay]: {
203
+ title: "App-style window",
204
+ fix: `Set display to "standalone" in the manifest, so your site opens from the Home Screen without the browser's address bar.`
205
+ },
206
+ [AUDIT_CHECK.ManifestThemeColor]: {
207
+ title: "Theme color",
208
+ fix: "Add theme_color to the manifest, so the phone can match the bars around your site to your brand."
209
+ },
210
+ [AUDIT_CHECK.Icon192]: {
211
+ title: "192px icon",
212
+ fix: "Add a 192px PNG icon to the manifest, so visitors on Android see your icon on their Home screen."
213
+ },
214
+ [AUDIT_CHECK.Icon512]: {
215
+ title: "512px icon",
216
+ fix: "Add a 512px PNG icon to the manifest, so Android has a sharp image for the Home screen and the splash screen."
217
+ },
218
+ [AUDIT_CHECK.IconMaskable]: {
219
+ title: "Maskable icon",
220
+ fix: 'Add an icon with purpose "maskable" to the manifest, so Android can fill its icon shape with your artwork instead of shrinking it onto a plain background.'
221
+ },
222
+ [AUDIT_CHECK.AppleTouchIcon]: {
223
+ title: "iPhone icon",
224
+ fix: 'Add <link rel="apple-touch-icon"> with a PNG of 180px or more, so you choose the icon visitors see on an iPhone Home Screen.'
225
+ },
226
+ [AUDIT_CHECK.AppleTitle]: {
227
+ title: "iPhone name",
228
+ fix: "Add an apple-mobile-web-app-title meta tag, so you choose the name under your icon on an iPhone."
229
+ },
230
+ [AUDIT_CHECK.AppleStatusBar]: {
231
+ title: "iPhone status bar style",
232
+ fix: "Add an apple-mobile-web-app-status-bar-style meta tag, so the clock and battery area suits your design when your site opens from the Home Screen."
233
+ },
234
+ [AUDIT_CHECK.ViewportFit]: {
235
+ title: "Full-screen layout",
236
+ fix: "Add viewport-fit=cover to the viewport meta tag and keep controls inside the safe areas, so your design reaches the edges of an iPhone screen."
237
+ },
238
+ [AUDIT_CHECK.ServiceWorker]: {
239
+ title: "Service worker",
240
+ fix: "Register a service worker, so your site can show visitors something useful when they open it without a connection."
241
+ }
242
+ };
243
+
244
+ // ../audit/src/index.ts
245
+ var USER_AGENT = "addtohome check";
246
+ var TIMEOUT_MS = 8e3;
247
+ var MAX_BYTES = 2 * 1024 * 1024;
248
+ var MAX_ICON_BYTES = 64 * 1024;
249
+ var MAX_QUOTED = 40;
250
+ var MAX_ICONS = 12;
251
+ var MAX_APPLE_ICONS = 4;
252
+ var MAX_REDIRECTS = 5;
253
+ var REDIRECTS = [301, 302, 303, 307, 308];
254
+ var NO_RESPONSE = "no response";
255
+ var WEB_PROTOCOLS = ["http:", "https:"];
256
+ var SHORT_NAME_MAX = 12;
257
+ var APPLE_ICON_MIN = 180;
258
+ var DECLARED = "declared, not measured";
259
+ var APP_DISPLAYS = ["standalone", "fullscreen", "minimal-ui"];
260
+ var LOCAL_HOSTS = ["localhost", "127.0.0.1"];
261
+ var ENTITIES = { "&amp;": "&", "&quot;": '"', "&lt;": "<", "&gt;": ">" };
262
+ var ENTITY = /&(?:amp|quot|lt|gt|#(\d+)|#[xX]([\da-fA-F]+));/g;
263
+ var GROUP = {
264
+ [AUDIT_CHECK.Https]: AUDIT_GROUP.Manifest,
265
+ [AUDIT_CHECK.ManifestLinked]: AUDIT_GROUP.Manifest,
266
+ [AUDIT_CHECK.ManifestLoads]: AUDIT_GROUP.Manifest,
267
+ [AUDIT_CHECK.ManifestName]: AUDIT_GROUP.Manifest,
268
+ [AUDIT_CHECK.ManifestShortName]: AUDIT_GROUP.Manifest,
269
+ [AUDIT_CHECK.ManifestStartUrl]: AUDIT_GROUP.Manifest,
270
+ [AUDIT_CHECK.ManifestDisplay]: AUDIT_GROUP.Manifest,
271
+ [AUDIT_CHECK.ManifestThemeColor]: AUDIT_GROUP.Manifest,
272
+ [AUDIT_CHECK.Icon192]: AUDIT_GROUP.Icons,
273
+ [AUDIT_CHECK.Icon512]: AUDIT_GROUP.Icons,
274
+ [AUDIT_CHECK.IconMaskable]: AUDIT_GROUP.Icons,
275
+ [AUDIT_CHECK.AppleTouchIcon]: AUDIT_GROUP.IPhone,
276
+ [AUDIT_CHECK.AppleTitle]: AUDIT_GROUP.IPhone,
277
+ [AUDIT_CHECK.AppleStatusBar]: AUDIT_GROUP.IPhone,
278
+ [AUDIT_CHECK.ViewportFit]: AUDIT_GROUP.IPhone,
279
+ [AUDIT_CHECK.ServiceWorker]: AUDIT_GROUP.ServiceWorker
280
+ };
281
+ async function readCapped(response, limit) {
282
+ const reader = response.body?.getReader();
283
+ if (!reader) return new Uint8Array();
284
+ const chunks = [];
285
+ let size = 0;
286
+ while (size < limit) {
287
+ const { done, value } = await reader.read();
288
+ if (done) break;
289
+ const kept = new Uint8Array(value.subarray(0, limit - size));
290
+ chunks.push(kept);
291
+ size += kept.length;
292
+ }
293
+ void reader.cancel().catch(() => {
294
+ });
295
+ return new Uint8Array(await new Blob(chunks).arrayBuffer());
296
+ }
297
+ function asUtf8(header) {
298
+ const codes = Array.from(header, (char) => char.charCodeAt(0));
299
+ if (codes.some((code2) => code2 > 255)) return header;
300
+ try {
301
+ return new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(codes));
302
+ } catch {
303
+ return header;
304
+ }
305
+ }
306
+ async function get({ fetch: fetch2, allow }, href, maxBytes) {
307
+ const abort = new AbortController();
308
+ const timer = setTimeout(() => abort.abort(), TIMEOUT_MS);
309
+ try {
310
+ let url = new URL(href);
311
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
312
+ url.hash = "";
313
+ if (!allow(url)) return null;
314
+ const response = await fetch2(url.href, { redirect: "manual", headers: { "user-agent": USER_AGENT }, signal: abort.signal });
315
+ if (!REDIRECTS.includes(response.status)) {
316
+ const bytes = await readCapped(response, maxBytes);
317
+ return { url: url.href, status: response.status, type: response.headers.get("content-type") ?? "", bytes };
318
+ }
319
+ void response.body?.cancel().catch(() => {
320
+ });
321
+ const location = response.headers.get("location");
322
+ if (!location) return null;
323
+ url = new URL(asUtf8(location), url);
324
+ }
325
+ return null;
326
+ } catch {
327
+ return null;
328
+ } finally {
329
+ clearTimeout(timer);
330
+ }
331
+ }
332
+ var text = (value) => typeof value === "string" ? value.trim() : "";
333
+ var words = (value) => text(value).toLowerCase().split(/\s+/).filter(Boolean);
334
+ var decode = (value) => value.replace(ENTITY, (entity, decimal, hex) => {
335
+ if (!decimal && !hex) return ENTITIES[entity] ?? entity;
336
+ const code2 = decimal ? Number(decimal) : parseInt(hex ?? "", 16);
337
+ return code2 <= 1114111 ? String.fromCodePoint(code2) : entity;
338
+ });
339
+ function resolve(href, base) {
340
+ if (!href) return null;
341
+ try {
342
+ return new URL(href, base).href;
343
+ } catch {
344
+ return null;
345
+ }
346
+ }
347
+ function parseManifest(bytes) {
348
+ try {
349
+ const value = JSON.parse(new TextDecoder().decode(bytes));
350
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
351
+ } catch {
352
+ return null;
353
+ }
354
+ }
355
+ function startsInScope(manifest, manifestUrl, pageUrl2) {
356
+ const start = resolve(text(manifest.start_url), manifestUrl);
357
+ if (!start) return false;
358
+ const declared = text(manifest.scope);
359
+ const scope = declared ? resolve(declared, manifestUrl) : resolve(".", start);
360
+ if (!scope) return false;
361
+ const from = new URL(start);
362
+ const within = new URL(scope);
363
+ return from.origin === new URL(pageUrl2).origin && from.origin === within.origin && from.pathname.startsWith(within.pathname);
364
+ }
365
+ function manifestIcons(manifest, manifestUrl) {
366
+ if (!Array.isArray(manifest.icons)) return [];
367
+ return manifest.icons.flatMap((entry) => {
368
+ const icon = entry ?? {};
369
+ const url = resolve(text(icon.src), manifestUrl);
370
+ return url ? [{ url, sizes: words(icon.sizes), maskable: words(icon.purpose).includes("maskable") }] : [];
371
+ });
372
+ }
373
+ var declares = (sizes, min) => sizes.some((size) => {
374
+ if (size === "any") return true;
375
+ const [width, height] = size.split("x").map(Number);
376
+ return Number(width) >= min && Number(height) >= min;
377
+ });
378
+ var largestDeclared = (sizes) => sizes.reduce((max, size) => Math.max(max, size === "any" ? Infinity : parseInt(size, 10) || 0), 0);
379
+ function biggestFirst(icons, unsized = 0) {
380
+ const rank = ({ sizes }) => sizes.length ? largestDeclared(sizes) : unsized;
381
+ return [...new Set([...icons].sort((a, b) => rank(b) - rank(a)).map((i) => i.url))];
382
+ }
383
+ function iconRequests(apple, manifest) {
384
+ const fromManifest = biggestFirst(manifest);
385
+ const fromApple = biggestFirst(apple, APPLE_ICON_MIN).slice(0, Math.max(MAX_APPLE_ICONS, MAX_ICONS - fromManifest.length));
386
+ return [.../* @__PURE__ */ new Set([...fromApple, ...fromManifest])].slice(0, MAX_ICONS);
387
+ }
388
+ function isImageType(contentType) {
389
+ const type = contentType.toLowerCase().trim();
390
+ if (type.startsWith("image/svg+xml")) return true;
391
+ return !type.startsWith("text/") && !type.startsWith("application/json") && !/html|xml/.test(type);
392
+ }
393
+ function iconResult(icons, loaded, min) {
394
+ let declared = false;
395
+ const asked = icons.filter((icon) => loaded.has(icon.url));
396
+ for (const icon of asked) {
397
+ const file = loaded.get(icon.url);
398
+ if (!file || file.status !== 200 || !isImageType(file.type)) continue;
399
+ const real = pngSize(file.bytes);
400
+ if (!real) declared ||= declares(icon.sizes, min);
401
+ else if (real.width >= min && real.height >= min) return { found: true };
402
+ }
403
+ if (declared) return { found: true, detail: DECLARED };
404
+ const unanswered = asked.length > 0 && asked.every((icon) => !loaded.get(icon.url));
405
+ return { found: false, detail: unanswered ? NO_RESPONSE : void 0 };
406
+ }
407
+ async function audit(url, opts = {}) {
408
+ const requester = {
409
+ fetch: opts.fetch ?? fetch,
410
+ allow: opts.allow ?? ((target) => WEB_PROTOCOLS.includes(target.protocol))
411
+ };
412
+ const page = await get(requester, url, MAX_BYTES);
413
+ if (!page || page.status < 200 || page.status > 299) return { url, reachable: false, results: [], ...page ? { detail: `HTTP ${page.status}` } : {} };
414
+ const { tags, registersServiceWorker } = readHead(new TextDecoder().decode(page.bytes));
415
+ const attr = (tag, name) => decode(tag?.attrs[name] ?? "").trim();
416
+ const base = resolve(attr(tags.find((t) => t.tag === "base" && t.attrs.href), "href"), page.url) ?? page.url;
417
+ const links = (rel) => tags.filter((t) => t.tag === "link" && words(t.attrs.rel).includes(rel) && attr(t, "href"));
418
+ const meta = (name) => attr(tags.find((t) => t.tag === "meta" && t.attrs.name?.toLowerCase() === name), "content");
419
+ const results = [];
420
+ const add = (check, passes, otherwise, detail) => {
421
+ results.push({ check, group: GROUP[check], level: passes ? AUDIT_LEVEL.Pass : otherwise, ...detail ? { detail } : {} });
422
+ };
423
+ const required = (check, passes, detail) => add(check, passes, AUDIT_LEVEL.Fail, detail);
424
+ const advised = (check, passes, detail) => add(check, passes, AUDIT_LEVEL.Warn, detail);
425
+ const { protocol, hostname } = new URL(page.url);
426
+ required(AUDIT_CHECK.Https, protocol === "https:" || LOCAL_HOSTS.includes(hostname));
427
+ const manifestLink = links("manifest")[0];
428
+ required(AUDIT_CHECK.ManifestLinked, !!manifestLink);
429
+ let manifest = null;
430
+ let manifestUrl = page.url;
431
+ if (manifestLink) {
432
+ const href = resolve(attr(manifestLink, "href"), base);
433
+ const file = href ? await get(requester, href, MAX_BYTES) : null;
434
+ manifest = file?.status === 200 ? parseManifest(file.bytes) : null;
435
+ if (file) manifestUrl = file.url;
436
+ const problem = !file ? NO_RESPONSE : file.status !== 200 ? `HTTP ${file.status}` : "not JSON";
437
+ required(AUDIT_CHECK.ManifestLoads, !!manifest, manifest ? void 0 : problem);
438
+ }
439
+ const icons = manifest ? manifestIcons(manifest, manifestUrl) : [];
440
+ const appleIcons = links("apple-touch-icon").flatMap((t) => {
441
+ const href = resolve(attr(t, "href"), base);
442
+ return href ? [{ url: href, sizes: words(t.attrs.sizes) }] : [];
443
+ });
444
+ const wanted = iconRequests(appleIcons, icons);
445
+ const loaded = new Map(await Promise.all(wanted.map(async (href) => [href, await get(requester, href, MAX_ICON_BYTES)])));
446
+ if (manifest) {
447
+ const shortName = text(manifest.short_name);
448
+ required(AUDIT_CHECK.ManifestName, !!(text(manifest.name) || shortName));
449
+ advised(AUDIT_CHECK.ManifestShortName, !!shortName && [...shortName].length <= SHORT_NAME_MAX);
450
+ required(AUDIT_CHECK.ManifestStartUrl, startsInScope(manifest, manifestUrl, page.url));
451
+ const display = text(manifest.display);
452
+ const isApp = APP_DISPLAYS.includes(display);
453
+ required(AUDIT_CHECK.ManifestDisplay, isApp, isApp ? void 0 : display.slice(0, MAX_QUOTED) || "missing");
454
+ }
455
+ advised(AUDIT_CHECK.ManifestThemeColor, !!(text(manifest?.theme_color) || meta("theme-color")));
456
+ if (manifest) {
457
+ for (const [check, min] of [[AUDIT_CHECK.Icon192, 192], [AUDIT_CHECK.Icon512, 512]]) {
458
+ const { found, detail } = iconResult(icons, loaded, min);
459
+ required(check, found, detail);
460
+ }
461
+ advised(AUDIT_CHECK.IconMaskable, icons.some((icon) => icon.maskable));
462
+ }
463
+ const apple = iconResult(appleIcons, loaded, APPLE_ICON_MIN);
464
+ advised(AUDIT_CHECK.AppleTouchIcon, apple.found, apple.detail);
465
+ advised(AUDIT_CHECK.AppleTitle, !!meta("apple-mobile-web-app-title"));
466
+ advised(AUDIT_CHECK.AppleStatusBar, !!meta("apple-mobile-web-app-status-bar-style"));
467
+ advised(AUDIT_CHECK.ViewportFit, /viewport-fit\s*=\s*cover/i.test(meta("viewport")));
468
+ advised(AUDIT_CHECK.ServiceWorker, registersServiceWorker, registersServiceWorker ? void 0 : "not found in the page's HTML");
469
+ return { url: page.url, reachable: true, results };
470
+ }
471
+
472
+ // src/format.ts
473
+ var STYLE = { Bold: 1, Red: 31, Green: 32, Yellow: 33 };
474
+ var MARK = {
475
+ [AUDIT_LEVEL.Pass]: { symbol: "\u2713", style: STYLE.Green },
476
+ [AUDIT_LEVEL.Warn]: { symbol: "!", style: STYLE.Yellow },
477
+ [AUDIT_LEVEL.Fail]: { symbol: "\u2717", style: STYLE.Red }
478
+ };
479
+ var NEXT_STEP = "Fix these, then show visitors how to add it: https://addtohome.com";
480
+ var printable = (value) => value.replace(new RegExp("\\p{Cc}", "gu"), "");
481
+ function summary(report) {
482
+ const count = (level) => report.results.filter((r) => r.level === level).length;
483
+ const failed = count(AUDIT_LEVEL.Fail);
484
+ const warnings = count(AUDIT_LEVEL.Warn);
485
+ const passed = count(AUDIT_LEVEL.Pass);
486
+ return [
487
+ failed && `${failed} failed`,
488
+ warnings && `${warnings} ${warnings === 1 ? "warning" : "warnings"}`,
489
+ passed && `${passed} passed`
490
+ ].filter(Boolean).join(", ");
491
+ }
492
+ function formatReport(report, color) {
493
+ const paint = (style, value) => color ? `\x1B[${style}m${value}\x1B[0m` : value;
494
+ if (!report.reachable) {
495
+ return `${report.url}
496
+
497
+ ${paint(STYLE.Red, MARK[AUDIT_LEVEL.Fail].symbol)} ${unreachableText(report.detail)}
498
+ `;
499
+ }
500
+ const lines = [report.url];
501
+ for (const group of Object.values(AUDIT_GROUP)) {
502
+ const results = report.results.filter((r) => r.group === group);
503
+ if (!results.length) continue;
504
+ lines.push("", paint(STYLE.Bold, AUDIT_GROUP_TEXT[group]));
505
+ for (const { check, level, detail } of results) {
506
+ const { symbol, style } = MARK[level];
507
+ lines.push(` ${paint(style, symbol)} ${AUDIT_TEXT[check].title}${detail ? ` (${printable(detail)})` : ""}`);
508
+ if (level !== AUDIT_LEVEL.Pass) lines.push(` ${AUDIT_TEXT[check].fix}`);
509
+ }
510
+ }
511
+ lines.push("", summary(report));
512
+ if (report.results.some((r) => r.level === AUDIT_LEVEL.Fail)) lines.push(NEXT_STEP);
513
+ return `${lines.join("\n")}
514
+ `;
515
+ }
516
+
517
+ // src/run.ts
518
+ var EXIT = { Ok: 0, Failed: 1, Usage: 2 };
519
+ var COMMAND = { Check: "check" };
520
+ var LOCAL_HOSTS2 = ["localhost", "127.0.0.1"];
521
+ var LEADING_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
522
+ var UNESCAPED_CONTROLS = /[\u007f-\u009f]/g;
523
+ var USAGE = `Usage: addtohome check <url> [--json]
524
+
525
+ Checks a site's app manifest, icons, iPhone tags and service worker, and says
526
+ what's missing before a phone can add it to the Home Screen well.
527
+
528
+ <url> A domain or an https:// address. http:// works for localhost only.
529
+ --json Print the results as JSON
530
+ --help Show this help
531
+ `;
532
+ function parse(argv) {
533
+ try {
534
+ return parseArgs({ args: argv, allowPositionals: true, options: { json: { type: "boolean" }, help: { type: "boolean" } } });
535
+ } catch {
536
+ return null;
537
+ }
538
+ }
539
+ var toJson = (value) => JSON.stringify(value, null, 2).replace(UNESCAPED_CONTROLS, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
540
+ function pageUrl(input) {
541
+ try {
542
+ const url = new URL(LEADING_SCHEME.test(input) ? input : `https://${input}`);
543
+ const allowed = url.protocol === "https:" || url.protocol === "http:" && LOCAL_HOSTS2.includes(url.hostname);
544
+ return allowed ? url.href : null;
545
+ } catch {
546
+ return null;
547
+ }
548
+ }
549
+ async function run(argv, io) {
550
+ const args = parse(argv);
551
+ if (args?.values.help) return { code: EXIT.Ok, out: USAGE };
552
+ const [command, input, ...extra] = args?.positionals ?? [];
553
+ if (!args || command !== COMMAND.Check || !input || extra.length) return { code: EXIT.Usage, out: USAGE };
554
+ const url = pageUrl(input);
555
+ if (!url) return { code: EXIT.Usage, out: `That address can't be checked.
556
+
557
+ ${USAGE}` };
558
+ const report = await audit(url, { fetch: io.fetch });
559
+ const failed = !report.reachable || report.results.some((r) => r.level === AUDIT_LEVEL.Fail);
560
+ return {
561
+ code: failed ? EXIT.Failed : EXIT.Ok,
562
+ out: args.values.json ? `${toJson(report)}
563
+ ` : formatReport(report, io.color)
564
+ };
565
+ }
566
+
567
+ // src/cli.ts
568
+ var { code, out } = await run(process.argv.slice(2), { color: process.stdout.isTTY && !process.env.NO_COLOR });
569
+ process.stdout.write(out);
570
+ process.exitCode = code;
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "addtohome",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Checks a site's Home Screen setup from the command line",
5
+ "type": "module",
6
+ "bin": {
7
+ "addtohome": "./dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "license": "UNLICENSED",
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "devDependencies": {
20
+ "@types/node": "22.20.5",
21
+ "esbuild": "0.28.2",
22
+ "typescript": "5.9.3",
23
+ "vitest": "3.2.7",
24
+ "@addtohome/audit": "0.1.0",
25
+ "@addtohome/shared": "0.1.0"
26
+ },
27
+ "scripts": {
28
+ "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --target=node20 --banner:js=\"#!/usr/bin/env node\" --outfile=dist/cli.js",
29
+ "typecheck": "tsc --noEmit",
30
+ "test": "vitest run"
31
+ }
6
32
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.