<!--
  Any copyright is dedicated to the Public Domain.
  http://creativecommons.org/publicdomain/zero/1.0/
-->
<!DOCTYPE HTML>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>

<script src="../utils.js"></script>
<script type="text/javascript">
function wait_until_controlled() {
  return new Promise(function(resolve) {
    if (navigator.serviceWorker.controller) {
      return resolve('controlled');
    }
    navigator.serviceWorker.addEventListener('controllerchange', function onController() {
      if (navigator.serviceWorker.controller) {
        navigator.serviceWorker.removeEventListener('controllerchange', onController);
        return resolve('controlled');
      }
    });
  });
}
addEventListener('load', async function(event) {
  window.controlled = wait_until_controlled();
  window.registration =
    await navigator.serviceWorker.register('sw_download_canceled.js');
  let sw = registration.installing || registration.waiting ||
           registration.active;
  await waitForState(sw, 'activated');
  sw.postMessage('claim');
});

// Place to hold promises for stream closures reported by the SW.
window.streamClosed = {};

// The ServiceWorker will postMessage to this BroadcastChannel when the streams
// are closed.  (Alternately, the SW could have used the clients API to post at
// us, but the mechanism by which that operates would be different when this
// test is uplifted, and it's desirable to avoid timing changes.)
//
// The browser test will use this promise to wait on stream shutdown.
window.swStreamChannel = new BroadcastChannel("stream-closed");
function trackStreamClosure(path) {
  let resolve;
  const promise = new Promise(r => { resolve = r });
  window.streamClosed[path] = { promise, resolve };
}
window.swStreamChannel.onmessage = ({ data }) => {
  window.streamClosed[data.what].resolve(data);
};
</script>

</body>
</html>
