// Yetano WebView bridge, protocol v1. Installed as a document-start script // before any page script. Replaces window.fetch and window.XMLHttpRequest for // page-local URLs ("/..." and "assets:...") and routes them through the single // native binding __yetano_post to the Go host. No network listener is used. (function () { 'use strict'; if (window.yetano && window.yetano.__installed) return; window.__yetano_install_count = (window.__yetano_install_count || 0) + 1; var cfg = window.__yetano_config || {}; var PROTO = 1; var origFetch = typeof window.fetch === 'function' ? window.fetch.bind(window) : null; var OrigXHR = window.XMLHttpRequest; var nonce = Math.random().toString(36).slice(2) + Date.now().toString(36); var gen = 0; var seq = 0; var pending = new Map(); var stats = { staleDropped: 0, requests: 0 }; var readyResolve, readyReject, readySettled = false; var ready = new Promise(function (res, rej) { readyResolve = res; readyReject = rej; }); ready.catch(function () {}); // the rejection is reported to callers, not as unhandled function settleReady(ok, v) { if (readySettled) return; readySettled = true; clearTimeout(helloTimer); (ok ? readyResolve : readyReject)(v); } function post(msg) { var fn = window.__yetano_post; if (typeof fn !== 'function') return Promise.reject(new Error('native binding __yetano_post missing')); try { return Promise.resolve(fn(msg)); } catch (e) { return Promise.reject(e); } } // ---- receive --------------------------------------------------------- window.__yetano_recv = function (m) { if (!m || typeof m !== 'object') return; if (m.t === 'ready') { if (m.nonce !== nonce) return; if (m.error) { settleReady(false, new Error('yetano bridge: ' + m.error)); return; } gen = m.gen; settleReady(true, { generation: m.gen, session: m.session, protocol: m.v }); return; } if (m.t !== 'res' && m.t !== 'err' && m.t !== 'chunk' && m.t !== 'end') return; var p = pending.get(m.id); if (!p || m.gen !== gen) { stats.staleDropped++; return; } switch (m.t) { case 'res': if (m.stream) p.startStream(m); else p.resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: b64dec(m.body || '') }); break; case 'chunk': p.chunk(b64dec(m.data || '')); break; case 'end': p.end(); break; default: { var e = m.code === 'timeout' ? new DOMException('yetano: ' + m.message, 'TimeoutError') : m.code === 'abort' ? new DOMException('yetano: ' + m.message, 'AbortError') : new TypeError('yetano bridge ' + m.code + ': ' + m.message); p.fail(e); } } }; var helloTimer = setTimeout(function () { settleReady(false, new Error('yetano bridge: handshake timed out')); }, cfg.handshakeTimeoutMs || 5000); post({ t: 'hello', v: cfg.protocolOverride || PROTO, nonce: nonce }).catch(function (e) { settleReady(false, new Error('yetano bridge: hello failed: ' + e)); }); // ---- helpers --------------------------------------------------------- function b64enc(u8) { var s = ''; for (var i = 0; i < u8.length; i += 0x8000) { s += String.fromCharCode.apply(null, u8.subarray(i, i + 0x8000)); } return btoa(s); } function b64dec(s) { var bin = atob(s); var u8 = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i); return u8; } function abortError(signal) { return (signal && signal.reason !== undefined) ? signal.reason : new DOMException('The operation was aborted.', 'AbortError'); } // Local URLs are recognized on the raw string, before any URL() resolution // (an inline entry document has an opaque data: origin). Absolute URLs on // the app origin (native transport) count as local, too. var NATIVE = cfg.transport === 'native'; function localURL(u) { if (typeof u !== 'string') return null; if (u.indexOf('assets:') === 0) return u; if (cfg.origin && u.indexOf(cfg.origin + '/') === 0) return u.slice(cfg.origin.length); if (u.charAt(0) === '/' && u.charAt(1) !== '/') return u; return null; } // For the native transport: "assets:x" is not loadable by the browser. function nativeURL(local) { return local.indexOf('assets:') === 0 ? '/assets/' + local.slice(7) : local; } function externalBlocked(u) { return new TypeError('yetano: external request blocked by policy: ' + u); } async function toBytes(body, headers) { function setType(t) { if (!headers['content-type']) headers['content-type'] = t; } if (typeof body === 'string') { setType('text/plain;charset=UTF-8'); return new TextEncoder().encode(body); } if (body instanceof URLSearchParams) { setType('application/x-www-form-urlencoded;charset=UTF-8'); return new TextEncoder().encode(body.toString()); } if (body instanceof ArrayBuffer) return new Uint8Array(body); if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength); if (typeof Blob !== 'undefined' && body instanceof Blob) { if (body.type) setType(body.type); return new Uint8Array(await body.arrayBuffer()); } if (typeof FormData !== 'undefined' && body instanceof FormData) { // Let the browser produce multipart/form-data (with its boundary). var mp = new Response(body); headers['content-type'] = mp.headers.get('content-type'); return new Uint8Array(await mp.arrayBuffer()); } if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) throw new TypeError('yetano: streaming request bodies are not supported (AP1 limit)'); setType('text/plain;charset=UTF-8'); return new TextEncoder().encode(String(body)); } // request sends one call. The promise settles exactly once: with the // response head (body bytes, or a ReadableStream for streamed responses) // or with an error (abort, timeout, stale generation, transport). A stream // ends exactly once, too: end, error, abort or reader cancel. Every end // that is not initiated by Go is reported to Go (abort message). async function request(d) { await ready; if (d.signal && d.signal.aborted) throw abortError(d.signal); var id = String(++seq); var myGen = gen; stats.requests++; return new Promise(function (resolve, reject) { var timer = null, ctrl = null, settled = false; function cleanup() { pending.delete(id); if (timer) { clearTimeout(timer); timer = null; } if (d.signal) d.signal.removeEventListener('abort', onAbort); } function fail(e) { if (!pending.has(id)) return; cleanup(); if (ctrl) { try { ctrl.error(e); } catch (x) {} } else if (!settled) { settled = true; reject(e); } } function onAbort() { fail(abortError(d.signal)); post({ t: 'abort', id: id, gen: myGen }); } pending.set(id, { resolve: function (v) { if (!pending.has(id)) return; cleanup(); settled = true; resolve(v); }, fail: fail, startStream: function (m) { if (timer) { clearTimeout(timer); timer = null; } // the timeout covers the response head var body = new ReadableStream({ start: function (c) { ctrl = c; }, cancel: function () { if (!pending.has(id)) return; cleanup(); post({ t: 'abort', id: id, gen: myGen }); } }); settled = true; resolve({ status: m.status, statusText: m.statusText || '', headers: m.headers || {}, body: body, streaming: true }); }, chunk: function (u8) { if (ctrl) ctrl.enqueue(u8); }, end: function () { if (!pending.has(id)) return; cleanup(); if (ctrl) ctrl.close(); } }); if (d.signal) d.signal.addEventListener('abort', onAbort, { once: true }); var t = d.timeoutMs != null ? d.timeoutMs : (cfg.defaultTimeoutMs || 30000); if (t > 0) { timer = setTimeout(function () { fail(new DOMException('yetano: request timed out after ' + t + ' ms', 'TimeoutError')); post({ t: 'abort', id: id, gen: myGen, reason: 'timeout' }); }, t); } post({ t: 'req', id: id, gen: myGen, method: d.method, url: d.url, headers: d.headers, body: d.body ? b64enc(d.body) : null, timeoutMs: t }).catch(function (e) { fail(new TypeError('yetano bridge: transport failed: ' + e)); }); }); } // ---- fetch ----------------------------------------------------------- // bridgeFetch: local requests as bridge messages (abort, timeout and // document generation reach the Go handler; bodies are buffered). async function bridgeFetch(input, init) { init = init || {}; var url = typeof input === 'string' ? input : (typeof URL !== 'undefined' && input instanceof URL) ? input.href : (input && input.url); var local = localURL(url); if (local === null) { if (cfg.external === 'passthrough' && origFetch) return origFetch(input, init); throw externalBlocked(url); } var method = String(init.method || 'GET').toUpperCase(); var headers = {}; new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; }); var body = null; if (init.body != null) { if (method === 'GET' || method === 'HEAD') throw new TypeError('yetano: ' + method + ' request cannot have a body'); body = await toBytes(init.body, headers); } var r = await request({ method: method, url: local, headers: headers, body: body, signal: init.signal, timeoutMs: init.yetanoTimeout }); var nullBody = method === 'HEAD' || r.status === 204 || r.status === 205 || r.status === 304; return new Response(nullBody ? null : r.body, { status: r.status, statusText: r.statusText, headers: r.headers }); } bridgeFetch.yetano = true; // nativeFetch (native transport): assets come from the native resource // handler (no size limit, real Response, ES modules); app routes use the // bridge (abort/timeout/generation reach Go, streaming via chunk messages // on every backend). init.yetanoTransport = 'native' | 'bridge' overrides. function isAsset(local) { return local.indexOf('assets:') === 0 || local.indexOf('/assets/') === 0; } async function nativeFetch(input, init) { var url = typeof input === 'string' ? input : (typeof URL !== 'undefined' && input instanceof URL) ? input.href : (input && input.url); var local = localURL(url); if (local === null) { if (cfg.external === 'passthrough') return origFetch(input, init); throw externalBlocked(url); } var via = (init && init.yetanoTransport) || (isAsset(local) ? 'native' : 'bridge'); if (via === 'bridge') return bridgeFetch(input, init); if (typeof input === 'string' || (typeof URL !== 'undefined' && input instanceof URL)) input = nativeURL(local); // WebKit hands Blob/FormData bodies to a URL scheme handler as empty // (observed); serialize them here so every backend receives the bytes. if (init && needsSerialize(init.body)) { var headers = {}; new Headers(init.headers || {}).forEach(function (v, k) { headers[k] = v; }); var bytes = await toBytes(init.body, headers); init = Object.assign({}, init, { body: bytes, headers: headers }); } return origFetch(input, init); } nativeFetch.yetano = true; function needsSerialize(b) { return b != null && ((typeof Blob !== 'undefined' && b instanceof Blob) || (typeof FormData !== 'undefined' && b instanceof FormData)); } var yetanoFetch = NATIVE ? nativeFetch : bridgeFetch; window.fetch = yetanoFetch; // ---- XMLHttpRequest ------------------------------------------------- // Local URLs go through the bridge (native transport: assets through the // real XHR from the app origin); external URLs are delegated to the real // XHR only with cfg.external === 'passthrough'. Re-opening or aborting an // instance invalidates its earlier call (token), so a late reply for an old // request never lands in the reused object. function YetanoXHR() { var et = new EventTarget(); this._et = et; this.upload = new EventTarget(); this.readyState = 0; this.status = 0; this.statusText = ''; this.response = null; this.responseText = ''; this.responseType = ''; this.responseURL = ''; this.timeout = 0; this.withCredentials = false; this._token = 0; this._reqHeaders = {}; this._respHeaders = {}; this._ctl = null; this._sent = false; } YetanoXHR.UNSENT = 0; YetanoXHR.OPENED = 1; YetanoXHR.HEADERS_RECEIVED = 2; YetanoXHR.LOADING = 3; YetanoXHR.DONE = 4; ['UNSENT', 'OPENED', 'HEADERS_RECEIVED', 'LOADING', 'DONE'].forEach(function (k, i) { YetanoXHR.prototype[k] = i; }); YetanoXHR.prototype.addEventListener = function (t, f, o) { this._et.addEventListener(t, f, o); }; YetanoXHR.prototype.removeEventListener = function (t, f, o) { this._et.removeEventListener(t, f, o); }; YetanoXHR.prototype.dispatchEvent = function (e) { return this._et.dispatchEvent(e); }; YetanoXHR.prototype._fire = function (type, loaded, total) { var ev = (type === 'readystatechange') ? new Event(type) : new ProgressEvent(type, { lengthComputable: total != null, loaded: loaded || 0, total: total || 0 }); var h = this['on' + type]; if (typeof h === 'function') { try { h.call(this, ev); } catch (e) { setTimeout(function () { throw e; }); } } this._et.dispatchEvent(ev); }; YetanoXHR.prototype._state = function (s) { this.readyState = s; this._fire('readystatechange'); }; YetanoXHR.prototype.open = function (method, url, async) { if (async === false) throw new DOMException('yetano: synchronous XMLHttpRequest is not supported', 'InvalidAccessError'); this._token++; if (this._ctl) { this._ctl.abort(); this._ctl = null; } if (this._native) { this._native.abort(); this._native = null; } this._method = String(method || 'GET').toUpperCase(); this._url = String(url); this._reqHeaders = {}; this._respHeaders = {}; this._sent = false; this.status = 0; this.statusText = ''; this.response = null; this.responseText = ''; this._state(1); }; YetanoXHR.prototype.setRequestHeader = function (k, v) { if (this.readyState !== 1 || this._sent) throw new DOMException('setRequestHeader: invalid state', 'InvalidStateError'); k = String(k).toLowerCase(); this._reqHeaders[k] = this._reqHeaders[k] ? this._reqHeaders[k] + ', ' + v : String(v); }; YetanoXHR.prototype.overrideMimeType = function (m) { this._mime = m; }; YetanoXHR.prototype.getResponseHeader = function (k) { var v = this._respHeaders[String(k).toLowerCase()]; return v === undefined ? null : v; }; YetanoXHR.prototype.getAllResponseHeaders = function () { var h = this._respHeaders; return Object.keys(h).sort().map(function (k) { return k + ': ' + h[k] + '\r\n'; }).join(''); }; YetanoXHR.prototype.abort = function () { var wasActive = this._sent && this.readyState !== 4; this._token++; if (this._ctl) { this._ctl.abort(); this._ctl = null; } if (this._native) { this._native.abort(); this._native = null; } if (wasActive) { this._sent = false; this._state(4); this._fire('abort'); this._fire('loadend'); } this.readyState = 0; }; YetanoXHR.prototype.send = function (body) { if (this.readyState !== 1 || this._sent) throw new DOMException('send: invalid state', 'InvalidStateError'); var self = this, token = this._token; var local = localURL(this._url); if (local === null) return this._sendNative(body, false); if (NATIVE && isAsset(local)) return this._sendNative(body, true, nativeURL(local)); this._sent = true; var ctl = new AbortController(); this._ctl = ctl; var headers = Object.assign({}, this._reqHeaders); this._fire('loadstart', 0); (async function () { var bytes = null; if (body != null && self._method !== 'GET' && self._method !== 'HEAD') bytes = await toBytes(body, headers); return request({ method: self._method, url: local, headers: headers, body: bytes, signal: ctl.signal, timeoutMs: self.timeout > 0 ? self.timeout : undefined }); })().then(async function (r) { if (r.streaming) r.body = new Uint8Array(await new Response(r.body).arrayBuffer()); return r; }).then(function (r) { if (token !== self._token) return; // reopened/aborted meanwhile self._ctl = null; self.status = r.status; self.statusText = r.statusText; self._respHeaders = r.headers; self.responseURL = local; self._state(2); var type = (self._mime || r.headers['content-type'] || '').split(';')[0].trim(); var text = null; function asText() { if (text === null) text = new TextDecoder().decode(r.body); return text; } switch (self.responseType) { case 'arraybuffer': self.response = r.body.buffer.slice(r.body.byteOffset, r.body.byteOffset + r.body.byteLength); break; case 'blob': self.response = new Blob([r.body], { type: type }); break; case 'json': try { self.response = JSON.parse(asText()); } catch (e) { self.response = null; } break; case 'document': self.response = new DOMParser().parseFromString(asText(), type === 'text/xml' || type === 'application/xml' ? type : 'text/html'); break; default: self.responseText = self.response = asText(); } self._state(3); self._fire('progress', r.body.length, r.body.length); self._sent = false; self._state(4); self._fire('load', r.body.length, r.body.length); self._fire('loadend', r.body.length, r.body.length); }, function (e) { if (token !== self._token) return; self._ctl = null; self._sent = false; self.status = 0; self._state(4); self._fire(e && e.name === 'TimeoutError' ? 'timeout' : (e && e.name === 'AbortError' ? 'abort' : 'error')); self._fire('loadend'); }); }; YetanoXHR.prototype._sendNative = function (body, asset, url) { var self = this; if (!asset && (cfg.external !== 'passthrough' || !OrigXHR)) { this._sent = true; setTimeout(function () { self._sent = false; self.status = 0; self._state(4); self._fire('error'); self._fire('loadend'); if (window.console) console.warn(String(externalBlocked(self._url))); }); return; } var x = new OrigXHR(); this._native = x; this._sent = true; x.open(this._method, url || this._url, true); Object.keys(this._reqHeaders).forEach(function (k) { x.setRequestHeader(k, self._reqHeaders[k]); }); x.responseType = this.responseType; x.timeout = this.timeout; x.withCredentials = this.withCredentials; ['readystatechange', 'loadstart', 'progress', 'load', 'error', 'abort', 'timeout', 'loadend'].forEach(function (t) { x.addEventListener(t, function () { if (self._native !== x) return; self.status = x.status; self.statusText = x.statusText; self.response = x.response; self.responseURL = x.responseURL; if (x.responseType === '' || x.responseType === 'text') self.responseText = x.responseText; self._respHeaders = {}; (x.getAllResponseHeaders() || '').trim().split(/[\r\n]+/).forEach(function (l) { var i = l.indexOf(':'); if (i > 0) self._respHeaders[l.slice(0, i).trim().toLowerCase()] = l.slice(i + 1).trim(); }); if (t === 'readystatechange') { self._state(x.readyState); } else { self._fire(t); } }); }); x.send(body); }; window.XMLHttpRequest = YetanoXHR; // ---- page console -> host log (diagnostics) --------------------------- if (cfg.forwardConsole) { ['log', 'warn', 'error'].forEach(function (lvl) { var orig = console[lvl]; console[lvl] = function () { try { post({ t: 'log', level: lvl, msg: Array.prototype.map.call(arguments, String).join(' ') }); } catch (e) {} return orig.apply(console, arguments); }; }); window.addEventListener('error', function (e) { post({ t: 'log', level: 'error', msg: 'uncaught: ' + e.message + ' @' + e.filename + ':' + e.lineno }); }); window.addEventListener('unhandledrejection', function (e) { post({ t: 'log', level: 'error', msg: 'unhandled rejection: ' + (e.reason && e.reason.stack || e.reason) }); }); } // ---- public API ------------------------------------------------------ async function call(route, payload, opts) { opts = opts || {}; var r = await bridgeFetch('/rpc/' + route, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload === undefined ? null : payload), signal: opts.signal, yetanoTimeout: opts.timeoutMs }); var text = await r.text(); if (!r.ok) { var err = new Error(route + ': HTTP ' + r.status + ': ' + text); err.status = r.status; throw err; } return text ? JSON.parse(text) : null; } window.yetano = Object.freeze({ __installed: true, protocol: PROTO, config: cfg, transport: NATIVE ? 'native' : 'inline', bridgeFetch: bridgeFetch, ready: ready, fetch: yetanoFetch, call: call, pendingCount: function () { return pending.size; }, stats: function () { return { staleDropped: stats.staleDropped, requests: stats.requests, pending: pending.size, generation: gen }; }, _post: cfg.selftest ? post : undefined }); })();