#!/usr/bin/env node
// wapp 1.0.0: make, check and try WispOS app packages (.wapp, format wispos.app/1).
// One file, no dependencies, Node 18 or newer. Built by the WispOS App Store's
// tools/build-wapp-cli.mjs from tools/wapp.mjs and tools/lib/; don't edit it here.
// Format: https://wisp-os.com/docs/app-store/building-apps/
import crypto from "node:crypto";
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import zlib from "node:zlib";
import { execFile } from "node:child_process";

// ---- tools/lib/zip.mjs -----------------------------------------------------
const mod_zip = (() => {
// A small, strict ZIP writer and reader for app packages (spec/APP-PACKAGE.md,
// "Container"). No dependencies: node:zlib does deflate and CRC-32.
//
// The writer is deterministic: same files in, same bytes out (fixed
// timestamps, no extra fields, entries in the order given).
// The reader accepts only the subset the spec allows and refuses the rest:
// no encryption, no ZIP64, no data descriptors, no archive comment, no bytes
// before the first entry or between entries, methods 0 (store) and 8 (deflate).

const SIG_LOCAL = 0x04034b50;
const SIG_CENTRAL = 0x02014b50;
const SIG_END = 0x06054b50;
const FLAG_UTF8 = 1 << 11;
// 1980-01-01 00:00, the DOS epoch: every entry gets it, so builds are reproducible.
const DOS_TIME = 0;
const DOS_DATE = (0 << 9) | (1 << 5) | 1;

class ZipError extends Error {}

// 2 GiB archive, 2x extracted headroom; stay below ZIP64’s 65,535 sentinel.
const ZIP_LIMITS = Object.freeze({ packageBytes: 2 * 1024 ** 3, unpackedBytes: 4 * 1024 ** 3, entries: 60000, pathBytes: 255 });

/**
 * entries: [{ name, data: Buffer, store?: boolean, deflate?: boolean }] in
 * archive order. store: never compress; deflate: always (tests only).
 * Returns the archive as one Buffer.
 */
function writeZip(entries) {
  if (entries.length > ZIP_LIMITS.entries) throw new ZipError(`more than ${ZIP_LIMITS.entries} files`);
  const total = entries.reduce((n, e) => n + Buffer.byteLength(e.data), 0);
  if (total > ZIP_LIMITS.unpackedBytes) throw new ZipError(`unpacked size is over the ${ZIP_LIMITS.unpackedBytes} byte limit`);
  const locals = [];
  const centrals = [];
  let offset = 0;
  for (const e of entries) {
    const name = Buffer.from(e.name, "utf8");
    const data = Buffer.isBuffer(e.data) ? e.data : Buffer.from(e.data);
    const crc = zlib.crc32(data) >>> 0;
    let method = 0;
    let body = data;
    if (!e.store && data.length > 0) {
      const deflated = zlib.deflateRawSync(data, { level: 9 });
      if (deflated.length < data.length || e.deflate) { method = 8; body = deflated; }
    }
    const local = Buffer.alloc(30);
    local.writeUInt32LE(SIG_LOCAL, 0);
    local.writeUInt16LE(20, 4);           // version needed: 2.0
    local.writeUInt16LE(FLAG_UTF8, 6);
    local.writeUInt16LE(method, 8);
    local.writeUInt16LE(DOS_TIME, 10);
    local.writeUInt16LE(DOS_DATE, 12);
    local.writeUInt32LE(crc, 14);
    local.writeUInt32LE(body.length, 18);
    local.writeUInt32LE(data.length, 22);
    local.writeUInt16LE(name.length, 26);
    local.writeUInt16LE(0, 28);           // no extra field
    locals.push(local, name, body);

    const central = Buffer.alloc(46);
    central.writeUInt32LE(SIG_CENTRAL, 0);
    central.writeUInt16LE((3 << 8) | 20, 4); // made by: Unix, 2.0
    central.writeUInt16LE(20, 6);
    central.writeUInt16LE(FLAG_UTF8, 8);
    central.writeUInt16LE(method, 10);
    central.writeUInt16LE(DOS_TIME, 12);
    central.writeUInt16LE(DOS_DATE, 14);
    central.writeUInt32LE(crc, 16);
    central.writeUInt32LE(body.length, 20);
    central.writeUInt32LE(data.length, 24);
    central.writeUInt16LE(name.length, 28);
    central.writeUInt16LE(0, 30);         // extra
    central.writeUInt16LE(0, 32);         // comment
    central.writeUInt16LE(0, 34);         // disk
    central.writeUInt16LE(0, 36);         // internal attrs
    central.writeUInt32LE(((0o100644 << 16) >>> 0), 38); // regular file, rw-r--r--
    central.writeUInt32LE(offset, 42);
    centrals.push(central, name);
    offset += 30 + name.length + body.length;
  }
  const cdSize = centrals.reduce((n, b) => n + b.length, 0);
  if (entries.length > 0xffff || offset > 0xffffffff || cdSize > 0xffffffff) throw new ZipError("too big for a v1 package (no ZIP64)");
  const end = Buffer.alloc(22);
  end.writeUInt32LE(SIG_END, 0);
  end.writeUInt16LE(entries.length, 8);
  end.writeUInt16LE(entries.length, 10);
  end.writeUInt32LE(cdSize, 12);
  end.writeUInt32LE(offset, 16);
  if (offset + cdSize + 22 > ZIP_LIMITS.packageBytes) throw new ZipError(`package is over ${ZIP_LIMITS.packageBytes} bytes`);
  return Buffer.concat([...locals, ...centrals, end]);
}

/**
 * Read a package archive. Returns [{ name, method, size, compressedSize,
 * data: Buffer }] in archive order. Throws ZipError on anything outside the
 * spec's subset. `limits.maxTotal` caps the total unpacked size.
 */
function readZip(buf, limits = {}) {
  const maxTotal = limits.maxTotal ?? ZIP_LIMITS.unpackedBytes;
  if (buf.length > ZIP_LIMITS.packageBytes) throw new ZipError(`package is over ${ZIP_LIMITS.packageBytes} bytes`);
  if (buf.length < 22) throw new ZipError("not a ZIP file (too short)");
  const endAt = buf.length - 22;
  if (buf.readUInt32LE(endAt) !== SIG_END) {
    throw new ZipError(buf.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06])) > 0
      ? "the archive has a comment or trailing bytes (not allowed)"
      : "not a ZIP file (no end of central directory)");
  }
  if (buf.readUInt16LE(endAt + 4) !== 0 || buf.readUInt16LE(endAt + 6) !== 0) throw new ZipError("multi-disk archives are not allowed");
  const count = buf.readUInt16LE(endAt + 10);
  if (buf.readUInt16LE(endAt + 8) !== count) throw new ZipError("inconsistent entry counts");
  const cdSize = buf.readUInt32LE(endAt + 12);
  const cdOffset = buf.readUInt32LE(endAt + 16);
  if (count === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) throw new ZipError("ZIP64 is not allowed");
  if (cdOffset + cdSize !== endAt) throw new ZipError("bytes between the central directory and its end record");

  if (count > (limits.maxEntries ?? ZIP_LIMITS.entries)) throw new ZipError(`more than ${limits.maxEntries ?? ZIP_LIMITS.entries} files`);
  // Reject a bomb from its directory before allocating any expanded payload.
  let declared = 0, cursor = cdOffset;
  for (let i = 0; i < count; i++) {
    if (cursor + 46 > endAt || buf.readUInt32LE(cursor) !== SIG_CENTRAL) throw new ZipError("damaged central directory");
    declared += buf.readUInt32LE(cursor + 24);
    if (declared > maxTotal) throw new ZipError(`unpacked size is over the ${maxTotal} byte limit`);
    cursor += 46 + buf.readUInt16LE(cursor + 28) + buf.readUInt16LE(cursor + 30) + buf.readUInt16LE(cursor + 32);
    if (cursor > endAt) throw new ZipError("damaged central directory");
  }
  if (cursor !== endAt) throw new ZipError("central directory size is wrong");
  const out = [];
  let p = cdOffset;
  let expectLocal = 0;
  let total = 0;
  for (let i = 0; i < count; i++) {
    if (p + 46 > endAt || buf.readUInt32LE(p) !== SIG_CENTRAL) throw new ZipError(`central directory entry ${i} is damaged`);
    const flags = buf.readUInt16LE(p + 8);
    const method = buf.readUInt16LE(p + 10);
    const crc = buf.readUInt32LE(p + 16);
    const csize = buf.readUInt32LE(p + 20);
    const usize = buf.readUInt32LE(p + 24);
    const nlen = buf.readUInt16LE(p + 28);
    const xlen = buf.readUInt16LE(p + 30);
    const clen = buf.readUInt16LE(p + 32);
    const extAttr = buf.readUInt32LE(p + 38);
    const lho = buf.readUInt32LE(p + 42);
    const nameBuf = buf.subarray(p + 46, p + 46 + nlen);
    const name = nameBuf.toString("utf8");
    p += 46 + nlen + xlen + clen;
    const where = JSON.stringify(name);
    if (!Buffer.from(name, "utf8").equals(nameBuf)) throw new ZipError(`${where}: name is not valid UTF-8`);
    if (flags & 0x1) throw new ZipError(`${where}: encrypted entries are not allowed`);
    if (flags & 0x8) throw new ZipError(`${where}: data descriptors are not allowed`);
    if (method !== 0 && method !== 8) throw new ZipError(`${where}: compression method ${method} is not allowed (only 0 and 8)`);
    const unixType = (extAttr >>> 16) & 0o170000;
    if (unixType === 0o120000) throw new ZipError(`${where}: symbolic links are not allowed`);
    if (name.endsWith("/")) throw new ZipError(`${where}: directory entries are not allowed (folders are implied by paths)`);
    if (lho !== expectLocal) throw new ZipError(`${where}: entries must be contiguous from the start of the file`);
    if (lho + 30 > cdOffset) throw new ZipError(`${where}: local header is out of bounds`);
    if (buf.readUInt32LE(lho) !== SIG_LOCAL) throw new ZipError(`${where}: local header is damaged`);
    const lnlen = buf.readUInt16LE(lho + 26);
    const lxlen = buf.readUInt16LE(lho + 28);
    if (buf.readUInt16LE(lho + 6) !== flags || buf.readUInt16LE(lho + 8) !== method || buf.readUInt32LE(lho + 14) !== crc ||
        buf.readUInt32LE(lho + 18) !== csize || buf.readUInt32LE(lho + 22) !== usize ||
        !buf.subarray(lho + 30, lho + 30 + lnlen).equals(nameBuf)) {
      throw new ZipError(`${where}: local header disagrees with the central directory`);
    }
    const start = lho + 30 + lnlen + lxlen;
    if (start + csize > cdOffset) throw new ZipError(`${where}: payload overlaps the central directory`);
    const body = buf.subarray(start, start + csize);
    if (body.length !== csize) throw new ZipError(`${where}: truncated`);
    expectLocal = start + csize;
    total += usize;
    if (total > maxTotal) throw new ZipError(`unpacked size is over the ${maxTotal} byte limit`);
    let data;
    if (method === 0) {
      if (csize !== usize) throw new ZipError(`${where}: stored entry sizes differ`);
      data = body; // Immutable view: avoid duplicating multi-gigabyte stored assets.
    } else {
      try { data = zlib.inflateRawSync(body, { maxOutputLength: Math.max(usize, 1) }); }
      catch (e) { throw new ZipError(`${where}: does not inflate to its declared size (${e.code || e.message})`); }
      if (data.length !== usize) throw new ZipError(`${where}: inflates to ${data.length} bytes, declared ${usize}`);
    }
    if ((zlib.crc32(data) >>> 0) !== crc) throw new ZipError(`${where}: CRC-32 mismatch`);
    out.push({ name, method, size: usize, compressedSize: csize, offset: lho, nameLength: lnlen, extraLength: lxlen, data });
  }
  if (p !== endAt) throw new ZipError("central directory size is wrong");
  if (expectLocal !== cdOffset) throw new ZipError("bytes between the last entry and the central directory");
  return out;
}
return { ZipError, ZIP_LIMITS, writeZip, readZip };
})();
// ---- tools/lib/schema.mjs --------------------------------------------------
const mod_schema = (() => {
// The subset of JSON Schema (2020-12) that spec/*.schema.json uses, so the
// schema files are the one source of truth for structure. Supports: type,
// const, enum, required, properties, additionalProperties (false or a
// schema), items, minItems, maxItems, uniqueItems, minLength, maxLength,
// pattern, minimum, maximum, $ref to "#/$defs/<name>". Anything else in a
// schema is a mistake here, so it throws.
const KNOWN = new Set(["$schema", "$id", "title", "description", "type", "const", "enum", "required", "properties",
  "additionalProperties", "items", "minItems", "maxItems", "uniqueItems", "minLength", "maxLength", "pattern",
  "minimum", "maximum", "$ref", "$defs"]);

function typeOf(v) {
  if (v === null) return "null";
  if (Array.isArray(v)) return "array";
  if (typeof v === "number") return Number.isInteger(v) ? "integer" : "number";
  return typeof v;
}

/** Returns a list of "path: problem" strings; empty means valid. */
function check(schema, value, root = schema, at = "") {
  const errs = [];
  const here = at || "(root)";
  for (const k of Object.keys(schema)) if (!KNOWN.has(k)) throw new Error(`schema keyword ${k} is not supported (${here})`);
  if (schema.$ref) {
    const m = schema.$ref.match(/^#\/\$defs\/(.+)$/);
    if (!m || !root.$defs || !root.$defs[m[1]]) throw new Error(`bad $ref ${schema.$ref}`);
    return check(root.$defs[m[1]], value, root, at);
  }
  const t = typeOf(value);
  if (schema.type) {
    const want = [].concat(schema.type);
    if (!want.includes(t) && !(t === "integer" && want.includes("number"))) {
      errs.push(`${here}: should be ${want.join(" or ")}, is ${t}`);
      return errs;
    }
  }
  if ("const" in schema && JSON.stringify(value) !== JSON.stringify(schema.const)) errs.push(`${here}: should be ${JSON.stringify(schema.const)}`);
  if (schema.enum && !schema.enum.some((e) => JSON.stringify(e) === JSON.stringify(value))) errs.push(`${here}: should be one of ${schema.enum.map((e) => JSON.stringify(e)).join(", ")}`);
  if (t === "string") {
    const len = [...value].length;
    if (schema.minLength != null && len < schema.minLength) errs.push(`${here}: shorter than ${schema.minLength}`);
    if (schema.maxLength != null && len > schema.maxLength) errs.push(`${here}: longer than ${schema.maxLength} (${len})`);
    if (schema.pattern && !new RegExp(schema.pattern, "u").test(value)) errs.push(`${here}: ${JSON.stringify(value)} doesn't match ${schema.pattern}`);
  }
  if (t === "number" || t === "integer") {
    if (schema.minimum != null && value < schema.minimum) errs.push(`${here}: below ${schema.minimum}`);
    if (schema.maximum != null && value > schema.maximum) errs.push(`${here}: above ${schema.maximum}`);
  }
  if (t === "array") {
    if (schema.minItems != null && value.length < schema.minItems) errs.push(`${here}: needs at least ${schema.minItems} item(s)`);
    if (schema.maxItems != null && value.length > schema.maxItems) errs.push(`${here}: more than ${schema.maxItems} items`);
    if (schema.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length) errs.push(`${here}: items must be unique`);
    if (schema.items) value.forEach((v, i) => errs.push(...check(schema.items, v, root, `${at}[${i}]`)));
  }
  if (t === "object") {
    for (const r of schema.required || []) if (!(r in value)) errs.push(`${here}: missing ${r}`);
    const props = schema.properties || {};
    for (const [k, v] of Object.entries(value)) {
      const sub = at ? `${at}.${k}` : k;
      if (props[k]) errs.push(...check(props[k], v, root, sub));
      else if (schema.additionalProperties === false) errs.push(`${here}: unknown field ${k}`);
      else if (schema.additionalProperties && typeof schema.additionalProperties === "object") errs.push(...check(schema.additionalProperties, v, root, sub));
    }
  }
  return errs;
}
return { check };
})();
// ---- tools/lib/package.mjs -------------------------------------------------
const mod_package = (() => {
// Pack and validate WispOS app packages (.wapp). The rules are the ones in
// spec/APP-PACKAGE.md; section names in messages point there.

const { writeZip, readZip, ZipError, ZIP_LIMITS } = mod_zip;
const { check } = mod_schema;

const FORMAT = "wispos.app/1";
const MIMETYPE = "application/vnd.wispos.app+zip";
const EXTENSION = ".wapp";
const LIMITS = ZIP_LIMITS;
const TOP = new Set(["app", "docs", "agent", "store", "locales", "native", "signature"]);
const SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;
const CHECKSUMS = "signature/checksums.json";
const SIGNATURE = "signature/signature.json";
const LOCALE_KEYS = new Set(["name", "summary", "description", "whatsNew", "keywords", "screenshots", "purchases"]);

const SCHEMA = {"$schema":"https://json-schema.org/draft/2020-12/schema","$id":"https://wisp-os.com/spec/app-package/1/manifest.schema.json","title":"WispOS app package manifest (manifest.json), format wispos.app/1","description":"The manifest at the root of every .wapp package. Rules a schema can't express (files exist, kind needs web or agent) are in spec/APP-PACKAGE.md and enforced by tools/wapp.mjs validate.","type":"object","additionalProperties":false,"required":["format","id","name","version","build","kind","category","summary","publisher","distribution","price","ageRating","languages","icon","screenshots","description","permissions","privacy"],"properties":{"format":{"const":"wispos.app/1","description":"Format and major version. A reader refuses any other value."},"id":{"type":"string","pattern":"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$","description":"Stable app id, 1-64 of [a-z0-9-], no leading or trailing dash. Never changes across versions. Used in wispos://install/<id>."},"name":{"type":"string","minLength":1,"maxLength":30,"description":"Display name, as on the Home Screen."},"version":{"type":"string","pattern":"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$","description":"What people see: MAJOR.MINOR.PATCH."},"build":{"type":"integer","minimum":1,"maximum":2147483647,"description":"Increases with every release of this id. An installer never replaces a build with a lower one."},"kind":{"enum":["game","tool","agent"],"description":"The store's shelf. game and tool need web or native; agent needs agent."},"category":{"type":"string","minLength":1,"maxLength":30},"summary":{"type":"string","minLength":1,"maxLength":80,"description":"One line under the name (the subtitle)."},"description":{"type":"array","minItems":1,"maxItems":20,"items":{"type":"string","minLength":1,"maxLength":2000},"description":"The product page's About text, one paragraph per item. Plain text."},"whatsNew":{"type":"string","maxLength":2000,"description":"Release notes for this version."},"keywords":{"type":"array","maxItems":20,"uniqueItems":true,"items":{"type":"string","minLength":1,"maxLength":40}},"publisher":{"type":"object","additionalProperties":false,"required":["id","name"],"properties":{"id":{"type":"string","pattern":"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$"},"name":{"type":"string","minLength":1,"maxLength":60},"email":{"type":"string","maxLength":200},"url":{"type":"string","pattern":"^https://"}}},"distribution":{"type":"object","additionalProperties":false,"required":["visibility"],"properties":{"visibility":{"enum":["public"],"description":"public: listed for everyone in the App Store."}}},"price":{"$ref":"#/$defs/price"},"ageRating":{"enum":["4+","9+","13+","16+","18+","12+","17+"],"description":"4+, 9+, 13+, 16+ or 18+. The old 12+ and 17+ stay valid and are read as 13+ and 18+."},"languages":{"type":"array","minItems":1,"uniqueItems":true,"items":{"type":"string","pattern":"^[a-z]{2,3}(-[A-Z]{2})?$"},"description":"BCP 47 tags. The first is the language of this manifest's text; others have locales/<tag>.json."},"copyright":{"type":"string","maxLength":120},"support":{"type":"object","additionalProperties":false,"properties":{"url":{"type":"string","pattern":"^https://"},"email":{"type":"string","maxLength":200}}},"minWispOS":{"type":"string","pattern":"^[0-9]+(\\.[0-9]+){0,2}$","description":"Oldest WispOS version that can run this package."},"icon":{"$ref":"#/$defs/path","description":"store/icon.svg, or a square PNG at least 512x512."},"screenshots":{"type":"array","maxItems":10,"items":{"type":"object","additionalProperties":false,"required":["image","caption"],"properties":{"image":{"$ref":"#/$defs/path"},"caption":{"type":"string","minLength":1,"maxLength":80},"device":{"enum":["desktop","phone"],"description":"Which store shows it: a desktop window's shot, or the app on a phone. Absent: desktop. The store on a phone shows the phone shots (the desktop ones when there are none), and on a desktop the desktop shots."}}}},"videos":{"type":"array","maxItems":3,"description":"App previews: short videos of the app, shown before the screenshots on its product page. MP4 (H.264) under store/, at most 60 seconds and 100 MB each. See \"Videos\" in APP-PACKAGE.md.","items":{"type":"object","additionalProperties":false,"required":["video","caption"],"properties":{"video":{"$ref":"#/$defs/path","description":"An .mp4 under store/."},"poster":{"$ref":"#/$defs/path","description":"The still shown before it plays: a PNG or JPEG under store/. Absent: the video's first frame."},"caption":{"type":"string","minLength":1,"maxLength":80},"device":{"enum":["desktop","phone"],"description":"As for screenshots: which store shows it. Absent: desktop."}}}},"web":{"type":"object","additionalProperties":false,"required":["entry"],"description":"Something that runs in the browser. WispOS opens entry in its own window, in a sandbox, with the runtime API (window.wispos).","properties":{"entry":{"$ref":"#/$defs/path","description":"An .html file under app/."},"window":{"type":"object","additionalProperties":false,"properties":{"width":{"type":"integer","minimum":200,"maximum":4096},"height":{"type":"integer","minimum":200,"maximum":4096},"resizable":{"type":"boolean"},"background":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$","description":"A one-look app's backdrop before first paint. WispOS also gives the window that color's appearance (dark or light), so an app with both modes uses backgrounds instead."},"backgrounds":{"type":"object","additionalProperties":false,"required":["dark","light"],"description":"An app with a light and a dark mode: its backdrop in each, before first paint. WispOS paints the one for its theme and leaves the window's appearance to the theme. See \"Light and dark\" in APP-PACKAGE.md.","properties":{"dark":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$"},"light":{"type":"string","pattern":"^#[0-9a-fA-F]{6}$"}}}}},"screens":{"type":"object","additionalProperties":false,"required":["mobile","desktop"],"description":"How the app wants each kind of screen. mobile: phones and tablets (WispOS on iPhone, Android, the phone page). desktop: a window on the Mac or PC. See \"Screens\" in APP-PACKAGE.md.","properties":{"mobile":{"type":"object","additionalProperties":false,"required":["orientation"],"properties":{"orientation":{"$ref":"#/$defs/orientation","description":"portrait or landscape: WispOS locks the screen to it while the app is open. any: it follows the device."},"fullscreen":{"type":"boolean","description":"true: no WispOS bar above the app and no status bar; the page is drawn edge to edge and keeps its controls inside env(safe-area-inset-*). WispOS leaves a close gesture. Default false."}}},"desktop":{"type":"object","additionalProperties":false,"required":["orientation","width","height"],"properties":{"orientation":{"$ref":"#/$defs/orientation","description":"The window's shape: landscape (wider than tall), portrait (taller than wide) or any. width and height must agree with it."},"width":{"type":"integer","minimum":200,"maximum":4096,"description":"The window's content width when it first opens, in CSS pixels."},"height":{"type":"integer","minimum":200,"maximum":4096},"minWidth":{"type":"integer","minimum":200,"maximum":4096,"description":"Smallest size the window can be dragged to. Default: 320 x 320."},"minHeight":{"type":"integer","minimum":200,"maximum":4096},"resizable":{"type":"boolean","description":"Default true."},"fullscreen":{"type":"boolean","description":"true: the window may go full screen (green button / F11). Default true."}}}}},"network":{"type":"array","uniqueItems":true,"maxItems":20,"items":{"type":"string","pattern":"^(https|wss)://(\\*\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+(:[0-9]+)?$"},"description":"Origins the app may reach. Empty or absent: none (offline). Needs the network permission when not empty. https:// for sites and APIs, wss:// for a WebSocket server (a multiplayer game's own server): scheme, host and an optional port, no path; *.example.com covers its subdomains. Never this computer over https or wss (localhost, 127.0.0.1). https and wss origins only."},"routines":{"type":"array","maxItems":4,"description":"What the app can bring the person on a schedule they choose (\"make it a routine\"). The manifest names what; the person picks the time and the days inside the app (wispos.routines.set), never the manifest. See \"Routines\" in APP-PACKAGE.md.","items":{"type":"object","additionalProperties":false,"required":["id","title","does"],"properties":{"id":{"type":"string","pattern":"^[a-z0-9][a-z0-9-]{0,31}$"},"title":{"type":"string","minLength":1,"maxLength":40,"description":"What arrives, as WispOS names it when it asks and in its list of routines."},"does":{"type":"string","enum":["open","card"],"description":"open: WispOS opens path at the time (and says so in Wisper's chat). card: WispOS posts the app's chat card of type card in Wisper's chat."},"path":{"$ref":"#/$defs/path","description":"does open: an .html file under app/."},"card":{"type":"string","pattern":"^[a-z0-9-]{1,32}$","description":"does card: a card type the app declares in app/chat-cards.json."}}}}}},"agent":{"type":"object","additionalProperties":false,"required":["folder"],"description":"An agent. folder is a WispOS shared-agent folder: card.json, the instructions .md it names (PROMPT.md by default) and knowledge/.","properties":{"folder":{"const":"agent"},"updates":{"type":"object","additionalProperties":false,"required":["git"],"properties":{"git":{"type":"string","minLength":1,"description":"Repo the installed agent pulls before each question (SHARED-AGENTS.md)."}}}}},"native":{"type":"object","additionalProperties":false,"description":"Native code for macOS and/or Windows (APP-PACKAGE.md \"Native apps\"), at least one platform, its files under native/<platform>/. WispOS installs it into its own app folder and opens it only from WispOS. A native app is free, unprotected and has no in-app purchases.","properties":{"macos":{"type":"object","additionalProperties":false,"required":["app","executable"],"description":"One app bundle: native/macos/<Name>.app with Contents/Info.plist and Contents/MacOS/<executable>.","properties":{"app":{"type":"string","maxLength":255,"pattern":"^native/macos/[A-Za-z0-9_-][A-Za-z0-9._-]*\\.app$"},"executable":{"type":"string","maxLength":255,"pattern":"^[A-Za-z0-9_-][A-Za-z0-9._-]*$"},"minimumSystem":{"type":"string","pattern":"^[0-9]{1,5}(\\.[0-9]{1,5}){0,2}$","description":"Oldest macOS it runs on, e.g. 13.0."}}},"windows":{"type":"object","additionalProperties":false,"required":["exe"],"description":"The program to start: an .exe under native/windows/, with the DLLs and files it needs beside it.","properties":{"exe":{"type":"string","maxLength":255,"pattern":"^native/windows/([A-Za-z0-9_-][A-Za-z0-9._-]*/)*[A-Za-z0-9_-][A-Za-z0-9._-]*\\.[eE][xX][eE]$"},"minimumSystem":{"type":"string","pattern":"^[0-9]{1,5}(\\.[0-9]{1,5}){0,2}$","description":"Oldest Windows it runs on, e.g. 10.0."}}}}},"docs":{"type":"array","maxItems":50,"items":{"type":"object","additionalProperties":false,"required":["title","path"],"properties":{"title":{"type":"string","minLength":1,"maxLength":60},"path":{"$ref":"#/$defs/path","description":"An .html or .md file under docs/. The first page is the help home."}}}},"purchases":{"type":"array","maxItems":100,"items":{"type":"object","additionalProperties":false,"required":["id","type","title","description","price"],"properties":{"id":{"type":"string","pattern":"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$","description":"Unique in this app. The full product id is <app id>/<id>."},"type":{"enum":["non-consumable","consumable","subscription"]},"title":{"type":"string","minLength":1,"maxLength":40},"description":{"type":"string","minLength":1,"maxLength":200},"price":{"$ref":"#/$defs/price"},"period":{"enum":["P1W","P1M","P3M","P6M","P1Y"],"description":"Subscriptions only: how often it renews."},"quantity":{"type":"integer","minimum":1,"maximum":10000,"description":"Consumables only: how many units one purchase grants."}}}},"permissions":{"type":"array","uniqueItems":true,"items":{"type":"object","additionalProperties":false,"required":["kind","reason"],"properties":{"kind":{"enum":["notifications","network","microphone","camera","clipboard","files","windows","calendar","location","photos"]},"reason":{"type":"string","minLength":1,"maxLength":200,"description":"Shown when WispOS asks, and on the product page."}}}},"privacy":{"type":"object","additionalProperties":false,"required":["collects","tracking"],"description":"The privacy label. collects empty means Data Not Collected.","properties":{"collects":{"type":"array","uniqueItems":true,"items":{"type":"object","additionalProperties":false,"required":["data","purpose","linked"],"properties":{"data":{"enum":["contact","identifiers","usage","diagnostics","content","purchases","location"]},"purpose":{"type":"string","minLength":1,"maxLength":200},"linked":{"type":"boolean","description":"Linked to the person's identity."}}}},"tracking":{"type":"boolean","description":"Used to track people across other companies' apps or sites."}}}},"$defs":{"orientation":{"enum":["portrait","landscape","any"]},"path":{"type":"string","minLength":1,"maxLength":255,"pattern":"^(?:app|docs|agent|store|locales)/(?:[A-Za-z0-9_-][A-Za-z0-9._-]*/)*[A-Za-z0-9_-][A-Za-z0-9._-]*$","description":"A file inside the package, relative to its root, under one of the content folders."},"price":{"type":"object","additionalProperties":false,"required":["amount","currency"],"properties":{"amount":{"type":"number","minimum":0,"maximum":10000,"description":"In major units (0.99 = 99 cents). 0 is free."},"currency":{"type":"string","pattern":"^[A-Z]{3}$"}}}}};

function hashBytes(b, algorithm = "sha256") {
  if (typeof b === "string") b = Buffer.from(b);
  const hash = crypto.createHash(algorithm);
  for (let offset = 0; offset < b.length; offset += 64 * 1024 ** 2) hash.update(b.subarray(offset, offset + 64 * 1024 ** 2));
  return hash.digest("hex");
}
const sha256 = hashBytes;

// fs.readFileSync refuses files >= 2 GiB, even when Buffer supports them.
function readBytes(file, maxBytes = LIMITS.packageBytes) {
  const fd = fs.openSync(file, "r");
  try {
    const size = fs.fstatSync(fd).size;
    if (size > maxBytes) throw new Error(`${file}: over ${maxBytes} bytes`);
    const buf = Buffer.allocUnsafe(size);
    for (let offset = 0; offset < size;) {
      const n = fs.readSync(fd, buf, offset, Math.min(64 * 1024 ** 2, size - offset), offset);
      if (!n) throw new Error(`${file}: truncated while reading`);
      offset += n;
    }
    return buf;
  } finally { fs.closeSync(fd); }
}

function writeBytes(file, buf) {
  const fd = fs.openSync(file, "w");
  try {
    for (let offset = 0; offset < buf.length;) {
      const n = fs.writeSync(fd, buf, offset, Math.min(64 * 1024 ** 2, buf.length - offset));
      if (!n) throw new Error(`${file}: could not write bytes`);
      offset += n;
    }
  } finally { fs.closeSync(fd); }
}

/** "Path rules": the name of every entry. Returns a problem or null. */
function pathProblem(name) {
  if (Buffer.byteLength(name) > LIMITS.pathBytes) return "longer than 255 bytes";
  if (name.includes("\\")) return "uses a backslash";
  if (name.startsWith("/")) return "is absolute";
  const segs = name.split("/");
  for (const s of segs) {
    if (s === "" ) return "has an empty segment";
    if (s === "." || s === "..") return "has a . or .. segment";
    if (!SEGMENT.test(s)) return `segment ${JSON.stringify(s)} uses characters outside [A-Za-z0-9._-] or starts with a dot`;
  }
  if (segs.length === 1 && name !== "mimetype" && name !== "manifest.json") return "is a file at the root other than mimetype and manifest.json";
  if (segs.length > 1 && !TOP.has(segs[0])) return `is under ${segs[0]}/, which isn't a package folder`;
  return null;
}

function pngSize(buf) {
  if (buf.length < 24 || buf.readUInt32BE(0) !== 0x89504e47 || buf.toString("ascii", 12, 16) !== "IHDR") return null;
  return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
}
function jpegOk(buf) { return buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8; }

// Videos ("Videos"): MP4 boxes, enough to read what the store needs. Returns
// { width, height, seconds, codec, faststart } or { error }.
function boxes(buf, start, end) {
  const out = [];
  for (let at = start; at + 8 <= end;) {
    let size = buf.readUInt32BE(at), head = 8;
    const type = buf.toString("latin1", at + 4, at + 8);
    if (size === 1) {
      if (at + 16 > end) return null;
      size = Number(buf.readBigUInt64BE(at + 8)); head = 16;
    } else if (size === 0) size = end - at;
    if (size < head || at + size > end) return null;
    out.push({ type, start: at + head, end: at + size, at });
    at += size;
  }
  return out;
}
const child = (buf, box, type) => (box && boxes(buf, box.start, box.end) || []).find((b) => b.type === type) || null;
function mp4Info(buf) {
  const top = buf.length >= 8 ? boxes(buf, 0, buf.length) : null;
  if (!top || top[0]?.type !== "ftyp") return { error: "is not an MP4 file" };
  const moov = top.find((b) => b.type === "moov"), mdat = top.find((b) => b.type === "mdat");
  if (!moov) return { error: "has no moov box (not a finished MP4)" };
  const mvhd = child(buf, moov, "mvhd");
  if (!mvhd) return { error: "has no movie header" };
  const v1 = buf[mvhd.start] === 1, o = mvhd.start + (v1 ? 20 : 12);
  if (o + (v1 ? 12 : 8) > mvhd.end) return { error: "has a short movie header" };
  const scale = buf.readUInt32BE(o), length = v1 ? Number(buf.readBigUInt64BE(o + 4)) : buf.readUInt32BE(o + 4);
  for (const trak of boxes(buf, moov.start, moov.end).filter((b) => b.type === "trak")) {
    const mdia = child(buf, trak, "mdia"), hdlr = child(buf, mdia, "hdlr");
    if (!hdlr || buf.toString("latin1", hdlr.start + 8, hdlr.start + 12) !== "vide") continue;
    const stsd = child(buf, child(buf, child(buf, mdia, "minf"), "stbl"), "stsd");
    const entry = stsd && boxes(buf, stsd.start + 8, stsd.end)?.[0];
    const tkhd = child(buf, trak, "tkhd");
    let width = 0, height = 0;
    if (tkhd) {
      const w = tkhd.start + (buf[tkhd.start] === 1 ? 88 : 76);
      if (w + 8 <= tkhd.end) { width = Math.round(buf.readUInt32BE(w) / 65536); height = Math.round(buf.readUInt32BE(w + 4) / 65536); }
    }
    return { width, height, seconds: scale ? length / scale : 0, codec: entry ? entry.type : "", faststart: !mdat || moov.at < mdat.at };
  }
  return { error: "has no video track" };
}
const VIDEO_LIMITS = Object.freeze({ count: 3, bytes: 100 * 1024 ** 2, seconds: 60 });

function checkCard(card, manifest, files, errors, warnings) {
  const where = "agent/card.json";
  const known = ["card", "name", "title", "team", "owner", "description", "knows", "askers", "model", "prompt", "knowledge", "store"];
  if (card.card !== 1) errors.push(`${where}: card must be 1 (SHARED-AGENTS.md card v1)`);
  if (typeof card.name !== "string" || !/^[a-z0-9-]{1,40}$/.test(card.name)) errors.push(`${where}: name must be [a-z0-9-], at most 40`);
  else if (card.name !== manifest.id) errors.push(`${where}: name "${card.name}" must equal the app id "${manifest.id}"`);
  for (const k of ["team", "owner"]) if (typeof card[k] !== "string" || !card[k].trim()) errors.push(`${where}: ${k} is required`);
  for (const k of ["knows", "askers"]) if (!Array.isArray(card[k]) || !card[k].length || !card[k].every((s) => typeof s === "string" && s.trim())) errors.push(`${where}: ${k} must be a non-empty list of strings`);
  if (card.model != null && !["haiku", "sonnet", "opus"].includes(card.model)) errors.push(`${where}: model must be haiku, sonnet or opus`);
  for (const k of Object.keys(card)) if (!known.includes(k)) warnings.push(`${where}: unknown field ${k}`);
  const prompt = "agent/" + (card.prompt || "PROMPT.md");
  if (pathProblem(prompt)) errors.push(`${where}: prompt path ${prompt} ${pathProblem(prompt)}`);
  else if (!files.has(prompt)) errors.push(`${where}: its instructions file ${prompt} is missing`);
  else if (!prompt.endsWith(".md")) errors.push(`${where}: instructions must be a .md file`);
  const kn = "agent/" + (card.knowledge || "knowledge") + "/";
  if (![...files.keys()].some((f) => f.startsWith(kn))) warnings.push(`${where}: no files under ${kn}`);
}

/**
 * Validate a package. Never throws for a bad package: returns
 * { ok, errors, warnings, manifest, files: Map<name, Buffer>, info }.
 */
function validate(buf) {
  const errors = [];
  const warnings = [];
  const info = { bytes: buf.length, sha256: sha256(buf), signed: false };
  const done = (manifest = null, files = new Map()) => ({ ok: errors.length === 0, errors, warnings, manifest, files, info });

  if (buf.length > LIMITS.packageBytes) { errors.push(`package is over ${LIMITS.packageBytes} bytes`); return done(); }
  let entries;
  try { entries = readZip(buf, { maxTotal: LIMITS.unpackedBytes, maxEntries: LIMITS.entries }); }
  catch (e) { errors.push(`Container: ${e instanceof ZipError ? e.message : "unreadable: " + e.message}`); return done(); }
  info.entries = entries.length;
  info.unpackedBytes = entries.reduce((n, e) => n + e.size, 0);
  if (entries.length > LIMITS.entries) errors.push(`more than ${LIMITS.entries} files`);

  // Container: mimetype first, stored, no extra field, so byte 30 starts
  // "mimetype" and byte 38 the media type (file-type sniffers rely on it).
  const first = entries[0];
  if (!first || first.name !== "mimetype") errors.push("Container: the first entry must be mimetype");
  else {
    if (first.method !== 0 || first.extraLength !== 0) errors.push("Container: mimetype must be stored (not compressed) with no extra field");
    if (first.data.toString("latin1") !== MIMETYPE) errors.push(`Container: mimetype must contain exactly ${MIMETYPE}`);
  }
  if (!entries[1] || entries[1].name !== "manifest.json") errors.push("Container: the second entry must be manifest.json");

  const files = new Map();
  const lower = new Set();
  for (const e of entries) {
    const p = pathProblem(e.name);
    if (p) errors.push(`Path rules: ${JSON.stringify(e.name)} ${p}`);
    if (lower.has(e.name.toLowerCase())) errors.push(`Path rules: ${JSON.stringify(e.name)} appears twice (names are compared case-insensitively)`);
    lower.add(e.name.toLowerCase());
    files.set(e.name, e.data);
  }
  if (!files.has("manifest.json")) { errors.push("manifest.json is missing"); return done(null, files); }

  let manifest;
  const raw = files.get("manifest.json");
  if (raw[0] === 0xef && raw[1] === 0xbb && raw[2] === 0xbf) errors.push("manifest.json: no byte-order mark");
  try { manifest = JSON.parse(raw.toString("utf8")); }
  catch (e) { errors.push(`manifest.json is not JSON: ${e.message}`); return done(null, files); }
  if (manifest?.format !== FORMAT) { errors.push(`manifest.json: format must be "${FORMAT}" (found ${JSON.stringify(manifest?.format)}); this reader knows only v1`); return done(manifest, files); }
  for (const e of check(SCHEMA, manifest)) errors.push(`manifest.json: ${e}`);
  if (errors.length) return done(manifest, files);

  semantic(manifest, files, errors, warnings);
  integrity(files, errors, info);
  return done(manifest, files);
}

// Screens: the desktop size agrees with its orientation and its minimums, and
// with web.window (which older WispOS reads), so every host opens one size.
function screenErrors(web) {
  const d = web.screens && web.screens.desktop, out = [];
  if (!d) return out;
  if (d.orientation === "landscape" && d.width < d.height) out.push(`screens.desktop: a landscape window is wider than tall (${d.width}x${d.height})`);
  if (d.orientation === "portrait" && d.height < d.width) out.push(`screens.desktop: a portrait window is taller than wide (${d.width}x${d.height})`);
  if (d.minWidth > d.width || d.minHeight > d.height) out.push("screens.desktop: minWidth/minHeight are larger than the window");
  const w = web.window || {};
  if ((w.width != null && w.width !== d.width) || (w.height != null && w.height !== d.height)) out.push(`screens.desktop: ${d.width}x${d.height} disagrees with web.window ${w.width}x${w.height}`);
  if (w.resizable != null && d.resizable != null && w.resizable !== d.resizable) out.push("screens.desktop: resizable disagrees with web.window");
  return out;
}

// Light and dark: one backdrop or a pair, not both (a single background pins the window to its look).
function themeErrors(web) {
  const w = web.window || {};
  return w.background && w.backgrounds ? ["web.window: background (one look) and backgrounds (light and dark) can't both be given"] : [];
}

// Routines: each id once; open names a page in the package, card a card type
// the app declares. The time is never here: the person picks it in the app.
function routineErrors(web, files, need, errors) {
  const seen = new Set();
  let cards = null;
  for (const r of web.routines || []) {
    if (seen.has(r.id)) errors.push(`web.routines: ${r.id} is listed twice`);
    seen.add(r.id);
    if (r.does === "open") {
      if (!r.path) errors.push(`web.routines: ${r.id} opens a page, so it needs path`);
      else need(r.path, `web.routines ${r.id}`, "app", [".html"]);
      if (r.card) errors.push(`web.routines: ${r.id} opens a page; card is for does "card"`);
    } else {
      if (r.path) errors.push(`web.routines: ${r.id} posts a card; path is for does "open"`);
      if (cards === null) {
        try { cards = (JSON.parse(files.get("app/chat-cards.json")?.toString("utf8") || "{}").cards || []).map((c) => c.type); } catch { cards = []; }
      }
      if (!r.card) errors.push(`web.routines: ${r.id} posts a card, so it needs card`);
      else if (!cards.includes(r.card)) errors.push(`web.routines: ${r.id} posts card "${r.card}", which app/chat-cards.json doesn't declare`);
    }
  }
}

// Native apps (spec/APP-PACKAGE.md "Native apps"): one macOS bundle and/or
// one Windows program, every file under native/<platform>/, free, unprotected,
// no in-app purchases. The same rules as WispOS's reader (native_app.rs).
function nativeErrors(m, files, errors, warnings) {
  const names = [...files.keys()];
  const under = (p) => names.filter((f) => f.startsWith(p));
  const n = m.native;
  if (!n) {
    if (under("native/").length) errors.push("native/ has files but the manifest has no native");
    return;
  }
  const platforms = Object.keys(n);
  if (!platforms.length) errors.push("native names at least one of macos, windows");
  if (m.price.amount > 0 || m.protection || (m.purchases || []).length || files.has("signature/encryption.json"))
    errors.push("native: a native app is free, unencrypted and has no in-app purchases (its code runs from disk, where WispOS can't lock it)");
  if (n.macos) {
    const app = n.macos.app;
    for (const need of [`${app}/Contents/Info.plist`, `${app}/Contents/MacOS/${n.macos.executable}`])
      if (!files.has(need)) errors.push(`native.macos: ${need} is not in the package`);
    const stray = under("native/macos/").find((f) => !f.startsWith(app + "/"));
    if (stray) errors.push(`native.macos: ${stray} is outside ${app} (one bundle per platform)`);
  }
  if (n.windows && !files.has(n.windows.exe)) errors.push(`native.windows: ${n.windows.exe} is not in the package`);
  const stray = under("native/").find((f) => !platforms.some((p) => f.startsWith(`native/${p}/`)));
  if (stray) errors.push(`${stray} is under native/ but not in a platform the manifest names`);
  if (!m.minWispOS) warnings.push("native: set minWispOS (0.2.17 or later): an older WispOS refuses a native app as a field it doesn't know");
}

// The public App Store is web-only for now (owner, 2026-10-14): a package that
// carries native code is refused there. Native apps stay allowed for his own
// installs and private shares.
// Revisited once the store has a human review step (docs/native-review.md).
// Same words as WispOS's Submit (WispOS-app submit.rs NATIVE_NOT_PUBLIC).
const NATIVE_NOT_PUBLIC = "The public App Store takes web apps only for now; native apps can be shared privately";
const publicStoreErrors = (m) => (m?.native ? [NATIVE_NOT_PUBLIC] : []);

function semantic(m, files, errors, warnings) {
  const need = (p, what, under, exts) => {
    if (!p.startsWith(under + "/")) { errors.push(`${what}: ${p} must be under ${under}/`); return false; }
    if (exts && !exts.some((x) => p.toLowerCase().endsWith(x))) { errors.push(`${what}: ${p} must be ${exts.join(" or ")}`); return false; }
    if (!files.has(p)) { errors.push(`${what}: ${p} is not in the package`); return false; }
    return true;
  };
  // Kinds: a game or tool runs as a page (web) or as native code (native), or both.
  if ((m.kind === "game" || m.kind === "tool") && !m.web && !m.native) errors.push(`Kinds: a ${m.kind} needs web or native`);
  if (m.kind === "agent" && !m.agent) errors.push("Kinds: an agent needs agent");
  // Web
  if (m.web) {
    need(m.web.entry, "web.entry", "app", [".html"]);
    if ((m.web.network || []).length && !m.permissions.some((p) => p.kind === "network")) errors.push("web.network lists origins, so permissions needs network");
    for (const o of m.web.network || []) if (/^http:\/\//.test(o)) errors.push(`web.network: ${o} is http; an App Store app reaches https and wss origins only`);
    // A server on the internet, never this computer over https or wss (the pattern lets an IP or a name under .localhost through).
    for (const o of m.web.network || []) if (/^(https|wss):\/\/(\*\.)?(([a-z0-9-]+\.)*localhost|127(\.[0-9]+){3}|0(\.0){3})(:[0-9]+)?$/.test(o)) errors.push(`web.network: ${o} is this computer; a game's server or an API is on the internet`);
    errors.push(...screenErrors(m.web), ...themeErrors(m.web));
    routineErrors(m.web, files, need, errors);
  }
  if (!m.web && [...files.keys()].some((f) => f.startsWith("app/"))) errors.push("app/ has files but the manifest has no web");
  // Store assets
  if (need(m.icon, "icon", "store", [".svg", ".png"])) {
    const b = files.get(m.icon);
    if (m.icon.endsWith(".png")) {
      const s = pngSize(b);
      if (!s) errors.push(`icon: ${m.icon} is not a PNG`);
      else if (s.width !== s.height || s.width < 512) errors.push(`icon: PNG must be square and at least 512x512 (is ${s.width}x${s.height})`);
    } else {
      const t = b.toString("utf8");
      if (!/<svg[\s>]/.test(t)) errors.push(`icon: ${m.icon} is not an SVG`);
      if (/<script|\son[a-z]+\s*=|(?:href|src)\s*=\s*["']\s*(?:https?:|javascript:)/i.test(t)) errors.push(`icon: ${m.icon} must not script or load anything`);
    }
  }
  if (!m.screenshots.length && !(m.videos || []).length) warnings.push("screenshots: none; the product page will have no preview");
  for (const s of m.screenshots) {
    if (!need(s.image, "screenshots", "store", [".png", ".jpg", ".jpeg"])) continue;
    const b = files.get(s.image);
    if (s.image.endsWith(".png")) {
      const sz = pngSize(b);
      if (!sz) errors.push(`screenshots: ${s.image} is not a PNG`);
      else if (Math.min(sz.width, sz.height) < 320) errors.push(`screenshots: ${s.image} is smaller than 320px on a side`);
      else if (s.device === "phone" && sz.width > sz.height && m.web?.screens?.mobile?.orientation === "portrait")
        errors.push(`screenshots: ${s.image} is a phone shot on its side, but the app holds a phone upright (web.screens.mobile)`);
    } else if (!jpegOk(b)) errors.push(`screenshots: ${s.image} is not a JPEG`);
  }
  // Videos: app previews, before the screenshots on the product page.
  for (const v of m.videos || []) {
    if (v.poster && need(v.poster, "videos: poster", "store", [".png", ".jpg", ".jpeg"])) {
      const b = files.get(v.poster), sz = v.poster.endsWith(".png") ? pngSize(b) : null;
      if (v.poster.endsWith(".png") ? !sz : !jpegOk(b)) errors.push(`videos: ${v.poster} is not a ${v.poster.endsWith(".png") ? "PNG" : "JPEG"}`);
      else if (sz && Math.min(sz.width, sz.height) < 320) errors.push(`videos: ${v.poster} is smaller than 320px on a side`);
    }
    if (!need(v.video, "videos", "store", [".mp4"])) continue;
    const b = files.get(v.video), info = mp4Info(b);
    if (b.length > VIDEO_LIMITS.bytes) errors.push(`videos: ${v.video} is over ${VIDEO_LIMITS.bytes / 1024 ** 2} MB; shorten it or lower its bitrate`);
    if (info.error) { errors.push(`videos: ${v.video} ${info.error}`); continue; }
    if (!/^avc[13]$/.test(info.codec)) errors.push(`videos: ${v.video} is ${info.codec || "an unknown codec"}; the store plays H.264 (avc1) MP4 only`);
    if (info.seconds > VIDEO_LIMITS.seconds) errors.push(`videos: ${v.video} is ${Math.round(info.seconds)} seconds; at most ${VIDEO_LIMITS.seconds}`);
    if (info.seconds < 1) errors.push(`videos: ${v.video} is under a second long`);
    if (info.width && Math.min(info.width, info.height) < 320) errors.push(`videos: ${v.video} is smaller than 320px on a side (${info.width}x${info.height})`);
    if (!info.faststart) warnings.push(`videos: ${v.video} keeps its index at the end, so it can't start until it has all downloaded; re-encode with -movflags +faststart`);
  }
  // Docs
  for (const d of m.docs || []) need(d.path, "docs", "docs", [".html", ".md"]);
  if (!(m.docs || []).length && [...files.keys()].some((f) => f.startsWith("docs/"))) warnings.push("docs/ has files but manifest.docs lists none");
  // Remote code: nothing under app/ or docs/ may load scripts, styles or frames from the internet.
  for (const [name, b] of files) {
    if (!/^(app|docs)\/.*\.(html|htm|js|css|svg)$/i.test(name)) continue;
    const t = b.toString("utf8");
    if (/<(script|iframe|img|link|source|video|audio)\b[^>]*\s(src|href)\s*=\s*["']?\s*(https?:)?\/\//i.test(t) || /@import\s+(url\()?["']?(https?:)?\/\//i.test(t) || /\bimport\s*\(?\s*["']https?:/i.test(t)) {
      errors.push(`Web content: ${name} loads something from the internet; packages carry everything they run`);
    }
  }
  // Agent
  if (m.agent) {
    const cardRaw = files.get("agent/card.json");
    if (!cardRaw) errors.push("agent: agent/card.json is missing");
    else {
      let card = null;
      try { card = JSON.parse(cardRaw.toString("utf8")); } catch (e) { errors.push(`agent/card.json is not JSON: ${e.message}`); }
      if (card) checkCard(card, m, files, errors, warnings);
    }
  } else if ([...files.keys()].some((f) => f.startsWith("agent/"))) errors.push("agent/ has files but the manifest has no agent");
  nativeErrors(m, files, errors, warnings);
  // Purchases
  const ids = new Set();
  for (const p of m.purchases || []) {
    if (ids.has(p.id)) errors.push(`purchases: ${p.id} appears twice`);
    ids.add(p.id);
    if (!(p.price.amount > 0)) errors.push(`purchases: ${p.id} must cost something (a free item belongs in the app)`);
    if (p.price.currency !== m.price.currency) errors.push(`purchases: ${p.id} is in ${p.price.currency}, the app in ${m.price.currency}`);
    if ((p.type === "subscription") !== ("period" in p)) errors.push(`purchases: ${p.id}: period is for subscriptions, and every subscription needs one`);
    if ("quantity" in p && p.type !== "consumable") errors.push(`purchases: ${p.id}: quantity is for consumables only`);
  }
  if ((m.purchases || []).length && !m.web) errors.push("purchases need web (they are bought from inside the app)");
  // Permissions
  const kinds = m.permissions.map((p) => p.kind);
  if (new Set(kinds).size !== kinds.length) errors.push("permissions: each kind once");
  // Languages / locales
  const want = new Set(m.languages.slice(1).map((l) => `locales/${l}.json`));
  for (const name of files.keys()) {
    if (!name.startsWith("locales/")) continue;
    if (!want.has(name)) { errors.push(`locales: ${name} isn't in languages`); continue; }
    try {
      const loc = JSON.parse(files.get(name).toString("utf8"));
      for (const k of Object.keys(loc)) if (!LOCALE_KEYS.has(k)) errors.push(`locales: ${name} has unknown field ${k}`);
    } catch (e) { errors.push(`locales: ${name} is not JSON`); }
  }
  for (const w of want) if (!files.has(w)) errors.push(`locales: ${w} is missing`);
}

function integrity(files, errors, info) {
  const raw = files.get(CHECKSUMS);
  if (!raw) { errors.push(`Integrity: ${CHECKSUMS} is missing`); return; }
  let sums;
  try { sums = JSON.parse(raw.toString("utf8")); } catch { errors.push(`Integrity: ${CHECKSUMS} is not JSON`); return; }
  if (sums.algorithm !== "sha256" || !sums.files || typeof sums.files !== "object") { errors.push(`Integrity: ${CHECKSUMS} must be { "algorithm": "sha256", "files": {...} }`); return; }
  const covered = [...files.keys()].filter((f) => !f.startsWith("signature/"));
  for (const f of covered) {
    if (!(f in sums.files)) errors.push(`Integrity: ${f} has no checksum`);
    else if (sums.files[f] !== sha256(files.get(f))) errors.push(`Integrity: ${f} doesn't match its checksum (changed after packing)`);
  }
  for (const f of Object.keys(sums.files)) if (!files.has(f)) errors.push(`Integrity: ${f} is listed but not in the package`);
  for (const f of files.keys()) if (f.startsWith("signature/") && f !== CHECKSUMS && f !== SIGNATURE) errors.push(`Integrity: ${f} isn't allowed under signature/`);
  const sigRaw = files.get(SIGNATURE);
  if (!sigRaw) return;
  try {
    const sig = JSON.parse(sigRaw.toString("utf8"));
    if (sig.algorithm !== "ed25519") throw new Error("algorithm must be ed25519");
    const der = Buffer.from(sig.publicKey, "base64");
    const key = crypto.createPublicKey({ key: der, format: "der", type: "spki" });
    if (!crypto.verify(null, raw, key, Buffer.from(sig.signature, "base64"))) throw new Error("the signature doesn't match checksums.json");
    info.signed = true;
    info.keyId = keyId(der);
  } catch (e) { errors.push(`Integrity: ${SIGNATURE}: ${e.message}`); }
}

function keyId(spkiDer) { return sha256(spkiDer).slice(0, 16); }

/** Every file a source folder contributes, as [name, Buffer], dotfiles skipped. */
function readSource(dir) {
  const out = [];
  const walk = (rel) => {
    for (const ent of fs.readdirSync(path.join(dir, rel), { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
      if (ent.name.startsWith(".")) continue;
      const r = rel ? `${rel}/${ent.name}` : ent.name;
      if (ent.isDirectory()) walk(r);
      else if (ent.isFile()) out.push([r, readBytes(path.join(dir, r), Math.min(LIMITS.unpackedBytes, 0xfffffffe))]);
      else throw new Error(`${r}: only plain files and folders can be packed`);
    }
  };
  walk("");
  return out;
}

/**
 * Pack a source folder (manifest.json + app/ docs/ agent/ store/ locales/)
 * into a package. `privateKey`: optional ed25519 KeyObject to sign with.
 * Returns { buf, result } where result is validate(buf); throws if invalid.
 */
function pack(dir, { privateKey } = {}) {
  const src = readSource(dir).filter(([n]) => n !== "mimetype" && !n.startsWith("signature/"));
  if (!src.some(([n]) => n === "manifest.json")) throw new Error(`${dir}: no manifest.json`);
  const bad = src.map(([n]) => [n, pathProblem(n)]).filter(([, p]) => p);
  if (bad.length) throw new Error(bad.map(([n, p]) => `${n} ${p}`).join("\n"));
  // Re-serialize the manifest so every package's manifest is formatted the same.
  const manifest = JSON.parse(src.find(([n]) => n === "manifest.json")[1].toString("utf8"));
  const body = [["manifest.json", Buffer.from(JSON.stringify(manifest, null, 2) + "\n")],
    ...src.filter(([n]) => n !== "manifest.json").sort(([a], [b]) => (Buffer.from(a) < Buffer.from(b) ? -1 : 1))];
  const all = [["mimetype", Buffer.from(MIMETYPE, "latin1")], ...body];
  const files = {};
  for (const [n, b] of all) files[n] = sha256(b);
  const checksums = Buffer.from(JSON.stringify({ algorithm: "sha256", files }, null, 2) + "\n");
  const entries = [{ name: "mimetype", data: all[0][1], store: true }, ...body.map(([name, data]) => ({ name, data })), { name: CHECKSUMS, data: checksums }];
  if (privateKey) {
    const der = crypto.createPublicKey(privateKey).export({ format: "der", type: "spki" });
    const signature = crypto.sign(null, checksums, privateKey).toString("base64");
    entries.push({ name: SIGNATURE, data: Buffer.from(JSON.stringify({ algorithm: "ed25519", keyId: keyId(der), publicKey: der.toString("base64"), signature }, null, 2) + "\n") });
  }
  const buf = writeZip(entries);
  const result = validate(buf);
  if (!result.ok) throw new Error(`${dir} doesn't make a valid package:\n  ` + result.errors.join("\n  "));
  return { buf, result };
}

function fileName(m) { return `${m.id}-${m.version}${EXTENSION}`; }
return { FORMAT, MIMETYPE, EXTENSION, LIMITS, SCHEMA, hashBytes, readBytes, writeBytes, pathProblem, mp4Info, VIDEO_LIMITS, validate, nativeErrors, NATIVE_NOT_PUBLIC, publicStoreErrors, keyId, readSource, pack, fileName };
})();
// ---- tools/lib/starter.mjs -------------------------------------------------
const mod_starter = (() => {
// The folder `wapp new` writes: the smallest app that packs, installs and keeps
// its state. Same app as "Make your .wapp yourself" on wisp-os.com's Building
// apps page (Tally), with the id and name filled in.

/** Files for a new app, as [path, text]. `id` is [a-z0-9-], `name` is what people see. */
function starter(id, name) {
  const manifest = {
    format: "wispos.app/1",
    id,
    name,
    version: "1.0.0",
    build: 1,
    kind: "tool",
    category: "Productivity",
    summary: "A counter that remembers where you left it.",
    description: ["Tap to count. The number is kept between launches."],
    publisher: { id: "me", name: "Me" },
    distribution: { visibility: "public" },
    price: { amount: 0, currency: "USD" },
    ageRating: "4+",
    languages: ["en"],
    icon: "store/icon.svg",
    screenshots: [],
    web: {
      entry: "app/index.html",
      window: { width: 420, height: 560, resizable: true, backgrounds: { dark: "#111318", light: "#f4f4f6" } },
      screens: {
        mobile: { orientation: "portrait", fullscreen: false },
        desktop: { orientation: "portrait", width: 420, height: 560, minWidth: 320, minHeight: 400, resizable: true },
      },
    },
    docs: [{ title: `Using ${name}`, path: "docs/index.md" }],
    permissions: [],
    privacy: { collects: [], tracking: false },
  };
  const html = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
  return [
    ["manifest.json", JSON.stringify(manifest, null, 2) + "\n"],
    ["app/index.html", `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="color-scheme" content="light dark">
<title>${html(name)}</title>
<style>
  body { margin: 0; height: 100vh; display: grid; place-items: center; font: 16px system-ui;
         background: #f4f4f6; color: #111318; box-sizing: border-box;
         padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left); }
  @media (prefers-color-scheme: dark) { body { background: #111318; color: #f4f4f6; } }
  button { font: 600 clamp(48px, 20vw, 120px) system-ui; min-width: 60vw; padding: 24px;
           border-radius: 24px; border: 0; background: #7b6cff; color: #fff; }
</style>
</head>
<body>
<button id="n">0</button>
<script src="app.js"></script>
</body>
</html>
`],
    ["app/app.js", `// Keeps the count in wispos.storage, and still counts in a plain browser.
const button = document.getElementById("n");
const store = window.wispos ? window.wispos.storage : null;
let count = 0;
if (store) store.get("count").then((v) => { count = v || 0; button.textContent = count; });
button.addEventListener("click", () => {
  count += 1;
  button.textContent = count;
  if (store) store.set("count", count);
});
`],
    ["docs/index.md", `# Using ${name}\n\nTap the number to add one. ${name} keeps the count between launches.\n`],
    ["store/icon.svg", `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#7b6cff"/><text x="256" y="330" font-family="system-ui" font-size="240" font-weight="700" fill="#fff" text-anchor="middle">1</text></svg>\n`],
  ];
}
return { starter };
})();

// ---- tools/wapp.mjs ---------------------------------------------------------

const { writeBytes, readBytes, pack, validate, fileName, EXTENSION, publicStoreErrors } = mod_package;
const { starter } = mod_starter;

const VERSION = "1.0.0";
const readRuntime = () => "/*\n * Reference implementation of the app runtime API (spec/APP-PACKAGE.md,\n * \"Runtime API\"), used by `node tools/wapp.mjs run`. WispOS injects its own\n * window.wispos before the app's scripts run; this file shows the shape and\n * behavior an app can rely on.\n *\n * Here everything is local to the browser: storage is localStorage under a\n * per-app prefix, and purchases are TEST purchases: a sheet asks, no money\n * moves, and what you \"bought\" is remembered in localStorage.\n *\n * Expects window.__WISPOS_MANIFEST__ (the package's manifest.json) to be set\n * before this script runs.\n */\n(function () {\n  \"use strict\";\n  var m = window.__WISPOS_MANIFEST__;\n  if (!m || window.wispos) return;\n  var NS = \"wispos:\" + m.id + \":\";\n  var products = (m.purchases || []).slice();\n  var perms = (m.permissions || []).map(function (p) { return p.kind; });\n  var routines = (m.web && m.web.routines) || [];\n  function routineOf(id) { return routines.filter(function (r) { return r.id === id; })[0]; }\n\n  function read(k, d) { try { var v = localStorage.getItem(NS + k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } }\n  function write(k, v) { localStorage.setItem(NS + k, JSON.stringify(v)); }\n  function owned() { return read(\"$owned\", []); }\n  function balances() { return read(\"$balances\", {}); }\n  function find(id) { return products.filter(function (p) { return p.id === id; })[0]; }\n  function displayPrice(price) {\n    try { return new Intl.NumberFormat(undefined, { style: \"currency\", currency: price.currency }).format(price.amount); }\n    catch (e) { return price.amount + \" \" + price.currency; }\n  }\n  var PERIOD = { P1W: \"week\", P1M: \"month\", P3M: \"3 months\", P6M: \"6 months\", P1Y: \"year\" };\n\n  // The purchase sheet: a small modal in the page, like the system sheet WispOS shows.\n  function sheet(p) {\n    return new Promise(function (resolve) {\n      var wrap = document.createElement(\"div\");\n      wrap.setAttribute(\"style\", \"position:fixed;inset:0;z-index:2147483647;display:flex;align-items:flex-end;justify-content:center;background:rgba(0,0,0,.45);font:15px -apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif\");\n      wrap.innerHTML =\n        '<div role=\"dialog\" aria-modal=\"true\" aria-label=\"Confirm purchase\" style=\"width:min(420px,100%);margin:12px;background:#1c1d24;color:#f2f2f7;border-radius:18px;padding:20px 20px 16px;box-shadow:0 20px 60px rgba(0,0,0,.5)\">' +\n        '<div style=\"font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:#9a9aa5\">Test purchase · no money moves</div>' +\n        '<div style=\"font-size:19px;font-weight:700;margin:6px 0 2px\"></div>' +\n        '<div style=\"color:#b9b9c4;margin-bottom:4px\" data-d></div>' +\n        '<div style=\"color:#9a9aa5;font-size:13px;margin-bottom:16px\" data-a></div>' +\n        '<button data-buy style=\"width:100%;padding:12px;border:0;border-radius:12px;background:#7c6cff;color:#fff;font:600 16px inherit;cursor:pointer\"></button>' +\n        '<button data-cancel style=\"width:100%;padding:10px;margin-top:6px;border:0;background:none;color:#9a9aa5;font:15px inherit;cursor:pointer\">Cancel</button></div>';\n      wrap.querySelector(\"[role=dialog] > div:nth-child(2)\").textContent = p.title;\n      wrap.querySelector(\"[data-d]\").textContent = p.description;\n      wrap.querySelector(\"[data-a]\").textContent = m.name + (p.type === \"subscription\" ? \" · renews every \" + PERIOD[p.period] : p.type === \"consumable\" ? \" · consumable\" : \"\");\n      wrap.querySelector(\"[data-buy]\").textContent = \"Buy for \" + displayPrice(p.price) + (p.type === \"subscription\" ? \" / \" + PERIOD[p.period] : \"\");\n      function done(ok) { wrap.remove(); resolve(ok); }\n      wrap.querySelector(\"[data-buy]\").onclick = function () { done(true); };\n      wrap.querySelector(\"[data-cancel]\").onclick = function () { done(false); };\n      wrap.addEventListener(\"click\", function (e) { if (e.target === wrap) done(false); });\n      document.body.appendChild(wrap);\n      wrap.querySelector(\"[data-buy]\").focus();\n    });\n  }\n\n  var api = {\n    version: \"1\",\n    app: Object.freeze({ id: m.id, name: m.name, version: m.version, build: m.build, kind: m.kind }),\n    storage: {\n      get: function (k) { return Promise.resolve(read(\"k:\" + k, null)); },\n      set: function (k, v) { write(\"k:\" + k, v); return Promise.resolve(); },\n      remove: function (k) { localStorage.removeItem(NS + \"k:\" + k); return Promise.resolve(); },\n      keys: function () {\n        var out = [];\n        for (var i = 0; i < localStorage.length; i++) { var k = localStorage.key(i); if (k.indexOf(NS + \"k:\") === 0) out.push(k.slice((NS + \"k:\").length)); }\n        return Promise.resolve(out);\n      },\n    },\n    purchases: {\n      products: function () {\n        var o = owned(), b = balances();\n        return Promise.resolve(products.map(function (p) {\n          return { id: p.id, type: p.type, title: p.title, description: p.description, price: p.price, displayPrice: displayPrice(p.price),\n            period: p.period || null, owned: p.type !== \"consumable\" && o.indexOf(p.id) !== -1, balance: p.type === \"consumable\" ? (b[p.id] || 0) : null };\n        }));\n      },\n      buy: function (id) {\n        var p = find(id);\n        if (!p) return Promise.reject(new Error(\"no product \" + id + \" in this app's manifest\"));\n        if (p.type !== \"consumable\" && owned().indexOf(id) !== -1) return Promise.resolve({ id: id, status: \"purchased\", already: true });\n        return sheet(p).then(function (ok) {\n          if (ok) {\n            if (p.type === \"consumable\") { var b = balances(); b[id] = (b[id] || 0) + (p.quantity || 1); write(\"$balances\", b); }\n            else { var o = owned(); o.push(id); write(\"$owned\", o); }\n          }\n          var r = { id: id, status: ok ? \"purchased\" : \"cancelled\" };\n          window.dispatchEvent(new CustomEvent(\"wispos:purchase\", { detail: r }));\n          return r;\n        });\n      },\n      owned: function () { return Promise.resolve(owned()); },\n      balance: function (id) { return Promise.resolve(balances()[id] || 0); },\n      consume: function (id, n) {\n        var b = balances(), have = b[id] || 0, take = n == null ? 1 : n;\n        if (take > have) return Promise.reject(new Error(\"not enough \" + id + \" (have \" + have + \")\"));\n        b[id] = have - take; write(\"$balances\", b);\n        return Promise.resolve(b[id]);\n      },\n      restore: function () { return Promise.resolve(owned()); },\n    },\n    notify: function (n) {\n      if (perms.indexOf(\"notifications\") === -1) return Promise.reject(new Error(\"the manifest doesn't ask for notifications\"));\n      if (!(\"Notification\" in window)) return Promise.resolve(false);\n      var show = function () { new Notification(n.title || m.name, { body: n.body || \"\" }); return true; };\n      if (Notification.permission === \"granted\") return Promise.resolve(show());\n      return Notification.requestPermission().then(function (p) { return p === \"granted\" ? show() : false; });\n    },\n    docs: {\n      list: function () { return Promise.resolve((m.docs || []).map(function (d) { return { title: d.title, path: d.path }; })); },\n      open: function (p) { var d = p || ((m.docs || [])[0] || {}).path; if (d) window.open(\"/\" + d, \"_blank\"); return Promise.resolve(!!d); },\n    },\n    // Routines the manifest declares (web.routines), at the time the person\n    // picked. WispOS asks before it keeps one and runs it; here it's kept in\n    // localStorage and nothing runs (wapp run is a page, not a scheduler).\n    routines: {\n      list: function () {\n        var all = read(\"$routines\", {});\n        return Promise.resolve(routines.map(function (r) { var s = all[r.id]; return { id: r.id, title: r.title, does: r.does, at: s ? s.at : null, days: s ? s.days : null }; }));\n      },\n      get: function (id) { var s = read(\"$routines\", {})[id]; return Promise.resolve(s ? { id: id, at: s.at, days: s.days } : null); },\n      set: function (id, when) {\n        if (!routineOf(id)) return Promise.reject(new Error(\"no routine \" + id + \" in this app's manifest (web.routines)\"));\n        var at = when && when.at, days = (when && when.days) || \"daily\";\n        if (!/^([01]\\d|2[0-3]):[0-5]\\d$/.test(at || \"\")) return Promise.reject(new Error(\"at is HH:MM, 24-hour\"));\n        if ([\"daily\", \"weekdays\", \"weekends\"].indexOf(days) === -1) return Promise.reject(new Error(\"days is daily, weekdays or weekends\"));\n        var all = read(\"$routines\", {}); all[id] = { at: at, days: days }; write(\"$routines\", all);\n        return Promise.resolve({ id: id, at: at, days: days });\n      },\n      clear: function (id) { var all = read(\"$routines\", {}); delete all[id]; write(\"$routines\", all); return Promise.resolve(); },\n    },\n    // An https link, in WispOS's browser (here: a new tab).\n    open: function (url) {\n      if (!/^https:\\/\\//.test(String(url))) return Promise.reject(new Error(\"only https links open\"));\n      window.open(String(url), \"_blank\", \"noopener\");\n      return Promise.resolve(true);\n    },\n  };\n  // wispos.photos (an app that asks for `photos`): WispOS reads the person's\n  // library one day at a time. Here it exists only when a sample library is\n  // given (window.__WISPOS_PHOTOS__ = { days: { \"YYYY-MM-DD\": { photos,\n  // places } }, thumbs: { id: url } }, as tools/shots.cjs does); without one\n  // the app sees no photos, as on a WispOS before 0.2.17. write needs an AI,\n  // so here it says no.\n  var lib = window.__WISPOS_PHOTOS__;\n  if (perms.indexOf(\"photos\") >= 0 && lib) {\n    var allowed = { state: \"allowed\", why: \"\" };\n    api.photos = Object.freeze({\n      access: function () { return Promise.resolve(allowed); },\n      connect: function () { return Promise.resolve(allowed); },\n      day: function (date) {\n        var d = (lib.days || {})[String(date)] || {};\n        return Promise.resolve({ date: String(date), photos: d.photos || [], places: d.places || [], more: false });\n      },\n      thumb: function (id) { var u = (lib.thumbs || {})[id]; return u ? Promise.resolve(u) : Promise.reject(new Error(\"no photo \" + id)); },\n      write: function () { return Promise.reject(new Error(\"writing a day needs WispOS's AI\")); },\n    });\n  }\n  Object.defineProperty(window, \"wispos\", { value: Object.freeze(api), enumerable: false });\n})();\n";
// How this was started, for the help: `wapp` from npm, `node <file>` otherwise.
const me = path.basename(process.argv[1] || "wapp");
const PROG = /^wapp(\.cmd)?$/.test(me) ? "wapp" : `node ${path.relative(process.cwd(), process.argv[1]).startsWith("..") ? process.argv[1] : path.relative(process.cwd(), process.argv[1])}`;
const USAGE = `wapp ${VERSION}: make, check and try WispOS app packages (.wapp, format wispos.app/1)

usage: ${PROG} <command>

  new <folder> [--name "Name"]                 start an app (a counter that keeps its count)
  pack <folder> [-o <file or folder>]          make <id>-<version>.wapp from the folder
       [--key <ed25519 key.pem>]               (and sign it)
  validate <file.wapp>... [--json]             check packages the way the App Store does
           [--public-store]                    (and refuse what the public App Store won't take)
  run <file.wapp> [--port N] [--no-open]       try it in a browser, with window.wispos
  inspect <file.wapp>                          what's in it
  unpack <file.wapp> <folder>                  get the files back
  keygen <key.pem>                             make a signing key
  media <folder>                               the store page's videos and screenshots, in order
  media <folder> add <file> --caption "…"      add a screenshot (PNG, JPEG) or video (MP4, H.264)
        [--phone] [--poster <picture>]         (shown on phones; a video's still before it plays)
  media <folder> remove <v1|s2|file>           take one off (and delete its file)
  media <folder> move <v1|s2|file> <place>     put one at that place in its list

Then in WispOS: More → App Store → Installed → Install from a file…
Guide: https://wisp-os.com/docs/app-store/building-apps/`;

const MEDIA_USAGE = `usage: ${PROG} media <folder> [list]
       ${PROG} media <folder> add <file.png|.jpg|.mp4> --caption "…" [--phone] [--poster <picture>]
       ${PROG} media <folder> remove <v1|s2|file>
       ${PROG} media <folder> move <v1|s2|file> <place>`;
const [cmd, ...rest] = process.argv.slice(2);
const flag = (name) => { const i = rest.indexOf(name); if (i === -1) return null; const v = rest[i + 1]; rest.splice(i, 2); return v; };
const bool = (name) => { const i = rest.indexOf(name); if (i === -1) return false; rest.splice(i, 1); return true; };
const die = (msg) => { console.error(msg); process.exit(2); };
const kb = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);

function load(file) {
  if (!file) die("which package?");
  if (!fs.existsSync(file)) die(`${file}: no such file`);
  return validate(readBytes(file));
}

function report(file, r) {
  if (r.ok) {
    const m = r.manifest;
    console.log(`✓ ${file}: ${m.name} ${m.version} (build ${m.build}), ${m.kind}, ${r.info.entries} files, ${kb(r.info.bytes)}, ${r.info.signed ? "signed by key " + r.info.keyId : "unsigned"}`);
  } else {
    console.log(`✗ ${file}`);
    for (const e of r.errors) console.log(`  error: ${e}`);
  }
  for (const w of r.warnings) console.log(`  warning: ${w}`);
}

const commands = {
  new() {
    const dir = rest.find((a) => !a.startsWith("-"));
    const name0 = flag("--name");
    if (!dir) die(`new <folder> [--name "Name"]`);
    const id = path.basename(path.resolve(dir)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
    if (!/^[a-z][a-z0-9-]{1,39}$/.test(id)) die(`✗ can't make an app id from "${path.basename(path.resolve(dir))}": name the folder with letters, digits and dashes, starting with a letter`);
    const name = name0 || id.split("-").map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");
    if (fs.existsSync(dir) && fs.readdirSync(dir).length) die(`✗ ${dir} isn't empty; not writing over it`);
    for (const [n, text] of starter(id, name)) {
      fs.mkdirSync(path.dirname(path.join(dir, n)), { recursive: true });
      fs.writeFileSync(path.join(dir, n), text);
    }
    console.log(`✓ ${dir}: ${name} (id ${id}). Edit it, then:\n  ${PROG} pack ${dir}\n  ${PROG} run ${id}-1.0.0${EXTENSION}`);
  },

  pack() {
    const src = rest.find((a) => !a.startsWith("-"));
    if (!src) die("pack <source folder> [-o out] [--key key.pem]");
    const out = flag("-o");
    const keyFile = flag("--key");
    const privateKey = keyFile ? crypto.createPrivateKey(fs.readFileSync(keyFile)) : undefined;
    let r;
    try { r = pack(src, { privateKey }); } catch (e) { die(`✗ ${e.message}`); }
    let dest = out || path.join(process.cwd(), fileName(r.result.manifest));
    if (out && (out.endsWith("/") || (fs.existsSync(out) && fs.statSync(out).isDirectory()))) dest = path.join(out, fileName(r.result.manifest));
    fs.mkdirSync(path.dirname(dest), { recursive: true });
    writeBytes(dest, r.buf);
    const rel = path.relative(process.cwd(), dest);
    report(rel.startsWith("..") ? dest : rel, r.result);
  },

  validate() {
    const json = bool("--json");
    // The public App Store's own rule (web apps only for now): a private
    // share is checked without it.
    const pub = bool("--public-store");
    const files = rest.filter((a) => !a.startsWith("-"));
    if (!files.length) die("validate <file.wapp>...");
    let bad = 0;
    const out = [];
    for (const f of files) {
      const r = load(f);
      if (pub && r.manifest) { r.errors.push(...publicStoreErrors(r.manifest)); r.ok = !r.errors.length; }
      if (!r.ok) bad++;
      if (json) out.push({ file: f, ok: r.ok, errors: r.errors, warnings: r.warnings, id: r.manifest?.id ?? null, version: r.manifest?.version ?? null, ...r.info });
      else report(f, r);
    }
    if (json) console.log(JSON.stringify(out, null, 2));
    process.exit(bad ? 1 : 0);
  },

  inspect() {
    const f = rest[0];
    const r = load(f);
    report(f, r);
    if (!r.manifest) process.exit(1);
    const m = r.manifest;
    const line = (k, v) => v != null && v !== "" && console.log(`  ${k.padEnd(13)}${v}`);
    line("id", m.id);
    line("publisher", m.publisher && `${m.publisher.name} (${m.publisher.id})`);
    line("category", m.category);
    line("visibility", m.distribution?.visibility);
    line("price", m.price && (m.price.amount ? `${m.price.amount} ${m.price.currency}` : "Free"));
    line("runs", m.web && `${m.web.entry}${(m.web.network || []).length ? " · network: " + m.web.network.join(", ") : " · offline"}`);
    line("agent", m.agent && `${m.agent.folder}/${m.agent.updates ? " · updates from " + m.agent.updates.git : ""}`);
    line("native", m.native && Object.entries(m.native).map(([p, v]) => `${p} ${v.app || v.exe}${v.minimumSystem ? " (" + v.minimumSystem + "+)" : ""}`).join(" · ") + " · runs outside the web sandbox");
    line("docs", (m.docs || []).map((d) => d.title).join(" · "));
    line("purchases", (m.purchases || []).map((p) => `${p.title} (${p.type}, ${p.price.amount} ${p.price.currency})`).join(" · "));
    line("permissions", (m.permissions || []).map((p) => p.kind).join(", ") || "none");
    line("privacy", m.privacy && (m.privacy.collects.length ? m.privacy.collects.map((c) => c.data).join(", ") : "Data Not Collected"));
    console.log("  files");
    for (const [n, b] of r.files) console.log(`    ${kb(b.length).padStart(9)}  ${n}`);
    process.exit(r.ok ? 0 : 1);
  },

  unpack() {
    const [f, dir] = rest;
    if (!dir) die("unpack <file.wapp> <folder>");
    const r = load(f);
    if (!r.ok) { report(f, r); die("refusing to unpack an invalid package"); }
    for (const [n, b] of r.files) {
      const dest = path.join(dir, n);
      fs.mkdirSync(path.dirname(dest), { recursive: true });
      writeBytes(dest, b);
    }
    console.log(`unpacked ${r.files.size} files into ${dir}`);
  },

  // The store page's pictures and videos (APP-PACKAGE.md "Videos"): what the
  // App Store shows is what the manifest lists, in its order. This edits the
  // list and copies the file in, and takes the change back if the App
  // Store's checks wouldn't pass it.
  media() {
    const caption = flag("--caption"), poster = flag("--poster"), phone = bool("--phone");
    const [dir, action, ...args] = rest;
    if (!dir || !fs.existsSync(path.join(dir, "manifest.json"))) die(MEDIA_USAGE);
    const file = path.join(dir, "manifest.json");
    const before = fs.readFileSync(file);
    const problems = () => { try { pack(dir); return []; } catch (e) { return e.message.split("\n").slice(1).map((l) => l.trim()).filter(Boolean); } };
    const had = action && action !== "list" ? new Set(problems()) : null;
    const m = JSON.parse(before.toString("utf8"));
    m.screenshots = m.screenshots || [];
    const lists = () => [...(m.videos || []).map((v, i) => ["v" + (i + 1), "videos", v, v.video]), ...m.screenshots.map((s, i) => ["s" + (i + 1), "screenshots", s, s.image])];
    const find = (ref) => lists().find(([n, , , p]) => n === ref || p === ref || p === `store/${ref}` || path.basename(p) === ref) || die(`✗ ${dir}: no video or screenshot "${ref}" (see ${PROG} media ${dir})`);
    const show = () => {
      if (!lists().length) return console.log(`${m.name}: no videos or screenshots yet. Add one: ${PROG} media ${dir} add <file> --caption "…"`);
      console.log(`${m.name}'s store page shows, in this order:`);
      for (const [n, kind, x, p] of lists()) {
        const b = fs.existsSync(path.join(dir, p)) ? fs.statSync(path.join(dir, p)).size : null;
        console.log(`  ${n.padEnd(4)}${kind === "videos" ? "video " : "image "} ${(x.device || "desktop").padEnd(8)}${p}${b == null ? " (missing)" : "  " + kb(b)}  “${x.caption}”${x.poster ? "  poster " + x.poster : ""}`);
      }
    };
    if (!action || action === "list") return show();
    const removed = [];
    if (action === "add") {
      const src = args[0];
      if (!src || !caption) die(MEDIA_USAGE);
      if (!fs.existsSync(src)) die(`✗ ${src}: no such file`);
      if (poster && !fs.existsSync(poster)) die(`✗ ${poster}: no such file`);
      const ext = path.extname(src).toLowerCase();
      const video = ext === ".mp4";
      if (!video && ![".png", ".jpg", ".jpeg"].includes(ext)) die("✗ the store page takes PNG or JPEG screenshots and MP4 (H.264) videos");
      const copyIn = (from, sub) => {
        const rel = `store/${sub}/${path.basename(from).replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[.-]+/, "")}`;
        const to = path.join(dir, rel);
        if (path.resolve(from) !== path.resolve(to)) {
          if (fs.existsSync(to) && !fs.readFileSync(to).equals(fs.readFileSync(from))) die(`✗ ${rel} is already there and is a different file; rename yours`);
          if (!fs.existsSync(to)) { fs.mkdirSync(path.dirname(to), { recursive: true }); fs.copyFileSync(from, to); copied.push(to); }
        }
        if (lists().some(([, , , p]) => p === rel)) die(`✗ ${rel} is already on the store page`);
        return rel;
      };
      const copied = [];
      const item = { caption, ...(phone ? { device: "phone" } : {}) };
      if (video) m.videos = [...(m.videos || []), { video: copyIn(src, "videos"), ...(poster ? { poster: copyIn(poster, "videos") } : {}), ...item }];
      else { if (poster) die("✗ --poster is for a video"); m.screenshots.push({ image: copyIn(src, "screenshots"), ...item }); }
      return save(copied, `added ${video ? "a video" : "a screenshot"}`);
    }
    if (action === "remove") {
      if (!args[0]) die(MEDIA_USAGE);
      const [, kind, x] = find(args[0]);
      m[kind] = m[kind].filter((y) => y !== x);
      if (kind === "videos" && !m.videos.length) delete m.videos;
      const still = new Set(lists().flatMap(([, , y, p]) => [p, y.poster]).filter(Boolean).concat(m.icon));
      for (const p of [x.video || x.image, x.poster]) if (p && !still.has(p) && fs.existsSync(path.join(dir, p))) removed.push(p);
      return save([], `removed ${x.video || x.image}`);
    }
    if (action === "move") {
      const to = Number(args[1]);
      if (!args[0] || !Number.isInteger(to) || to < 1) die(MEDIA_USAGE);
      const [, kind, x] = find(args[0]);
      const list = m[kind].filter((y) => y !== x);
      list.splice(Math.min(to, list.length + 1) - 1, 0, x);
      m[kind] = list;
      return save([], `moved ${x.video || x.image} to ${kind === "videos" ? "video" : "screenshot"} ${Math.min(to, list.length)}`);
    }
    die(MEDIA_USAGE);

    // Write the manifest, then check the folder the way the App Store will:
    // a problem it didn't have before puts everything back as it was.
    function save(copied, did) {
      fs.writeFileSync(file, JSON.stringify(m, null, 2) + "\n");
      const moved = removed.map((p) => { const to = path.join(os.tmpdir(), `wapp-media-${process.pid}-${path.basename(p)}`); fs.renameSync(path.join(dir, p), to); return [p, to]; });
      const fresh = problems().filter((e) => !had.has(e));
      if (fresh.length) {
        fs.writeFileSync(file, before);
        for (const c of copied) fs.rmSync(c, { force: true });
        for (const [p, to] of moved) fs.renameSync(to, path.join(dir, p));
        console.log(`✗ not changed: the App Store wouldn't take it`);
        for (const e of fresh) console.log(`  error: ${e}`);
        process.exit(1);
      }
      for (const [, to] of moved) fs.rmSync(to, { force: true });
      console.log(`✓ ${did}${moved.length ? " (deleted " + moved.map(([p]) => p).join(", ") + ")" : ""}`);
      show();
      console.log(`Then raise the build, pack it and submit it again from WispOS; the store page changes when the App Store approves it.`);
    }
  },

  keygen() {
    const out = rest[0];
    if (!out) die("keygen <key.pem>");
    if (fs.existsSync(out)) die(`${out} exists; not overwriting a key`);
    const { privateKey, publicKey } = crypto.generateKeyPairSync("ed25519");
    fs.writeFileSync(out, privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o600 });
    const der = publicKey.export({ format: "der", type: "spki" });
    console.log(`wrote ${out} (keep it private). Key id ${crypto.createHash("sha256").update(der).digest("hex").slice(0, 16)}`);
  },

  // Serve a package from memory the way WispOS runs one: its own origin, the
  // manifest's CSP, and window.wispos (the reference runtime) injected into
  // every HTML page before the app's own scripts.
  run() {
    const port = Number(flag("--port") || 0);
    const noOpen = bool("--no-open");
    const f = rest[0];
    const r = load(f);
    if (!r.ok) { report(f, r); die("refusing to run an invalid package"); }
    const m = r.manifest;
    const runtime = readRuntime();
    const connect = ["'self'", ...((m.web && m.web.network) || [])].join(" ");
    const csp = `default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:; font-src 'self' data:; connect-src ${connect}; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'`;
    const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json; charset=utf-8",
      ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".webp": "image/webp", ".mp3": "audio/mpeg", ".woff2": "font/woff2" };
    const inject = `<script>window.__WISPOS_MANIFEST__=${JSON.stringify(m).replace(/</g, "\\u003c")};</script><script src="/__wispos/runtime.js"></script>`;
    const server = http.createServer((req, res) => {
      const u = new URL(req.url, "http://x");
      let p = decodeURIComponent(u.pathname).replace(/^\/+/, "");
      if (p === "") { res.writeHead(302, { location: "/" + (m.web ? m.web.entry : (m.docs || [])[0]?.path || "manifest.json") }); return res.end(); }
      if (p === "__wispos/runtime.js") { res.writeHead(200, { "content-type": TYPES[".js"] }); return res.end(runtime); }
      if (p.endsWith("/")) p += "index.html";
      const body = r.files.get(p);
      if (!body || p.startsWith("signature/")) { res.writeHead(404, { "content-type": "text/plain" }); return res.end("not in this package"); }
      const ext = path.extname(p).toLowerCase();
      const headers = { "content-type": TYPES[ext] || "application/octet-stream", "content-security-policy": csp, "x-content-type-options": "nosniff", "cache-control": "no-store" };
      if (ext === ".html" && p.startsWith("app/")) {
        const html = body.toString("utf8");
        const at = html.search(/<head[^>]*>/i);
        const out = at === -1 ? inject + html : html.replace(/<head[^>]*>/i, (h) => h + inject);
        res.writeHead(200, headers); return res.end(out);
      }
      res.writeHead(200, headers); res.end(body);
    });
    server.listen(port, "127.0.0.1", () => {
      const url = `http://127.0.0.1:${server.address().port}/`;
      console.log(`${m.name} ${m.version} running at ${url}  (Ctrl-C to stop)`);
      if (m.docs?.length) console.log(`help: ${url}${m.docs[0].path}`);
      if (!m.web) console.log(m.native ? "this package is a native app: install it in WispOS to run it (it opens only from WispOS); the URL shows its help." : "this package has no web app (an agent); the URL shows its help.");
      if (!noOpen && process.platform === "darwin") execFile("open", [url]);
    });
  },
};

if (cmd === "--version" || cmd === "-v") { console.log(VERSION); process.exit(0); }
if (!commands[cmd]) {
  console.log(USAGE);
  process.exit(cmd && cmd !== "help" && cmd !== "--help" && cmd !== "-h" ? 2 : 0);
}
commands[cmd]();
