iOS porting: EvenHub app compatibility first pass

This commit is contained in:
James Babcock committed 2026-09-08 14:47:58 -07:00
1 parent 79b6c276f8
commit 44bd1d8a2d
24 files changed
+843 -24

No files matched your search

+7
View File
@@ -18,6 +18,11 @@ const RECORD_FILE = 0xe4;
const RECORD_DIR = 0xe5;
const RECORD_FOOTER = 0xe3;
/** Archive paths are relative to one package, never to the phone container. */
export function safeEhpkPath(value: string): boolean {
return !!value && !/[\\\u0000:]/.test(value) && value.split('/').every(part => !!part && part !== '.' && part !== '..');
}
export type EhpkArchive = {
/** Relative path (e.g. "app.json", "dist/index.html") to contents. */
files: Map<string, Uint8Array>;
@@ -90,6 +95,7 @@ export function parseEhpk(data: Uint8Array): EhpkArchive {
const uncompressedLength = view.getUint32(p + 8, true);
const nameLength = view.getUint16(p + 14, true);
const name = utf8Decode(unxor(data, p + 16, nameLength));
if (!safeEhpkPath(name)) throw new Error(`ehpk: invalid file path ${name}`);
const blob = unxor(data, p + 16 + nameLength, compressedLength);
const content = decompress(blob, new Uint8Array(uncompressedLength));
if (content.length !== uncompressedLength) {
@@ -119,6 +125,7 @@ export function parseManifest(appJsonText: string): EvenHubManifest {
const name = String(raw.name ?? packageId);
const version = String(raw.version ?? "0");
const entrypoint = String(raw.entrypoint ?? "index.html");
if (!safeEhpkPath(entrypoint)) throw new Error('Invalid EHPK entrypoint');
const permissions = parsePermissions(raw.permissions);
const privacyPolicyUrl = firstSafeHttpsUrl(
+17 -11
View File
@@ -66,16 +66,15 @@ export async function launchPackage(
): Promise<void> {
const data = readBinaryFile(ehpkPath);
if (!data) {
ctx.appendLog(`evenhub: could not read ${ehpkPath}`);
return;
throw new Error('Could not read the EHPK file.');
}
const archive = parseEhpk(data);
const appJson = archive.files.get("app.json");
if (!appJson) {
ctx.appendLog("evenhub: package has no app.json");
return;
throw new Error('The EHPK package has no app.json.');
}
const manifest = parseManifest(utf8Decode(appJson));
if (!archive.files.has(`dist/${manifest.entrypoint}`)) throw new Error('The EHPK entrypoint is missing from dist/.');
const appId = options.appId ?? "evenhub";
if (options.singleton) {
const existing = Array.from(running.values()).find((app) => app.appId === appId);
@@ -88,16 +87,18 @@ export async function launchPackage(
// Unpack fresh into app-private storage, keyed by package id.
const safeId = manifest.packageId.replace(/[^A-Za-z0-9._-]/g, "_");
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}`;
if (!safeId || safeId === '.' || safeId === '..') throw new Error('Invalid EHPK package ID');
const baseDir = `${appFilesDirPath()}/evenhub-apps/${safeId}${global.isIOS ? `-${Date.now()}-${nextSerial}` : ''}`;
deletePathRecursively(baseDir);
for (const [name, content] of Array.from(archive.files)) {
if (!writeBinaryFile(`${baseDir}/${name}`, content)) {
ctx.appendLog(`evenhub: failed to write ${name}`);
return;
deletePathRecursively(baseDir);
throw new Error(`Could not unpack ${name}.`);
}
}
await startApp(ctx, manifest, `${baseDir}/dist`, "", appId);
try { await startApp(ctx, manifest, `${baseDir}/dist`, "", appId, global.isIOS ? () => deletePathRecursively(baseDir) : undefined); }
catch (error) { deletePathRecursively(baseDir); throw error; }
}
/**
@@ -111,6 +112,7 @@ async function startApp(
distDir: string,
remoteUrl: string,
appId: string,
cleanup?: () => void,
): Promise<void> {
const windowId = `evenhub:app:${nextSerial++}`;
const session = new EvenHubSession(manifest, distDir, ctx.appendLog, remoteUrl);
@@ -123,6 +125,7 @@ async function startApp(
phoneShownWindowId = null;
}
webView.destroy();
cleanup?.();
running.delete(windowId);
},
});
@@ -130,9 +133,11 @@ async function startApp(
ensureBackHandler();
ctx.appendLog(`evenhub: launching ${manifest.name} ${manifest.version} (${manifest.packageId})`);
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
);
try {
await ctx.launchInProcessApp(windowId, `window:${windowId}`, (options) =>
createEvenHubWindow(windowId, appId, session, options, () => showOnPhone(windowId)),
);
} catch (error) { session.close(); throw error; }
}
/**
@@ -210,6 +215,7 @@ export function closeRunningPackage(packageId: string): void {
export function showOnPhone(windowId: string): void {
const app = running.get(windowId);
if (!app) return;
if (phoneShownWindowId && phoneShownWindowId !== windowId) hidePhone();
app.webView.showOnPhone();
phoneShownWindowId = windowId;
}
+5
View File
@@ -0,0 +1,5 @@
import { Utils } from '@nativescript/core'
/** Open outside the app runtime; this page has no EvenHub bridge. */
export function openPrivacyPolicyOnPhone(url: string, _appName: string): void {
if (/^https:\/\//i.test(url)) Utils.openUrl(url)
}
+14 -3
View File
@@ -334,6 +334,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
private windowHooks: EvenHubWindowHooks | null = null;
private closed = false;
private launchContextPushed = false;
private loadError = '';
private systemExitSent = false;
/** The one-shot launch FOREGROUND_ENTER has been delivered (page exists). */
private launchEnterSent = false;
@@ -383,6 +384,11 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
this.webViewHandle = handle;
}
webViewFailed(message: string): void {
if (this.closed) return;
this.loadError = message; this.log(`evenhub: ${message}`); this.windowHooks?.requestRender();
}
/** The WebView finished loading the app: push the one-shot launch context. */
webViewLoaded(): void {
if (this.launchContextPushed) return;
@@ -416,11 +422,12 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
// Focus changes always trigger a repaint of the foreground window, so paint
// is a reliable place to sample shell input-focus for lifecycle events.
this.updateShellFocus(focused);
if (!this.pageCreated || !this.page) {
if (this.loadError || !this.pageCreated || !this.page) {
const image = new GrayImage(size.width, size.height, 0);
const font = EvenHubFont.get();
font.drawText(image, 16, 16, `Loading ${this.manifest.name}...`, 255);
font.drawText(image, 16, 16 + 2 * font.lineHeight, "(waiting for the app to build its page)", 120);
font.drawText(image, 16, 16, `${this.loadError ? 'Could not run' : 'Loading'} ${this.manifest.name}...`, 255);
font.drawTextWrapped(image, 16, 16 + 2 * font.lineHeight, Math.max(1, size.width - 32),
this.loadError || "(waiting for the app to build its page)", 120);
return image;
}
return compositePage(this.page, size, focused);
@@ -604,6 +611,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* flows (foreground + screen on + no assistant modal).
*/
private audioControl(data: Record<string, unknown>): boolean {
if (global.isIOS) return false; // EvenHub PCM routing is not ported yet.
if (!permissionsIncludeMicrophone(this.manifest.permissions)) {
this.log("evenhub: audioControl denied (app declares no microphone permission)");
return false;
@@ -634,6 +642,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
/** getAppLocation(): one-shot fix, or null on denial/error (SDK contract). */
private async getAppLocation(): Promise<AppLocation | null> {
if (global.isIOS) return null;
if (!this.declaresLocation()) return null;
if (!(await ensureFineLocationPermission())) return null;
try {
@@ -657,6 +666,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* Navigate app's foreground-service-backed tracking.
*/
private async startLocationUpdates(data: Record<string, unknown>): Promise<boolean> {
if (global.isIOS) return false;
if (!this.declaresLocation()) return false;
if (!(await ensureFineLocationPermission())) return false;
if (this.closed) return false;
@@ -697,6 +707,7 @@ export class EvenHubSession implements EvenHubMicClient, EvenHubImuClient, EvenH
* to the foreground app. reportFrq is one of 100..1000 (step 100).
*/
private imuControl(data: Record<string, unknown>): boolean {
if (global.isIOS) return false;
const enable = readEnableFlag(data);
const freq = clampImuFreq(readOptionalNumber(data, "reportFrq") ?? readOptionalNumber(data, "reportFreq") ?? 100);
// Payload field spelling isn't fully captured; log once per toggle.
+43
View File
@@ -0,0 +1,43 @@
import { EVENHUB_BRIDGE_INJECT_SCRIPT, buildFaceclawExtensionsScript, type EvenHubSession } from './session'
import { FACECLAW_VERSION } from '../../version'
import type { EvenHubWebView } from './webview'
declare const FaceclawEvenHubWebView: any
export const IOS_EVENHUB_TRANSPORT_SCRIPT = `
window.__faceclawEvenHub = { postMessage: function(name, args, id) {
window.webkit.messageHandlers.faceclaw.postMessage({kind:'call', name:name, args:args, id:id});
}};
(function() {
['log','warn','error'].forEach(function(level) {
var original = console[level];
console[level] = function() {
original.apply(console, arguments);
window.webkit.messageHandlers.faceclaw.postMessage({kind:'console', message:Array.prototype.map.call(arguments, String).join(' ').slice(0,4000)});
};
});
window.addEventListener('error', function(e) { console.error(e.message); });
window.addEventListener('unhandledrejection', function(e) { console.error(String(e.reason)); });
})();
`
export function createEvenHubWebView(session: EvenHubSession): EvenHubWebView {
if (session.remoteUrl) throw new Error('On iOS, open a local .ehpk package from Files.')
const host = FaceclawEvenHubWebView.new()
host.packageIdentifier = session.manifest.packageId
host.eventHandler = (json: string) => {
try {
const event = JSON.parse(json)
if (event.kind === 'call' && typeof event.name === 'string' && typeof event.args === 'string' && Number.isSafeInteger(event.id))
session.handleBridgeCall(event.name, event.args, event.id)
else if (event.kind === 'loaded') session.webViewLoaded()
else if (event.kind === 'error') session.webViewFailed(String(event.message))
else if (event.kind === 'console') console.log(`[evenhub:${session.manifest.name}] ${event.message}`)
} catch (error) { console.warn(`EvenHub bridge: ${error}`) }
}
// Defer loading until manager.ts has attached the session/window handles.
const loading = setTimeout(() => host.startEntrypointScript(session.distDir, session.manifest.entrypoint,
IOS_EVENHUB_TRANSPORT_SCRIPT + EVENHUB_BRIDGE_INJECT_SCRIPT + buildFaceclawExtensionsScript(`Faceclaw/${FACECLAW_VERSION}`)), 0)
return { native: host, evaluateJs: js => host.evaluate(js),
destroy: () => { clearTimeout(loading); host.destroy() },
showOnPhone: () => host.showOnPhone(), hideOnPhone: () => host.hideOnPhone() }
}
+4 -3
View File
@@ -45,7 +45,7 @@ export type FilesAppOptions = InProcessAppOptions & {
export function createFilesAppWindow(options: FilesAppOptions): InProcessWindow {
let created: InProcessWindow | null = null;
const browser = new FileBrowserLayer({
isSupportedFile: (name) => TEXT_FILE.test(name) || isFontFile(name) || (!global.isIOS && (isDecodableImageFile(name) || EHPK_FILE.test(name))),
isSupportedFile: (name) => TEXT_FILE.test(name) || isFontFile(name) || EHPK_FILE.test(name) || (!global.isIOS && isDecodableImageFile(name)),
// The browser handles double-click itself (up a level), so it is not
// wrapped in YieldAtRootLayer; it yields explicitly from the top level.
onLeave: () => shell.yieldFocusToSidebar(),
@@ -170,7 +170,7 @@ function confirmEhpkPermissions(ctx: LayerContext, entry: DirectoryEntry, procee
* window for viewable types, empty for everything else (metadata only).
*/
function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileInfoAction[] {
if (global.isIOS && !TEXT_FILE.test(entry.name) && !isFontFile(entry.name)) return [];
if (global.isIOS && !TEXT_FILE.test(entry.name) && !isFontFile(entry.name) && !EHPK_FILE.test(entry.name)) return [];
if (TEXT_FILE.test(entry.name)) {
return [
{
@@ -192,7 +192,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
];
}
if (EHPK_FILE.test(entry.name)) {
return [
const actions: FileInfoAction[] = [
{
label: "Run app",
onSelect: (ctx) => {
@@ -210,6 +210,7 @@ function fileOpenActions(entry: DirectoryEntry, options: FilesAppOptions): FileI
},
},
];
return global.isIOS ? actions.slice(0, 1) : actions;
}
if (isDecodableImageFile(entry.name)) {
return [
+1
View File
@@ -64,6 +64,7 @@ const filesApp: AppDefinition = {
openEhpkApp: (path) => {
void openEvenHubPackage(ctx, path).catch((error) => {
ctx.appendLog(`evenhub launch failed: ${error}`);
openTextDocumentWindow(ctx, 'Could not run app', String(error));
});
},
installEhpkApp: async (path) => {
+1 -1
View File
@@ -8,7 +8,7 @@ const unavailable: Record<string, string> = {
navigate: 'Navigation location tracking is not available on iOS yet.',
weather: 'Weather location access is not available on iOS yet.',
calendar: 'Calendar access is not available on iOS yet.',
evenhub: 'The EvenHub store and app runtime are not available on iOS yet.',
evenhub: 'Open a local .ehpk file in Files to run an EvenHub app. The EvenHub store is not available on iOS yet.',
}
export function iosAppUnavailableReason(appId: string): string | null {
return unavailable[appId] ?? null