<!DOCTYPE html>
<meta charset="utf-8">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>

<body>
<script>
// Regression test for https://crbug.com/1244145:
// This test loads a same script file (`resources/v8-code-cache.js`)
// multiple times to trigger V8 Code Cache.
// Host defined options (including base URLs and nonces) are lost when the
// script is compiled using the cached metadata, and thus causing
// dynamic import failures due to wrong base URLs and wrong nonces.

function runTest(type, nonce, description) {
  promise_test(t => {
    return new Promise((resolve, reject) => {
      const iframe = document.createElement('iframe');
      iframe.src = 'resources/v8-code-cache-iframe.sub.html?nonce=' + nonce + '&type=' + type;
      iframe.onload = () => {
        // `window.promise` is set by `resources/v8-code-cache.js`.
        window.promise.then(resolve, reject);
      };
      document.body.appendChild(iframe);
      t.add_cleanup(() => iframe.remove());
    });
  }, type + ': ' + description);
}

// As `promise_test` are serialized, each iframe is created after previous
// iframes and scripts are completely loaded.
for (const type of ['text/javascript', 'module']) {
  // Cache the script in V8 Code Cache by running multiple times.
  runTest(type, 'abc', 'Run #1');
  runTest(type, 'abc', 'Run #2');
  runTest(type, 'abc', 'Run #3');
  runTest(type, 'abc', 'Run #4');
  // Changing the nonce seems to disable compilation cache, trigger compilation
  // using V8 Code Cache and thus expose the bug.
  runTest(type, 'def', 'Run #5');
}
</script>
