browser.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. import * as base from './base.js';
  2. const browser = {};
  3. browser.Host = class {
  4. constructor() {
  5. this._window = window;
  6. this._navigator = window.navigator;
  7. this._document = window.document;
  8. this._telemetry = new base.Telemetry(this._window);
  9. this._window.eval = () => {
  10. throw new Error('window.eval() not supported.');
  11. };
  12. this._meta = {};
  13. for (const element of Array.from(this._document.getElementsByTagName('meta'))) {
  14. if (element.name !== undefined && element.name !== '' && element.content !== undefined) {
  15. this._meta[element.name] = this._meta[element.name] || [];
  16. this._meta[element.name].push(element.content);
  17. }
  18. }
  19. this._environment = {
  20. name: this._document.title,
  21. type: this._meta.type ? this._meta.type[0] : 'Browser',
  22. version: this._meta.version ? this._meta.version[0] : null,
  23. date: Array.isArray(this._meta.date) && this._meta.date.length > 0 && this._meta.date[0] ? new Date(`${this._meta.date[0].split(' ').join('T')}Z`) : new Date(),
  24. packaged: this._meta.version && this._meta.version[0] !== '0.0.0',
  25. platform: /(Mac|iPhone|iPod|iPad)/i.test(this._navigator.platform) ? 'darwin' : undefined,
  26. agent: this._navigator.userAgent.toLowerCase().indexOf('safari') !== -1 && this._navigator.userAgent.toLowerCase().indexOf('chrome') === -1 ? 'safari' : '',
  27. repository: this._element('logo-github').getAttribute('href'),
  28. menu: true
  29. };
  30. if (this.version && !/^\d+\.\d+\.\d+$/.test(this.version)) {
  31. throw new Error('Invalid version.');
  32. }
  33. }
  34. get window() {
  35. return this._window;
  36. }
  37. get document() {
  38. return this._document;
  39. }
  40. get version() {
  41. return this._environment.version;
  42. }
  43. get type() {
  44. return this._environment.type;
  45. }
  46. async view(view) {
  47. this._view = view;
  48. const age = async () => {
  49. const days = (new Date() - new Date(this._environment.date)) / (24 * 60 * 60 * 1000);
  50. if (days > 180) {
  51. const link = this._element('logo-github').href;
  52. this.document.body.classList.remove('spinner');
  53. for (;;) {
  54. /* eslint-disable no-await-in-loop */
  55. await this.message('Please update to the newest version.', null, 'Update');
  56. /* eslint-enable no-await-in-loop */
  57. this.openURL(link);
  58. }
  59. }
  60. return Promise.resolve();
  61. };
  62. const consent = async () => {
  63. if (this._getCookie('consent') || this._getCookie('_ga')) {
  64. return;
  65. }
  66. let consent = true;
  67. try {
  68. const text = await this._request('https://ipinfo.io/json', { 'Content-Type': 'application/json' }, 'utf-8', null, 2000);
  69. const json = JSON.parse(text);
  70. const countries = ['AT', 'BE', 'BG', 'HR', 'CZ', 'CY', 'DK', 'EE', 'FI', 'FR', 'DE', 'EL', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'NO', 'PL', 'PT', 'SK', 'ES', 'SE', 'GB', 'UK', 'GR', 'EU', 'RO'];
  71. if (json && json.country && countries.indexOf(json.country) === -1) {
  72. consent = false;
  73. }
  74. } catch {
  75. // continue regardless of error
  76. }
  77. if (consent) {
  78. this.document.body.classList.remove('spinner');
  79. await this.message('This app uses cookies to report errors and anonymous usage information.', null, 'Accept');
  80. }
  81. this._setCookie('consent', Date.now().toString(), 30);
  82. };
  83. const telemetry = async () => {
  84. if (this._environment.packaged) {
  85. this._window.addEventListener('error', (event) => {
  86. if (event instanceof ErrorEvent && event.error && event.error instanceof Error) {
  87. this.exception(event.error, true);
  88. } else {
  89. const message = event && event.message ? event.message : JSON.stringify(event);
  90. const error = new Error(message);
  91. this.exception(error, true);
  92. }
  93. });
  94. const measurement_id = '848W2NVWVH';
  95. const user = this._getCookie('_ga').replace(/^(GA1\.\d\.)*/, '');
  96. const session = this._getCookie(`_ga${measurement_id}`);
  97. await this._telemetry.start(`G-${measurement_id}`, user, session);
  98. this._telemetry.set('page_location', this._document.location && this._document.location.href ? this._document.location.href : null);
  99. this._telemetry.set('page_title', this._document.title ? this._document.title : null);
  100. this._telemetry.set('page_referrer', this._document.referrer ? this._document.referrer : null);
  101. this._telemetry.send('page_view', {
  102. app_name: this.type,
  103. app_version: this.version,
  104. });
  105. this._telemetry.send('scroll', {
  106. percent_scrolled: 90,
  107. app_name: this.type,
  108. app_version: this.version
  109. });
  110. this._setCookie('_ga', `GA1.2.${this._telemetry.get('client_id')}`, 1200);
  111. this._setCookie(`_ga${measurement_id}`, `GS1.1.${this._telemetry.session}`, 1200);
  112. }
  113. };
  114. const capabilities = async () => {
  115. const filter = (list) => {
  116. return list.filter((capability) => {
  117. const path = capability.split('.').reverse();
  118. let obj = this.window[path.pop()];
  119. while (obj && path.length > 0) {
  120. obj = obj[path.pop()];
  121. }
  122. return obj;
  123. });
  124. };
  125. const capabilities = filter(['fetch', 'DataView.prototype.getBigInt64', 'Worker', 'Array.prototype.flat']);
  126. this.event('browser_open', {
  127. browser_capabilities: capabilities.map((capability) => capability.split('.').pop()).join(',')
  128. });
  129. return Promise.resolve();
  130. };
  131. await age();
  132. await consent();
  133. await telemetry();
  134. await capabilities();
  135. }
  136. async start() {
  137. if (this._meta.file) {
  138. const [url] = this._meta.file;
  139. if (this._view.accept(url)) {
  140. const identifier = Array.isArray(this._meta.identifier) && this._meta.identifier.length === 1 ? this._meta.identifier[0] : null;
  141. const name = this._meta.name || null;
  142. const status = await this._openModel(this._url(url), identifier || null, name);
  143. if (status === '') {
  144. return;
  145. }
  146. }
  147. }
  148. const search = this.window.location.search;
  149. const params = new Map(search ? new URLSearchParams(this.window.location.search) : []);
  150. const hash = this.window.location.hash ? this.window.location.hash.replace(/^#/, '') : '';
  151. const url = hash ? hash : params.get('url');
  152. if (url) {
  153. const identifier = params.get('identifier') || null;
  154. const location = url
  155. .replace(/^https:\/\/github\.com\/([\w-]*\/[\w-]*)\/blob\/([\w/\-_.]*)(\?raw=true)?$/, 'https://raw.githubusercontent.com/$1/$2')
  156. .replace(/^https:\/\/github\.com\/([\w-]*\/[\w-]*)\/raw\/([\w/\-_.]*)$/, 'https://raw.githubusercontent.com/$1/$2')
  157. .replace(/^https:\/\/huggingface.co\/(.*)\/blob\/(.*)$/, 'https://huggingface.co/$1/resolve/$2');
  158. if (this._view.accept(identifier || location) && location.indexOf('*') === -1) {
  159. const status = await this._openModel(location, identifier);
  160. if (status === '') {
  161. return;
  162. }
  163. }
  164. }
  165. const gist = params.get('gist');
  166. if (gist) {
  167. this._openGist(gist);
  168. return;
  169. }
  170. const openFileButton = this._element('open-file-button');
  171. const openFileDialog = this._element('open-file-dialog');
  172. if (openFileButton && openFileDialog) {
  173. openFileButton.addEventListener('click', () => {
  174. this.execute('open');
  175. });
  176. const mobileSafari = this.environment('platform') === 'darwin' && navigator.maxTouchPoints && navigator.maxTouchPoints > 1;
  177. if (!mobileSafari) {
  178. const extensions = new base.Metadata().extensions.map((extension) => `.${extension}`);
  179. openFileDialog.setAttribute('accept', extensions.join(', '));
  180. }
  181. openFileDialog.addEventListener('change', (e) => {
  182. if (e.target && e.target.files && e.target.files.length > 0) {
  183. const files = Array.from(e.target.files);
  184. const file = files.find((file) => this._view.accept(file.name, file.size));
  185. if (file) {
  186. this._open(file, files);
  187. }
  188. }
  189. });
  190. }
  191. this.document.addEventListener('dragover', (e) => {
  192. e.preventDefault();
  193. });
  194. this.document.addEventListener('drop', (e) => {
  195. e.preventDefault();
  196. });
  197. this.document.body.addEventListener('drop', (e) => {
  198. e.preventDefault();
  199. if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  200. const files = Array.from(e.dataTransfer.files);
  201. const file = files.find((file) => this._view.accept(file.name, file.size));
  202. if (file) {
  203. this._open(file, files);
  204. }
  205. }
  206. });
  207. this._view.show('welcome');
  208. }
  209. environment(name) {
  210. return this._environment[name];
  211. }
  212. async require(id) {
  213. return import(`${id}.js`);
  214. }
  215. worker(id) {
  216. return new this.window.Worker(`${id}.js`, { type: 'module' });
  217. }
  218. async save(name, extension, defaultPath) {
  219. return `${defaultPath}.${extension}`;
  220. }
  221. async export(file, blob) {
  222. const element = this.document.createElement('a');
  223. element.download = file;
  224. const url = URL.createObjectURL(blob);
  225. element.href = url;
  226. this.document.body.appendChild(element);
  227. element.click();
  228. this.document.body.removeChild(element);
  229. URL.revokeObjectURL(url);
  230. }
  231. async execute(name /*, value */) {
  232. switch (name) {
  233. case 'open': {
  234. const openFileDialog = this._element('open-file-dialog');
  235. if (openFileDialog) {
  236. openFileDialog.value = '';
  237. openFileDialog.click();
  238. }
  239. break;
  240. }
  241. case 'report-issue': {
  242. this.openURL(`${this.environment('repository')}/issues/new`);
  243. break;
  244. }
  245. case 'about': {
  246. this._view.about();
  247. break;
  248. }
  249. default: {
  250. break;
  251. }
  252. }
  253. }
  254. async request(file, encoding, base) {
  255. const url = base ? `${base}/${file}` : this._url(file);
  256. if (base === null) {
  257. this._requests = this._requests || new Map();
  258. const key = `${url}:${encoding}`;
  259. if (!this._requests.has(key)) {
  260. const promise = this._request(url, null, encoding);
  261. this._requests.set(key, promise);
  262. }
  263. return this._requests.get(key);
  264. }
  265. return this._request(url, null, encoding);
  266. }
  267. openURL(url) {
  268. this.window.location = url;
  269. }
  270. exception(error, fatal) {
  271. if (this._telemetry && error) {
  272. const name = error.name ? `${error.name}: ` : '';
  273. const message = error.message ? error.message : JSON.stringify(error);
  274. let context = '';
  275. let stack = '';
  276. if (error.stack) {
  277. const format = (file, line, column) => {
  278. return `${file.split('\\').join('/').split('/').pop()}:${line}:${column}`;
  279. };
  280. const match = error.stack.match(/\n {4}at (.*) \((.*):(\d*):(\d*)\)/);
  281. if (match) {
  282. stack = `${match[1]} (${format(match[2], match[3], match[4])})`;
  283. } else {
  284. const match = error.stack.match(/\n {4}at (.*):(\d*):(\d*)/);
  285. if (match) {
  286. stack = `(${format(match[1], match[2], match[3])})`;
  287. } else {
  288. const match = error.stack.match(/\n {4}at (.*)\((.*)\)/);
  289. if (match) {
  290. stack = `(${format(match[1], match[2], match[3])})`;
  291. } else {
  292. const match = error.stack.match(/\s*@\s*(.*):(.*):(.*)/);
  293. if (match) {
  294. stack = `(${format(match[1], match[2], match[3])})`;
  295. } else {
  296. const match = error.stack.match(/.*\n\s*(.*)\s*/);
  297. if (match) {
  298. [, stack] = match;
  299. }
  300. }
  301. }
  302. }
  303. }
  304. }
  305. if (error.context) {
  306. context = typeof error.context === 'string' ? error.context : JSON.stringify(error.context);
  307. }
  308. this._telemetry.send('exception', {
  309. app_name: this.type,
  310. app_version: this.version,
  311. error_name: name,
  312. error_message: message,
  313. error_context: context,
  314. error_stack: stack,
  315. error_fatal: fatal ? true : false
  316. });
  317. }
  318. }
  319. event(name, params) {
  320. if (name && params) {
  321. params.app_name = this.type;
  322. params.app_version = this.version;
  323. this._telemetry.send(name, params);
  324. }
  325. }
  326. async _request(url, headers, encoding, callback, timeout) {
  327. if (!url.startsWith('data:')) {
  328. const date = new Date().getTime();
  329. const separator = (/\?/).test(url) ? '&' : '?';
  330. url = `${url}${separator}cb=${date}`;
  331. }
  332. return new Promise((resolve, reject) => {
  333. const request = new XMLHttpRequest();
  334. if (!encoding) {
  335. request.responseType = 'arraybuffer';
  336. }
  337. if (timeout) {
  338. request.timeout = timeout;
  339. }
  340. const progress = (value) => {
  341. if (callback) {
  342. callback(value);
  343. }
  344. };
  345. request.onload = () => {
  346. progress(0);
  347. if (request.status === 200) {
  348. let value = null;
  349. if (request.responseType === 'arraybuffer') {
  350. const buffer = new Uint8Array(request.response);
  351. value = new base.BinaryStream(buffer);
  352. } else {
  353. value = request.responseText;
  354. }
  355. resolve(value);
  356. } else {
  357. const error = new Error(`The web request failed with status code '${request.status}'.`);
  358. error.context = url;
  359. reject(error);
  360. }
  361. };
  362. request.onerror = () => {
  363. progress(0);
  364. const error = new Error(`The web request failed.`);
  365. error.context = url;
  366. reject(error);
  367. };
  368. request.ontimeout = () => {
  369. progress(0);
  370. request.abort();
  371. const error = new Error('The web request timed out.', 'timeout', url);
  372. error.context = url;
  373. reject(error);
  374. };
  375. request.onprogress = (e) => {
  376. if (e && e.lengthComputable) {
  377. progress(e.loaded / e.total * 100);
  378. }
  379. };
  380. request.open('GET', url, true);
  381. if (headers) {
  382. for (const [name, value] of Object.entries(headers)) {
  383. request.setRequestHeader(name, value);
  384. }
  385. }
  386. request.send();
  387. });
  388. }
  389. _url(file) {
  390. if (file.startsWith('./')) {
  391. file = file.substring(2);
  392. } else if (file.startsWith('/')) {
  393. file = file.substring(1);
  394. }
  395. const location = this.window.location;
  396. const pathname = location.pathname.endsWith('/') ?
  397. location.pathname :
  398. `${location.pathname.split('/').slice(0, -1).join('/')}/`;
  399. return `${location.protocol}//${location.host}${pathname}${file}`;
  400. }
  401. async _openModel(url, identifier, name) {
  402. this._view.show('welcome spinner');
  403. let context = null;
  404. try {
  405. const progress = (value) => {
  406. this._view.progress(value);
  407. };
  408. let stream = await this._request(url, null, null, progress);
  409. if (url.startsWith('https://raw.githubusercontent.com/') && stream.length < 150) {
  410. const buffer = stream.peek();
  411. const content = Array.from(buffer).map((c) => String.fromCodePoint(c)).join('');
  412. if (content.split('\n')[0] === 'version https://git-lfs.github.com/spec/v1') {
  413. url = url.replace('https://raw.githubusercontent.com/', 'https://media.githubusercontent.com/media/');
  414. stream = await this._request(url, null, null, progress);
  415. }
  416. }
  417. context = new browser.Context(this, url, identifier, name, stream);
  418. this._telemetry.set('session_engaged', 1);
  419. } catch (error) {
  420. await this._view.error(error, 'Model load request failed.');
  421. this._view.show('welcome');
  422. return null;
  423. }
  424. return await this._openContext(context);
  425. }
  426. async _open(file, files) {
  427. this._view.show('welcome spinner');
  428. const context = new browser.BrowserFileContext(this, file, files);
  429. try {
  430. await context.open();
  431. await this._openContext(context);
  432. } catch (error) {
  433. await this._view.error(error);
  434. }
  435. }
  436. async _openGist(gist) {
  437. this._view.show('welcome spinner');
  438. const url = `https://api.github.com/gists/${gist}`;
  439. try {
  440. const text = await this._request(url, { 'Content-Type': 'application/json' }, 'utf-8');
  441. const json = JSON.parse(text);
  442. let message = json.message;
  443. let file = null;
  444. if (!message) {
  445. file = Object.values(json.files).find((file) => this._view.accept(file.filename));
  446. if (!file) {
  447. message = 'Gist does not contain a model file.';
  448. }
  449. }
  450. if (message) {
  451. const error = new Error(message);
  452. error.name = 'Error while loading Gist.';
  453. throw error;
  454. }
  455. const identifier = file.filename;
  456. const encoder = new TextEncoder();
  457. const buffer = encoder.encode(file.content);
  458. const stream = new base.BinaryStream(buffer);
  459. const context = new browser.Context(this, '', identifier, null, stream);
  460. await this._openContext(context);
  461. } catch (error) {
  462. await this._view.error(error, 'Error while loading Gist.');
  463. this._view.show('welcome');
  464. }
  465. }
  466. async _openContext(context) {
  467. this._telemetry.set('session_engaged', 1);
  468. try {
  469. const attachment = await this._view.attach(context);
  470. if (attachment) {
  471. this._view.show(null);
  472. return 'context-open-attachment';
  473. }
  474. const model = await this._view.open(context);
  475. if (model) {
  476. this._view.show(null);
  477. this.document.title = context.name || context.identifier;
  478. return '';
  479. }
  480. this.document.title = '';
  481. return 'context-open-failed';
  482. } catch (error) {
  483. await this._view.error(error, error.name);
  484. return 'context-open-error';
  485. }
  486. }
  487. _setCookie(name, value, days) {
  488. this.document.cookie = `${name}=; Max-Age=0`;
  489. const location = this.window.location;
  490. const domain = location && location.hostname && location.hostname.indexOf('.') !== -1 ? `;domain=.${location.hostname.split('.').slice(-2).join('.')}` : '';
  491. const date = new Date();
  492. date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  493. this.document.cookie = `${name}=${value}${domain};path=/;expires=${date.toUTCString()}`;
  494. }
  495. _getCookie(name) {
  496. for (const cookie of this.document.cookie.split(';')) {
  497. const entry = cookie.split('=');
  498. if (entry[0].trim() === name) {
  499. return entry[1].trim();
  500. }
  501. }
  502. return '';
  503. }
  504. get(name) {
  505. try {
  506. if (typeof this.window.localStorage !== 'undefined') {
  507. const content = this.window.localStorage.getItem(name);
  508. return JSON.parse(content);
  509. }
  510. } catch {
  511. // continue regardless of error
  512. }
  513. return undefined;
  514. }
  515. set(name, value) {
  516. try {
  517. if (typeof this.window.localStorage !== 'undefined') {
  518. this.window.localStorage.setItem(name, JSON.stringify(value));
  519. }
  520. } catch {
  521. // continue regardless of error
  522. }
  523. }
  524. delete(name) {
  525. try {
  526. if (typeof this.window.localStorage !== 'undefined') {
  527. this.window.localStorage.removeItem(name);
  528. }
  529. } catch {
  530. // continue regardless of error
  531. }
  532. }
  533. _element(id) {
  534. return this.document.getElementById(id);
  535. }
  536. update() {
  537. }
  538. async message(message, alert, action) {
  539. return new Promise((resolve) => {
  540. const type = this.document.body.getAttribute('class');
  541. this._element('message-text').innerText = message || '';
  542. const button = this._element('message-button');
  543. if (action) {
  544. button.style.removeProperty('display');
  545. button.innerText = action;
  546. button.onclick = () => {
  547. button.onclick = null;
  548. this.document.body.setAttribute('class', type);
  549. resolve(0);
  550. };
  551. } else {
  552. button.style.display = 'none';
  553. button.onclick = null;
  554. }
  555. if (alert) {
  556. this.document.body.setAttribute('class', 'alert');
  557. } else {
  558. this.document.body.classList.add('notification');
  559. this.document.body.classList.remove('default');
  560. }
  561. if (action) {
  562. button.focus();
  563. }
  564. });
  565. }
  566. };
  567. browser.BrowserFileContext = class {
  568. constructor(host, file, blobs) {
  569. this._host = host;
  570. this._file = file;
  571. this._blobs = {};
  572. for (const blob of blobs) {
  573. this._blobs[blob.name] = blob;
  574. }
  575. }
  576. get identifier() {
  577. return this._file.name;
  578. }
  579. get stream() {
  580. return this._stream;
  581. }
  582. async request(file, encoding, basename) {
  583. if (basename !== undefined) {
  584. return this._host.request(file, encoding, basename);
  585. }
  586. const blob = this._blobs[file];
  587. if (!blob) {
  588. throw new Error(`File not found '${file}'.`);
  589. }
  590. return new Promise((resolve, reject) => {
  591. const reader = new FileReader();
  592. const size = 0x10000000;
  593. let position = 0;
  594. const chunks = [];
  595. reader.onload = (e) => {
  596. if (encoding) {
  597. resolve(e.target.result);
  598. } else {
  599. const buffer = new Uint8Array(e.target.result);
  600. if (position === 0 && buffer.length === blob.size) {
  601. const stream = new base.BinaryStream(buffer);
  602. resolve(stream);
  603. } else {
  604. chunks.push(buffer);
  605. position += buffer.length;
  606. if (position < blob.size) {
  607. const slice = blob.slice(position, Math.min(position + size, blob.size));
  608. reader.readAsArrayBuffer(slice);
  609. } else {
  610. const stream = new browser.FileStream(chunks, size, 0, position);
  611. resolve(stream);
  612. }
  613. }
  614. }
  615. };
  616. reader.onerror = (event) => {
  617. event = event || this._host.window.event;
  618. let message = '';
  619. const error = event.target.error;
  620. switch (error.code) {
  621. case error.NOT_FOUND_ERR:
  622. message = `File not found '${file}'.`;
  623. break;
  624. case error.NOT_READABLE_ERR:
  625. message = `File not readable '${file}'.`;
  626. break;
  627. case error.SECURITY_ERR:
  628. message = `File access denied '${file}'.`;
  629. break;
  630. default:
  631. message = error.message ? error.message : `File read '${error.code}' error '${file}'.`;
  632. break;
  633. }
  634. reject(new Error(message));
  635. };
  636. if (encoding === 'utf-8') {
  637. reader.readAsText(blob, encoding);
  638. } else {
  639. const slice = blob.slice(position, Math.min(position + size, blob.size));
  640. reader.readAsArrayBuffer(slice);
  641. }
  642. });
  643. }
  644. async require(id) {
  645. return this._host.require(id);
  646. }
  647. error(error, fatal) {
  648. this._host.exception(error, fatal);
  649. }
  650. async open() {
  651. this._stream = await this.request(this._file.name, null);
  652. }
  653. };
  654. browser.FileStream = class {
  655. constructor(chunks, size, start, length) {
  656. this._chunks = chunks;
  657. this._size = size;
  658. this._start = start;
  659. this._length = length;
  660. this._position = 0;
  661. }
  662. get position() {
  663. return this._position;
  664. }
  665. get length() {
  666. return this._length;
  667. }
  668. stream(length) {
  669. const file = new browser.FileStream(this._chunks, this._size, this._start + this._position, length);
  670. this.skip(length);
  671. return file;
  672. }
  673. seek(position) {
  674. this._position = position >= 0 ? position : this._length + position;
  675. }
  676. skip(offset) {
  677. this._position += offset;
  678. if (this._position > this._length) {
  679. throw new Error(`Expected ${this._position - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  680. }
  681. }
  682. peek(length) {
  683. length = length === undefined ? this._length - this._position : length;
  684. if (length < 0x10000000) {
  685. const position = this._fill(length);
  686. this._position -= length;
  687. return this._buffer.subarray(position, position + length);
  688. }
  689. const position = this._start + this._position;
  690. if (position % this._size === 0) {
  691. const index = Math.floor(position / this._size);
  692. const chunk = this._chunks[index];
  693. if (chunk && chunk.length === length) {
  694. return chunk;
  695. }
  696. }
  697. const buffer = new Uint8Array(length);
  698. this._read(buffer, position);
  699. return buffer;
  700. }
  701. read(length) {
  702. length = length === undefined ? this._length - this._position : length;
  703. if (length < 0x10000000) {
  704. const position = this._fill(length);
  705. return this._buffer.slice(position, position + length);
  706. }
  707. const position = this._start + this._position;
  708. this.skip(length);
  709. if (position % this._size === 0) {
  710. const index = Math.floor(position / this._size);
  711. const chunk = this._chunks[index];
  712. if (chunk && chunk.length === length) {
  713. return chunk;
  714. }
  715. }
  716. const buffer = new Uint8Array(length);
  717. this._read(buffer, position);
  718. return buffer;
  719. }
  720. _fill(length) {
  721. if (this._position + length > this._length) {
  722. throw new Error(`Expected ${this._position + length - this._length} more bytes. The file might be corrupted. Unexpected end of file.`);
  723. }
  724. if (!this._buffer || this._position < this._offset || this._position + length > this._offset + this._buffer.length) {
  725. this._offset = this._start + this._position;
  726. const length = Math.min(0x10000000, this._start + this._length - this._offset);
  727. if (!this._buffer || length !== this._buffer.length) {
  728. this._buffer = new Uint8Array(length);
  729. }
  730. this._read(this._buffer, this._offset);
  731. }
  732. const position = this._start + this._position - this._offset;
  733. this._position += length;
  734. return position;
  735. }
  736. _read(buffer, offset) {
  737. let index = Math.floor(offset / this._size);
  738. offset -= index * this._size;
  739. const chunk = this._chunks[index++];
  740. let destination = Math.min(chunk.length - offset, buffer.length);
  741. buffer.set(chunk.subarray(offset, offset + destination), 0);
  742. while (destination < buffer.length) {
  743. const chunk = this._chunks[index++];
  744. const size = Math.min(this._size, buffer.length - destination);
  745. buffer.set(chunk.subarray(0, size), destination);
  746. destination += size;
  747. }
  748. }
  749. };
  750. browser.Context = class {
  751. constructor(host, url, identifier, name, stream) {
  752. this._host = host;
  753. this._name = name;
  754. this._stream = stream;
  755. const parts = url.split('?')[0].split('/');
  756. this._identifier = parts.pop();
  757. this._base = parts.join('/');
  758. if (identifier) {
  759. this._identifier = identifier;
  760. }
  761. }
  762. get identifier() {
  763. return this._identifier;
  764. }
  765. get name() {
  766. return this._name;
  767. }
  768. get stream() {
  769. return this._stream;
  770. }
  771. async request(file, encoding, base) {
  772. base = base === undefined ? this._base : base;
  773. return this._host.request(file, encoding, base);
  774. }
  775. async require(id) {
  776. return this._host.require(id);
  777. }
  778. error(error, fatal) {
  779. this._host.exception(error, fatal);
  780. }
  781. };
  782. if (!('scrollBehavior' in window.document.documentElement.style)) {
  783. const __scrollTo__ = Element.prototype.scrollTo;
  784. Element.prototype.scrollTo = function(...args) {
  785. const [options] = args;
  786. if (options !== undefined) {
  787. if (options === null || typeof options !== 'object' || options.behavior === undefined || options.behavior === 'auto' || options.behavior === 'instant') {
  788. if (__scrollTo__) {
  789. __scrollTo__.apply(this, args);
  790. }
  791. } else {
  792. const now = () => window.performance && window.performance.now ? window.performance.now() : Date.now();
  793. const ease = (k) => 0.5 * (1 - Math.cos(Math.PI * k));
  794. const step = (context) => {
  795. const value = ease(Math.min((now() - context.startTime) / 468, 1));
  796. const x = context.startX + (context.x - context.startX) * value;
  797. const y = context.startY + (context.y - context.startY) * value;
  798. context.element.scrollLeft = x;
  799. context.element.scrollTop = y;
  800. if (x !== context.x || y !== context.y) {
  801. window.requestAnimationFrame(step.bind(window, context));
  802. }
  803. };
  804. const context = {
  805. element: this,
  806. x: typeof options.left === 'undefined' ? this.scrollLeft : ~~options.left,
  807. y: typeof options.top === 'undefined' ? this.scrollTop : ~~options.top,
  808. startX: this.scrollLeft,
  809. startY: this.scrollTop,
  810. startTime: now()
  811. };
  812. step(context);
  813. }
  814. }
  815. };
  816. }
  817. if (typeof window !== 'undefined' && window.exports) {
  818. window.exports.browser = browser;
  819. }
  820. export const Host = browser.Host;