0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-03-03 17:34:47 -05:00

refactor: Use ES modules for internal runtime code (#17648)

This PR refactors all internal js files (except core) to be written as
ES modules.
`__bootstrap`has been mostly replaced with static imports in form in
`internal:[path to file from repo root]`.
To specify if files are ESM, an `esm` method has been added to
`Extension`, similar to the `js` method.
A new ModuleLoader called `InternalModuleLoader` has been added to
enable the loading of internal specifiers, which is used in all
situations except when a snapshot is only loaded, and not a new one is
created from it.

---------

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
This commit is contained in:
Leo Kettmeir 2023-02-07 20:22:46 +01:00 committed by GitHub
parent 65500f36e8
commit b4aa153097
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
123 changed files with 41574 additions and 41713 deletions

View file

@ -10,6 +10,9 @@ use crate::profiling::is_profiling;
pub fn create_js_runtime(setup: impl FnOnce() -> Vec<Extension>) -> JsRuntime { pub fn create_js_runtime(setup: impl FnOnce() -> Vec<Extension>) -> JsRuntime {
JsRuntime::new(RuntimeOptions { JsRuntime::new(RuntimeOptions {
extensions_with_js: setup(), extensions_with_js: setup(),
module_loader: Some(std::rc::Rc::new(
deno_core::InternalModuleLoader::new(None),
)),
..Default::default() ..Default::default()
}) })
} }

View file

@ -275,6 +275,7 @@ mod ts {
.build()], .build()],
extensions_with_js: vec![], extensions_with_js: vec![],
additional_files: files, additional_files: files,
additional_esm_files: vec![],
compression_cb: Some(Box::new(|vec, snapshot_slice| { compression_cb: Some(Box::new(|vec, snapshot_slice| {
vec.extend_from_slice( vec.extend_from_slice(
&zstd::bulk::compress(snapshot_slice, 22) &zstd::bulk::compress(snapshot_slice, 22)
@ -306,7 +307,7 @@ mod ts {
} }
} }
fn create_cli_snapshot(snapshot_path: PathBuf, files: Vec<PathBuf>) { fn create_cli_snapshot(snapshot_path: PathBuf, esm_files: Vec<PathBuf>) {
let extensions: Vec<Extension> = vec![ let extensions: Vec<Extension> = vec![
deno_webidl::init(), deno_webidl::init(),
deno_console::init(), deno_console::init(),
@ -343,7 +344,8 @@ fn create_cli_snapshot(snapshot_path: PathBuf, files: Vec<PathBuf>) {
startup_snapshot: Some(deno_runtime::js::deno_isolate_init()), startup_snapshot: Some(deno_runtime::js::deno_isolate_init()),
extensions, extensions,
extensions_with_js: vec![], extensions_with_js: vec![],
additional_files: files, additional_files: vec![],
additional_esm_files: esm_files,
compression_cb: Some(Box::new(|vec, snapshot_slice| { compression_cb: Some(Box::new(|vec, snapshot_slice| {
lzzzz::lz4_hc::compress_to_vec( lzzzz::lz4_hc::compress_to_vec(
snapshot_slice, snapshot_slice,
@ -448,13 +450,13 @@ fn main() {
let o = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let o = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let compiler_snapshot_path = o.join("COMPILER_SNAPSHOT.bin"); let compiler_snapshot_path = o.join("COMPILER_SNAPSHOT.bin");
let js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "tsc"); let js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "tsc", None);
ts::create_compiler_snapshot(compiler_snapshot_path, js_files, &c); ts::create_compiler_snapshot(compiler_snapshot_path, js_files, &c);
let cli_snapshot_path = o.join("CLI_SNAPSHOT.bin"); let cli_snapshot_path = o.join("CLI_SNAPSHOT.bin");
let mut js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js"); let mut esm_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js", None);
js_files.push(deno_runtime::js::get_99_main()); esm_files.push(deno_runtime::js::get_99_main());
create_cli_snapshot(cli_snapshot_path, js_files); create_cli_snapshot(cli_snapshot_path, esm_files);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {

View file

@ -1,13 +1,13 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const { setExitHandler } = window.__bootstrap.os; const internals = globalThis.__bootstrap.internals;
const { Console } = window.__bootstrap.console; import { setExitHandler } from "internal:runtime/js/30_os.js";
const { serializePermissions } = window.__bootstrap.permissions; import { Console } from "internal:ext/console/02_console.js";
const { assert } = window.__bootstrap.infra; import { serializePermissions } from "internal:runtime/js/10_permissions.js";
import { assert } from "internal:ext/web/00_infra.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayFrom, ArrayFrom,
ArrayPrototypeFilter, ArrayPrototypeFilter,
@ -33,7 +33,7 @@
Set, Set,
SymbolToStringTag, SymbolToStringTag,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const opSanitizerDelayResolveQueue = []; const opSanitizerDelayResolveQueue = [];
@ -1417,16 +1417,13 @@
return testFn; return testFn;
} }
window.__bootstrap.internals = { internals.testing = {
...window.__bootstrap.internals ?? {},
testing: {
runTests, runTests,
runBenchmarks, runBenchmarks,
enableTest, enableTest,
enableBench, enableBench,
},
}; };
window.__bootstrap.denoNs.bench = bench; import { denoNs } from "internal:runtime/js/90_deno_ns.js";
window.__bootstrap.denoNs.test = test; denoNs.bench = bench;
})(this); denoNs.test = test;

View file

@ -3844,3 +3844,15 @@ itest!(node_prefix_missing {
envs: env_vars_for_npm_tests_no_sync_download(), envs: env_vars_for_npm_tests_no_sync_download(),
exit_code: 1, exit_code: 1,
}); });
itest!(internal_import {
args: "run run/internal_import.ts",
output: "run/internal_import.ts.out",
exit_code: 1,
});
itest!(internal_dynamic_import {
args: "run run/internal_dynamic_import.ts",
output: "run/internal_dynamic_import.ts.out",
exit_code: 1,
});

View file

@ -1,5 +1,4 @@
1 1
queueMicrotask
error: Uncaught Error: bar error: Uncaught Error: bar
throw new Error("bar"); throw new Error("bar");
^ ^

View file

@ -0,0 +1 @@
await import("internal:runtime/js/01_build.js");

View file

@ -0,0 +1,4 @@
error: Uncaught TypeError: Cannot load internal module from external code
await import("internal:runtime/js/01_build.js");
^
at [WILDCARD]/internal_dynamic_import.ts:1:1

View file

@ -0,0 +1 @@
import "internal:runtime/js/01_build.js";

View file

@ -0,0 +1,8 @@
error: Unsupported scheme "internal" for module "internal:runtime/js/01_build.js". Supported schemes: [
"data",
"blob",
"file",
"http",
"https",
]
at [WILDCARD]

View file

@ -427,6 +427,8 @@
}); });
ObjectAssign(globalThis.__bootstrap, { core }); ObjectAssign(globalThis.__bootstrap, { core });
const internals = {};
ObjectAssign(globalThis.__bootstrap, { internals });
ObjectAssign(globalThis.Deno, { core }); ObjectAssign(globalThis.Deno, { core });
// Direct bindings on `globalThis` // Direct bindings on `globalThis`

View file

@ -267,9 +267,11 @@ pub fn host_import_module_dynamically_callback<'s>(
.unwrap() .unwrap()
.to_rust_string_lossy(scope); .to_rust_string_lossy(scope);
let is_internal_module = specifier_str.starts_with("internal:");
let resolver = v8::PromiseResolver::new(scope).unwrap(); let resolver = v8::PromiseResolver::new(scope).unwrap();
let promise = resolver.get_promise(scope); let promise = resolver.get_promise(scope);
if !is_internal_module {
let assertions = parse_import_assertions( let assertions = parse_import_assertions(
scope, scope,
import_assertions, import_assertions,
@ -305,7 +307,7 @@ pub fn host_import_module_dynamically_callback<'s>(
); );
state_rc.borrow_mut().notify_new_dynamic_import(); state_rc.borrow_mut().notify_new_dynamic_import();
} }
}
// Map errors from module resolution (not JS errors from module execution) to // Map errors from module resolution (not JS errors from module execution) to
// ones rethrown from this scope, so they include the call stack of the // ones rethrown from this scope, so they include the call stack of the
// dynamic import site. Error objects without any stack frames are assumed to // dynamic import site. Error objects without any stack frames are assumed to
@ -317,6 +319,14 @@ pub fn host_import_module_dynamically_callback<'s>(
let promise = promise.catch(scope, map_err).unwrap(); let promise = promise.catch(scope, map_err).unwrap();
if is_internal_module {
let message =
v8::String::new(scope, "Cannot load internal module from external code")
.unwrap();
let exception = v8::Exception::type_error(scope, message);
resolver.reject(scope, exception);
}
Some(promise) Some(promise)
} }

View file

@ -38,6 +38,7 @@ impl OpDecl {
#[derive(Default)] #[derive(Default)]
pub struct Extension { pub struct Extension {
js_files: Option<Vec<SourcePair>>, js_files: Option<Vec<SourcePair>>,
esm_files: Option<Vec<SourcePair>>,
ops: Option<Vec<OpDecl>>, ops: Option<Vec<OpDecl>>,
opstate_fn: Option<Box<OpStateFn>>, opstate_fn: Option<Box<OpStateFn>>,
middleware_fn: Option<Box<OpMiddlewareFn>>, middleware_fn: Option<Box<OpMiddlewareFn>>,
@ -81,13 +82,20 @@ impl Extension {
/// returns JS source code to be loaded into the isolate (either at snapshotting, /// returns JS source code to be loaded into the isolate (either at snapshotting,
/// or at startup). as a vector of a tuple of the file name, and the source code. /// or at startup). as a vector of a tuple of the file name, and the source code.
pub fn init_js(&self) -> &[SourcePair] { pub fn get_js_sources(&self) -> &[SourcePair] {
match &self.js_files { match &self.js_files {
Some(files) => files, Some(files) => files,
None => &[], None => &[],
} }
} }
pub fn get_esm_sources(&self) -> &[SourcePair] {
match &self.esm_files {
Some(files) => files,
None => &[],
}
}
/// Called at JsRuntime startup to initialize ops in the isolate. /// Called at JsRuntime startup to initialize ops in the isolate.
pub fn init_ops(&mut self) -> Option<Vec<OpDecl>> { pub fn init_ops(&mut self) -> Option<Vec<OpDecl>> {
// TODO(@AaronO): maybe make op registration idempotent // TODO(@AaronO): maybe make op registration idempotent
@ -145,6 +153,7 @@ impl Extension {
#[derive(Default)] #[derive(Default)]
pub struct ExtensionBuilder { pub struct ExtensionBuilder {
js: Vec<SourcePair>, js: Vec<SourcePair>,
esm: Vec<SourcePair>,
ops: Vec<OpDecl>, ops: Vec<OpDecl>,
state: Option<Box<OpStateFn>>, state: Option<Box<OpStateFn>>,
middleware: Option<Box<OpMiddlewareFn>>, middleware: Option<Box<OpMiddlewareFn>>,
@ -164,6 +173,11 @@ impl ExtensionBuilder {
self self
} }
pub fn esm(&mut self, js_files: Vec<SourcePair>) -> &mut Self {
self.esm.extend(js_files);
self
}
pub fn ops(&mut self, ops: Vec<OpDecl>) -> &mut Self { pub fn ops(&mut self, ops: Vec<OpDecl>) -> &mut Self {
self.ops.extend(ops); self.ops.extend(ops);
self self
@ -195,10 +209,12 @@ impl ExtensionBuilder {
pub fn build(&mut self) -> Extension { pub fn build(&mut self) -> Extension {
let js_files = Some(std::mem::take(&mut self.js)); let js_files = Some(std::mem::take(&mut self.js));
let esm_files = Some(std::mem::take(&mut self.esm));
let ops = Some(std::mem::take(&mut self.ops)); let ops = Some(std::mem::take(&mut self.ops));
let deps = Some(std::mem::take(&mut self.deps)); let deps = Some(std::mem::take(&mut self.deps));
Extension { Extension {
js_files, js_files,
esm_files,
ops, ops,
opstate_fn: self.state.take(), opstate_fn: self.state.take(),
middleware_fn: self.middleware.take(), middleware_fn: self.middleware.take(),

View file

@ -73,6 +73,7 @@ pub use crate::module_specifier::ModuleResolutionError;
pub use crate::module_specifier::ModuleSpecifier; pub use crate::module_specifier::ModuleSpecifier;
pub use crate::module_specifier::DUMMY_SPECIFIER; pub use crate::module_specifier::DUMMY_SPECIFIER;
pub use crate::modules::FsModuleLoader; pub use crate::modules::FsModuleLoader;
pub use crate::modules::InternalModuleLoader;
pub use crate::modules::ModuleId; pub use crate::modules::ModuleId;
pub use crate::modules::ModuleLoader; pub use crate::modules::ModuleLoader;
pub use crate::modules::ModuleSource; pub use crate::modules::ModuleSource;

View file

@ -292,6 +292,69 @@ impl ModuleLoader for NoopModuleLoader {
} }
} }
pub struct InternalModuleLoader(Rc<dyn ModuleLoader>);
impl InternalModuleLoader {
pub fn new(module_loader: Option<Rc<dyn ModuleLoader>>) -> Self {
InternalModuleLoader(
module_loader.unwrap_or_else(|| Rc::new(NoopModuleLoader)),
)
}
}
impl ModuleLoader for InternalModuleLoader {
fn resolve(
&self,
specifier: &str,
referrer: &str,
kind: ResolutionKind,
) -> Result<ModuleSpecifier, Error> {
if let Ok(url_specifier) = ModuleSpecifier::parse(specifier) {
if url_specifier.scheme() == "internal" {
let referrer_specifier = ModuleSpecifier::parse(referrer).ok();
if referrer == "." || referrer_specifier.unwrap().scheme() == "internal"
{
return Ok(url_specifier);
} else {
return Err(generic_error(
"Cannot load internal module from external code",
));
};
}
}
self.0.resolve(specifier, referrer, kind)
}
fn load(
&self,
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<ModuleSpecifier>,
is_dyn_import: bool,
) -> Pin<Box<ModuleSourceFuture>> {
self.0.load(module_specifier, maybe_referrer, is_dyn_import)
}
fn prepare_load(
&self,
op_state: Rc<RefCell<OpState>>,
module_specifier: &ModuleSpecifier,
maybe_referrer: Option<String>,
is_dyn_import: bool,
) -> Pin<Box<dyn Future<Output = Result<(), Error>>>> {
if module_specifier.scheme() == "internal" {
return async { Ok(()) }.boxed_local();
}
self.0.prepare_load(
op_state,
module_specifier,
maybe_referrer,
is_dyn_import,
)
}
}
/// Basic file system module loader. /// Basic file system module loader.
/// ///
/// Note that this loader will **block** event loop /// Note that this loader will **block** event loop
@ -2508,4 +2571,33 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error();
) )
.unwrap(); .unwrap();
} }
#[test]
fn internal_module_loader() {
let loader = InternalModuleLoader::new(None);
assert!(loader
.resolve("internal:foo", "internal:bar", ResolutionKind::Import)
.is_ok());
assert_eq!(
loader
.resolve("internal:foo", "file://bar", ResolutionKind::Import)
.err()
.map(|e| e.to_string()),
Some("Cannot load internal module from external code".to_string())
);
assert_eq!(
loader
.resolve("file://foo", "file://bar", ResolutionKind::Import)
.err()
.map(|e| e.to_string()),
Some("Module loading is not supported".to_string())
);
assert_eq!(
loader
.resolve("file://foo", "internal:bar", ResolutionKind::Import)
.err()
.map(|e| e.to_string()),
Some("Module loading is not supported".to_string())
);
}
} }

View file

@ -13,17 +13,18 @@ use crate::modules::ModuleId;
use crate::modules::ModuleLoadId; use crate::modules::ModuleLoadId;
use crate::modules::ModuleLoader; use crate::modules::ModuleLoader;
use crate::modules::ModuleMap; use crate::modules::ModuleMap;
use crate::modules::NoopModuleLoader;
use crate::op_void_async; use crate::op_void_async;
use crate::op_void_sync; use crate::op_void_sync;
use crate::ops::*; use crate::ops::*;
use crate::source_map::SourceMapCache; use crate::source_map::SourceMapCache;
use crate::source_map::SourceMapGetter; use crate::source_map::SourceMapGetter;
use crate::Extension; use crate::Extension;
use crate::NoopModuleLoader;
use crate::OpMiddlewareFn; use crate::OpMiddlewareFn;
use crate::OpResult; use crate::OpResult;
use crate::OpState; use crate::OpState;
use crate::PromiseId; use crate::PromiseId;
use anyhow::Context as AnyhowContext;
use anyhow::Error; use anyhow::Error;
use futures::channel::oneshot; use futures::channel::oneshot;
use futures::future::poll_fn; use futures::future::poll_fn;
@ -605,9 +606,16 @@ impl JsRuntime {
None None
}; };
let loader = options let loader = if snapshot_options != SnapshotOptions::Load {
Rc::new(crate::modules::InternalModuleLoader::new(
options.module_loader,
))
} else {
options
.module_loader .module_loader
.unwrap_or_else(|| Rc::new(NoopModuleLoader)); .unwrap_or_else(|| Rc::new(NoopModuleLoader))
};
{ {
let mut state = state_rc.borrow_mut(); let mut state = state_rc.borrow_mut();
state.global_realm = Some(JsRealm(global_context.clone())); state.global_realm = Some(JsRealm(global_context.clone()));
@ -805,12 +813,32 @@ impl JsRuntime {
// Take extensions to avoid double-borrow // Take extensions to avoid double-borrow
let extensions = std::mem::take(&mut self.extensions_with_js); let extensions = std::mem::take(&mut self.extensions_with_js);
for ext in &extensions { for ext in &extensions {
let js_files = ext.init_js(); {
let js_files = ext.get_esm_sources();
for (filename, source) in js_files {
futures::executor::block_on(async {
let id = self
.load_side_module(
&ModuleSpecifier::parse(filename)?,
Some(source.to_string()),
)
.await?;
let receiver = self.mod_evaluate(id);
self.run_event_loop(false).await?;
receiver.await?
})
.with_context(|| format!("Couldn't execute '{filename}'"))?;
}
}
{
let js_files = ext.get_js_sources();
for (filename, source) in js_files { for (filename, source) in js_files {
// TODO(@AaronO): use JsRuntime::execute_static() here to move src off heap // TODO(@AaronO): use JsRuntime::execute_static() here to move src off heap
realm.execute_script(self.v8_isolate(), filename, source)?; realm.execute_script(self.v8_isolate(), filename, source)?;
} }
} }
}
// Restore extensions // Restore extensions
self.extensions_with_js = extensions; self.extensions_with_js = extensions;

View file

@ -1,10 +1,12 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use anyhow::Context;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
use crate::Extension; use crate::Extension;
use crate::JsRuntime; use crate::JsRuntime;
use crate::ModuleSpecifier;
use crate::RuntimeOptions; use crate::RuntimeOptions;
use crate::Snapshot; use crate::Snapshot;
@ -17,6 +19,7 @@ pub struct CreateSnapshotOptions {
pub extensions: Vec<Extension>, pub extensions: Vec<Extension>,
pub extensions_with_js: Vec<Extension>, pub extensions_with_js: Vec<Extension>,
pub additional_files: Vec<PathBuf>, pub additional_files: Vec<PathBuf>,
pub additional_esm_files: Vec<PathBuf>,
pub compression_cb: Option<Box<CompressionCb>>, pub compression_cb: Option<Box<CompressionCb>>,
} }
@ -44,6 +47,27 @@ pub fn create_snapshot(create_snapshot_options: CreateSnapshotOptions) {
) )
.unwrap(); .unwrap();
} }
for file in create_snapshot_options.additional_esm_files {
let display_path = file.strip_prefix(display_root).unwrap_or(&file);
let display_path_str = display_path.display().to_string();
let filename =
&("internal:".to_string() + &display_path_str.replace('\\', "/"));
futures::executor::block_on(async {
let id = js_runtime
.load_side_module(
&ModuleSpecifier::parse(filename)?,
Some(std::fs::read_to_string(&file)?),
)
.await?;
let receiver = js_runtime.mod_evaluate(id);
js_runtime.run_event_loop(false).await?;
receiver.await?
})
.with_context(|| format!("Couldn't execute '{}'", file.display()))
.unwrap();
}
let snapshot = js_runtime.snapshot(); let snapshot = js_runtime.snapshot();
let snapshot_slice: &[u8] = &snapshot; let snapshot_slice: &[u8] = &snapshot;
@ -79,9 +103,12 @@ pub fn create_snapshot(create_snapshot_options: CreateSnapshotOptions) {
); );
} }
pub type FilterFn = Box<dyn Fn(&PathBuf) -> bool>;
pub fn get_js_files( pub fn get_js_files(
cargo_manifest_dir: &'static str, cargo_manifest_dir: &'static str,
directory: &str, directory: &str,
filter: Option<FilterFn>,
) -> Vec<PathBuf> { ) -> Vec<PathBuf> {
let manifest_dir = Path::new(cargo_manifest_dir); let manifest_dir = Path::new(cargo_manifest_dir);
let mut js_files = std::fs::read_dir(directory) let mut js_files = std::fs::read_dir(directory)
@ -92,7 +119,7 @@ pub fn get_js_files(
}) })
.filter(|path| { .filter(|path| {
path.extension().unwrap_or_default() == "js" path.extension().unwrap_or_default() == "js"
&& !path.ends_with("99_main.js") && filter.as_ref().map(|filter| filter(path)).unwrap_or(true)
}) })
.collect::<Vec<PathBuf>>(); .collect::<Vec<PathBuf>>();
js_files.sort(); js_files.sort();

View file

@ -2,23 +2,23 @@
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { MessageEvent, defineEventHandler, setTarget } = import {
window.__bootstrap.event; defineEventHandler,
const { EventTarget } = window.__bootstrap.eventTarget; EventTarget,
const { DOMException } = window.__bootstrap.domException; setTarget,
} from "internal:ext/web/02_event.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeIndexOf, ArrayPrototypeIndexOf,
ArrayPrototypeSplice, ArrayPrototypeSplice,
ArrayPrototypePush, ArrayPrototypePush,
Symbol, Symbol,
Uint8Array, Uint8Array,
} = window.__bootstrap.primordials; } = primordials;
const _name = Symbol("[[name]]"); const _name = Symbol("[[name]]");
const _closed = Symbol("[[closed]]"); const _closed = Symbol("[[closed]]");
@ -147,5 +147,4 @@
defineEventHandler(BroadcastChannel.prototype, "messageerror"); defineEventHandler(BroadcastChannel.prototype, "messageerror");
const BroadcastChannelPrototype = BroadcastChannel.prototype; const BroadcastChannelPrototype = BroadcastChannel.prototype;
window.__bootstrap.broadcastChannel = { BroadcastChannel }; export { BroadcastChannel };
})(this);

View file

@ -112,7 +112,7 @@ pub fn init<BC: BroadcastChannel + 'static>(
) -> Extension { ) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web"]) .dependencies(vec!["deno_webidl", "deno_web"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/broadcast_channel", prefix "internal:ext/broadcast_channel",
"01_broadcast_channel.js", "01_broadcast_channel.js",
)) ))

42
ext/cache/01_cache.js vendored
View file

@ -1,23 +1,22 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.__bootstrap.core; import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = window.__bootstrap.webidl; const primordials = globalThis.__bootstrap.primordials;
const { const {
Symbol, Symbol,
TypeError, TypeError,
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
} = window.__bootstrap.primordials; } = primordials;
const { import {
Request, Request,
toInnerResponse, RequestPrototype,
toInnerRequest, toInnerRequest,
} = window.__bootstrap.fetch; } from "internal:ext/fetch/23_request.js";
const { URLPrototype } = window.__bootstrap.url; import { toInnerResponse } from "internal:ext/fetch/23_response.js";
const RequestPrototype = Request.prototype; import { URLPrototype } from "internal:ext/url/00_url.js";
const { getHeader } = window.__bootstrap.headers; import { getHeader } from "internal:ext/fetch/20_headers.js";
const { readableStreamForRid } = window.__bootstrap.streams; import { readableStreamForRid } from "internal:ext/web/06_streams.js";
class CacheStorage { class CacheStorage {
constructor() { constructor() {
@ -282,15 +281,12 @@
const CacheStoragePrototype = CacheStorage.prototype; const CacheStoragePrototype = CacheStorage.prototype;
const CachePrototype = Cache.prototype; const CachePrototype = Cache.prototype;
let cacheStorage; let cacheStorageStorage;
window.__bootstrap.caches = { function cacheStorage() {
CacheStorage, if (!cacheStorageStorage) {
Cache, cacheStorageStorage = webidl.createBranded(CacheStorage);
cacheStorage() {
if (!cacheStorage) {
cacheStorage = webidl.createBranded(CacheStorage);
} }
return cacheStorage; return cacheStorageStorage;
}, }
};
})(this); export { Cache, CacheStorage, cacheStorage };

2
ext/cache/lib.rs vendored
View file

@ -27,7 +27,7 @@ pub fn init<CA: Cache + 'static>(
) -> Extension { ) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web", "deno_url", "deno_fetch"]) .dependencies(vec!["deno_webidl", "deno_web", "deno_url", "deno_fetch"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/cache", prefix "internal:ext/cache",
"01_cache.js", "01_cache.js",
)) ))

View file

@ -2,14 +2,12 @@
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
"use strict"; const primordials = globalThis.__bootstrap.primordials;
((window) => {
const { const {
RegExp, RegExp,
StringPrototypeReplace, StringPrototypeReplace,
ArrayPrototypeJoin, ArrayPrototypeJoin,
} = window.__bootstrap.primordials; } = primordials;
let noColor = false; let noColor = false;
@ -92,20 +90,19 @@
return !noColor ? fn : (s) => s; return !noColor ? fn : (s) => s;
} }
window.__bootstrap.colors = { export {
bold,
italic,
yellow,
cyan,
red,
green,
bgRed, bgRed,
white, bold,
gray, cyan,
magenta,
stripColor,
maybeColor,
setNoColor,
getNoColor, getNoColor,
gray,
green,
italic,
magenta,
maybeColor,
red,
setNoColor,
stripColor,
white,
yellow,
}; };
})(this);

View file

@ -2,11 +2,9 @@
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
"use strict"; const core = globalThis.Deno.core;
const internals = globalThis.__bootstrap.internals;
((window) => { const primordials = globalThis.__bootstrap.primordials;
const core = window.Deno.core;
const colors = window.__bootstrap.colors;
const { const {
AggregateErrorPrototype, AggregateErrorPrototype,
ArrayPrototypeUnshift, ArrayPrototypeUnshift,
@ -117,7 +115,8 @@
TypedArrayPrototypeGetSymbolToStringTag, TypedArrayPrototypeGetSymbolToStringTag,
WeakMapPrototype, WeakMapPrototype,
WeakSetPrototype, WeakSetPrototype,
} = window.__bootstrap.primordials; } = primordials;
import * as colors from "internal:ext/console/01_colors.js";
function isInvalidDate(x) { function isInvalidDate(x) {
return isNaN(DatePrototypeGetTime(x)); return isNaN(DatePrototypeGetTime(x));
@ -823,8 +822,7 @@
value, value,
inspectOptions, inspectOptions,
) { ) {
const abbreviateSize = const abbreviateSize = typeof inspectOptions.strAbbreviateSize === "undefined"
typeof inspectOptions.strAbbreviateSize === "undefined"
? STR_ABBREVIATE_SIZE ? STR_ABBREVIATE_SIZE
: inspectOptions.strAbbreviateSize; : inspectOptions.strAbbreviateSize;
const green = maybeColor(colors.green, inspectOptions); const green = maybeColor(colors.green, inspectOptions);
@ -2364,23 +2362,19 @@
} }
// Expose these fields to internalObject for tests. // Expose these fields to internalObject for tests.
window.__bootstrap.internals = { internals.Console = Console;
...window.__bootstrap.internals ?? {}, internals.cssToAnsi = cssToAnsi;
Console, internals.inspectArgs = inspectArgs;
cssToAnsi, internals.parseCss = parseCss;
inspectArgs, internals.parseCssColor = parseCssColor;
parseCss,
parseCssColor,
};
window.__bootstrap.console = { export {
CSI,
inspectArgs,
Console, Console,
createFilteredInspectProxy,
CSI,
customInspect, customInspect,
inspect, inspect,
wrapConsole, inspectArgs,
createFilteredInspectProxy,
quoteString, quoteString,
wrapConsole,
}; };
})(this);

View file

@ -3,14 +3,10 @@
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
declare namespace globalThis { declare module "internal:ext/console/02_console.js" {
declare namespace __bootstrap { function createFilteredInspectProxy<TObject>(params: {
declare namespace console {
declare function createFilteredInspectProxy<TObject>(params: {
object: TObject; object: TObject;
keys: (keyof TObject)[]; keys: (keyof TObject)[];
evaluate: boolean; evaluate: boolean;
}): Record<string, unknown>; }): Record<string, unknown>;
} }
}
}

View file

@ -6,7 +6,7 @@ use std::path::PathBuf;
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/console", prefix "internal:ext/console",
"01_colors.js", "01_colors.js",
"02_console.js", "02_console.js",

View file

@ -6,14 +6,11 @@
/// <reference path="../webidl/internal.d.ts" /> /// <reference path="../webidl/internal.d.ts" />
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; const primordials = globalThis.__bootstrap.primordials;
const { DOMException } = window.__bootstrap.domException; import * as webidl from "internal:ext/webidl/00_webidl.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayBufferIsView, ArrayBufferIsView,
@ -49,7 +46,7 @@
WeakMap, WeakMap,
WeakMapPrototypeGet, WeakMapPrototypeGet,
WeakMapPrototypeSet, WeakMapPrototypeSet,
} = window.__bootstrap.primordials; } = primordials;
// P-521 is not yet supported. // P-521 is not yet supported.
const supportedNamedCurves = ["P-256", "P-384"]; const supportedNamedCurves = ["P-256", "P-384"];
@ -4718,10 +4715,5 @@
webidl.configurePrototype(Crypto); webidl.configurePrototype(Crypto);
const CryptoPrototype = Crypto.prototype; const CryptoPrototype = Crypto.prototype;
window.__bootstrap.crypto = { const crypto = webidl.createBranded(Crypto);
SubtleCrypto, export { Crypto, crypto, CryptoKey, SubtleCrypto };
crypto: webidl.createBranded(Crypto),
Crypto,
CryptoKey,
};
})(this);

View file

@ -4,17 +4,15 @@
/// <reference path="../../core/lib.deno_core.d.ts" /> /// <reference path="../../core/lib.deno_core.d.ts" />
/// <reference path="../webidl/internal.d.ts" /> /// <reference path="../webidl/internal.d.ts" />
"use strict"; const primordials = globalThis.__bootstrap.primordials;
import * as webidl from "internal:ext/webidl/00_webidl.js";
((window) => { import { CryptoKey } from "internal:ext/crypto/00_crypto.js";
const webidl = window.__bootstrap.webidl;
const { CryptoKey } = window.__bootstrap.crypto;
const { const {
ArrayBufferIsView, ArrayBufferIsView,
ArrayBufferPrototype, ArrayBufferPrototype,
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
SafeArrayIterator, SafeArrayIterator,
} = window.__bootstrap.primordials; } = primordials;
webidl.converters.AlgorithmIdentifier = (V, opts) => { webidl.converters.AlgorithmIdentifier = (V, opts) => {
// Union for (object or DOMString) // Union for (object or DOMString)
@ -66,7 +64,7 @@
webidl.converters.HashAlgorithmIdentifier = webidl.converters.HashAlgorithmIdentifier =
webidl.converters.AlgorithmIdentifier; webidl.converters.AlgorithmIdentifier;
/** @type {__bootstrap.webidl.Dictionary} */ /** @type {webidl.Dictionary} */
const dictAlgorithm = [{ const dictAlgorithm = [{
key: "name", key: "name",
converter: webidl.converters.DOMString, converter: webidl.converters.DOMString,
@ -78,7 +76,7 @@
webidl.converters.BigInteger = webidl.converters.Uint8Array; webidl.converters.BigInteger = webidl.converters.Uint8Array;
/** @type {__bootstrap.webidl.Dictionary} */ /** @type {webidl.Dictionary} */
const dictRsaKeyGenParams = [ const dictRsaKeyGenParams = [
...new SafeArrayIterator(dictAlgorithm), ...new SafeArrayIterator(dictAlgorithm),
{ {
@ -484,4 +482,3 @@
webidl.converters.EcdhKeyDeriveParams = webidl webidl.converters.EcdhKeyDeriveParams = webidl
.createDictionaryConverter("EcdhKeyDeriveParams", dictEcdhKeyDeriveParams); .createDictionaryConverter("EcdhKeyDeriveParams", dictEcdhKeyDeriveParams);
})(this);

View file

@ -75,7 +75,7 @@ use crate::shared::RawKeyData;
pub fn init(maybe_seed: Option<u64>) -> Extension { pub fn init(maybe_seed: Option<u64>) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web"]) .dependencies(vec!["deno_webidl", "deno_web"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/crypto", prefix "internal:ext/crypto",
"00_crypto.js", "00_crypto.js",
"01_webidl.js", "01_webidl.js",

View file

@ -1,22 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const { TypeError } = window.__bootstrap.primordials;
function requiredArguments(
name,
length,
required,
) {
if (length < required) {
const errMsg = `${name} requires at least ${required} argument${
required === 1 ? "" : "s"
}, but only ${length} present`;
throw new TypeError(errMsg);
}
}
window.__bootstrap.fetchUtil = {
requiredArguments,
};
})(this);

View file

@ -8,19 +8,18 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = window.__bootstrap.webidl; import {
const { byteLowerCase,
collectHttpQuotedString,
collectSequenceOfCodepoints,
HTTP_TAB_OR_SPACE_PREFIX_RE, HTTP_TAB_OR_SPACE_PREFIX_RE,
HTTP_TAB_OR_SPACE_SUFFIX_RE, HTTP_TAB_OR_SPACE_SUFFIX_RE,
HTTP_TOKEN_CODE_POINT_RE, HTTP_TOKEN_CODE_POINT_RE,
byteLowerCase,
collectSequenceOfCodepoints,
collectHttpQuotedString,
httpTrim, httpTrim,
} = window.__bootstrap.infra; } from "internal:ext/web/00_infra.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayIsArray, ArrayIsArray,
ArrayPrototypeMap, ArrayPrototypeMap,
@ -38,7 +37,7 @@
SymbolIterator, SymbolIterator,
StringPrototypeReplaceAll, StringPrototypeReplaceAll,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const _headerList = Symbol("header list"); const _headerList = Symbol("header list");
const _iterableHeaders = Symbol("iterable headers"); const _iterableHeaders = Symbol("iterable headers");
@ -452,7 +451,7 @@
} }
/** /**
* @param {Headers} * @param {Headers} headers
* @returns {HeaderList} * @returns {HeaderList}
*/ */
function headerListFromHeaders(headers) { function headerListFromHeaders(headers) {
@ -460,20 +459,19 @@
} }
/** /**
* @param {Headers} * @param {Headers} headers
* @returns {"immutable" | "request" | "request-no-cors" | "response" | "none"} * @returns {"immutable" | "request" | "request-no-cors" | "response" | "none"}
*/ */
function guardFromHeaders(headers) { function guardFromHeaders(headers) {
return headers[_guard]; return headers[_guard];
} }
window.__bootstrap.headers = { export {
headersFromHeaderList,
headerListFromHeaders,
getDecodeSplitHeader,
guardFromHeaders,
fillHeaders, fillHeaders,
getDecodeSplitHeader,
getHeader, getHeader,
guardFromHeaders,
headerListFromHeaders,
Headers, Headers,
headersFromHeaderList,
}; };
})(this);

View file

@ -8,13 +8,16 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core; import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = globalThis.__bootstrap.webidl; import {
const { Blob, BlobPrototype, File, FilePrototype } = Blob,
globalThis.__bootstrap.file; BlobPrototype,
File,
FilePrototype,
} from "internal:ext/web/09_file.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypePush, ArrayPrototypePush,
ArrayPrototypeSlice, ArrayPrototypeSlice,
@ -36,7 +39,7 @@
StringPrototypeReplaceAll, StringPrototypeReplaceAll,
TypeError, TypeError,
TypedArrayPrototypeSubarray, TypedArrayPrototypeSubarray,
} = window.__bootstrap.primordials; } = primordials;
const entryList = Symbol("entry list"); const entryList = Symbol("entry list");
@ -513,11 +516,10 @@
webidl.converters["FormData"] = webidl webidl.converters["FormData"] = webidl
.createInterfaceConverter("FormData", FormDataPrototype); .createInterfaceConverter("FormData", FormDataPrototype);
globalThis.__bootstrap.formData = { export {
FormData, FormData,
formDataFromEntries,
FormDataPrototype, FormDataPrototype,
formDataToBlob, formDataToBlob,
parseFormData, parseFormData,
formDataFromEntries,
}; };
})(globalThis);

View file

@ -10,31 +10,32 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core; import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = globalThis.__bootstrap.webidl; import {
const { parseUrlEncoded } = globalThis.__bootstrap.url; parseUrlEncoded,
const { URLSearchParamsPrototype } = globalThis.__bootstrap.url; URLSearchParamsPrototype,
const { } from "internal:ext/url/00_url.js";
parseFormData, import {
formDataFromEntries, formDataFromEntries,
formDataToBlob,
FormDataPrototype, FormDataPrototype,
} = globalThis.__bootstrap.formData; formDataToBlob,
const mimesniff = globalThis.__bootstrap.mimesniff; parseFormData,
const { BlobPrototype } = globalThis.__bootstrap.file; } from "internal:ext/fetch/21_formdata.js";
const { import * as mimesniff from "internal:ext/web/01_mimesniff.js";
isReadableStreamDisturbed, import { BlobPrototype } from "internal:ext/web/09_file.js";
errorReadableStream, import {
readableStreamClose,
readableStreamDisturb,
readableStreamCollectIntoUint8Array,
readableStreamThrowIfErrored,
createProxy, createProxy,
errorReadableStream,
isReadableStreamDisturbed,
readableStreamClose,
readableStreamCollectIntoUint8Array,
readableStreamDisturb,
ReadableStreamPrototype, ReadableStreamPrototype,
} = globalThis.__bootstrap.streams; readableStreamThrowIfErrored,
} from "internal:ext/web/06_streams.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayBufferIsView, ArrayBufferIsView,
@ -48,7 +49,7 @@
TypeError, TypeError,
Uint8Array, Uint8Array,
Uint8ArrayPrototype, Uint8ArrayPrototype,
} = window.__bootstrap.primordials; } = primordials;
/** /**
* @param {Uint8Array | string} chunk * @param {Uint8Array | string} chunk
@ -467,5 +468,4 @@
webidl.converters["BodyInit_DOMString"], webidl.converters["BodyInit_DOMString"],
); );
window.__bootstrap.fetchBody = { mixinBody, InnerBody, extractBody }; export { extractBody, InnerBody, mixinBody };
})(globalThis);

View file

@ -9,10 +9,8 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
/** /**
@ -41,8 +39,4 @@
} }
const HttpClientPrototype = HttpClient.prototype; const HttpClientPrototype = HttpClient.prototype;
window.__bootstrap.fetch ??= {}; export { createHttpClient, HttpClient, HttpClientPrototype };
window.__bootstrap.fetch.createHttpClient = createHttpClient;
window.__bootstrap.fetch.HttpClient = HttpClient;
window.__bootstrap.fetch.HttpClientPrototype = HttpClientPrototype;
})(globalThis);

View file

@ -8,26 +8,32 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = window.__bootstrap.webidl; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const consoleInternal = window.__bootstrap.console; import {
const { HTTP_TOKEN_CODE_POINT_RE, byteUpperCase } = window.__bootstrap.infra; byteUpperCase,
const { URL } = window.__bootstrap.url; HTTP_TOKEN_CODE_POINT_RE,
const { guardFromHeaders } = window.__bootstrap.headers; } from "internal:ext/web/00_infra.js";
const { mixinBody, extractBody, InnerBody } = window.__bootstrap.fetchBody; import { URL } from "internal:ext/url/00_url.js";
const { getLocationHref } = window.__bootstrap.location; import {
const { extractMimeType } = window.__bootstrap.mimesniff; extractBody,
const { blobFromObjectUrl } = window.__bootstrap.file; InnerBody,
const { mixinBody,
headersFromHeaderList, } from "internal:ext/fetch/22_body.js";
headerListFromHeaders, import { getLocationHref } from "internal:ext/web/12_location.js";
import { extractMimeType } from "internal:ext/web/01_mimesniff.js";
import { blobFromObjectUrl } from "internal:ext/web/09_file.js";
import {
fillHeaders, fillHeaders,
getDecodeSplitHeader, getDecodeSplitHeader,
} = window.__bootstrap.headers; guardFromHeaders,
const { HttpClientPrototype } = window.__bootstrap.fetch; headerListFromHeaders,
const abortSignal = window.__bootstrap.abortSignal; headersFromHeaderList,
} from "internal:ext/fetch/20_headers.js";
import { HttpClientPrototype } from "internal:ext/fetch/22_http_client.js";
import * as abortSignal from "internal:ext/web/03_abort_signal.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeMap, ArrayPrototypeMap,
ArrayPrototypeSlice, ArrayPrototypeSlice,
@ -38,7 +44,7 @@
Symbol, Symbol,
SymbolFor, SymbolFor,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const _request = Symbol("request"); const _request = Symbol("request");
const _headers = Symbol("headers"); const _headers = Symbol("headers");
@ -530,7 +536,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(RequestPrototype, this), evaluate: ObjectPrototypeIsPrototypeOf(RequestPrototype, this),
keys: [ keys: [
@ -653,12 +659,13 @@
return request; return request;
} }
window.__bootstrap.fetch ??= {}; export {
window.__bootstrap.fetch.Request = Request; _flash,
window.__bootstrap.fetch.toInnerRequest = toInnerRequest; fromFlashRequest,
window.__bootstrap.fetch.fromFlashRequest = fromFlashRequest; fromInnerRequest,
window.__bootstrap.fetch.fromInnerRequest = fromInnerRequest; newInnerRequest,
window.__bootstrap.fetch.newInnerRequest = newInnerRequest; processUrlList,
window.__bootstrap.fetch.processUrlList = processUrlList; Request,
window.__bootstrap.fetch._flash = _flash; RequestPrototype,
})(globalThis); toInnerRequest,
};

View file

@ -9,28 +9,28 @@
/// <reference path="../web/06_streams_types.d.ts" /> /// <reference path="../web/06_streams_types.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const { isProxy } = Deno.core; import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = window.__bootstrap.webidl; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const consoleInternal = window.__bootstrap.console; import {
const {
byteLowerCase, byteLowerCase,
} = window.__bootstrap.infra; HTTP_TAB_OR_SPACE,
const { HTTP_TAB_OR_SPACE, regexMatcher, serializeJSValueToJSONString } = regexMatcher,
window.__bootstrap.infra; serializeJSValueToJSONString,
const { extractBody, mixinBody } = window.__bootstrap.fetchBody; } from "internal:ext/web/00_infra.js";
const { getLocationHref } = window.__bootstrap.location; import { extractBody, mixinBody } from "internal:ext/fetch/22_body.js";
const { extractMimeType } = window.__bootstrap.mimesniff; import { getLocationHref } from "internal:ext/web/12_location.js";
const { URL } = window.__bootstrap.url; import { extractMimeType } from "internal:ext/web/01_mimesniff.js";
const { import { URL } from "internal:ext/url/00_url.js";
import {
fillHeaders,
getDecodeSplitHeader, getDecodeSplitHeader,
guardFromHeaders,
headerListFromHeaders, headerListFromHeaders,
headersFromHeaderList, headersFromHeaderList,
guardFromHeaders, } from "internal:ext/fetch/20_headers.js";
fillHeaders, const primordials = globalThis.__bootstrap.primordials;
} = window.__bootstrap.headers;
const { const {
ArrayPrototypeMap, ArrayPrototypeMap,
ArrayPrototypePush, ArrayPrototypePush,
@ -43,7 +43,7 @@
Symbol, Symbol,
SymbolFor, SymbolFor,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const VCHAR = ["\x21-\x7E"]; const VCHAR = ["\x21-\x7E"];
const OBS_TEXT = ["\x80-\xFF"]; const OBS_TEXT = ["\x80-\xFF"];
@ -166,7 +166,7 @@
* https://fetch.spec.whatwg.org#initialize-a-response * https://fetch.spec.whatwg.org#initialize-a-response
* @param {Response} response * @param {Response} response
* @param {ResponseInit} init * @param {ResponseInit} init
* @param {{ body: __bootstrap.fetchBody.InnerBody, contentType: string | null } | null} bodyWithType * @param {{ body: fetchBody.InnerBody, contentType: string | null } | null} bodyWithType
*/ */
function initializeAResponse(response, init, bodyWithType) { function initializeAResponse(response, init, bodyWithType) {
// 1. // 1.
@ -190,7 +190,7 @@
// 4. // 4.
response[_response].statusMessage = init.statusText; response[_response].statusMessage = init.statusText;
// 5. // 5.
/** @type {__bootstrap.headers.Headers} */ /** @type {headers.Headers} */
const headers = response[_headers]; const headers = response[_headers];
if (init.headers) { if (init.headers) {
fillHeaders(headers, init.headers); fillHeaders(headers, init.headers);
@ -418,7 +418,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(ResponsePrototype, this), evaluate: ObjectPrototypeIsPrototypeOf(ResponsePrototype, this),
keys: [ keys: [
@ -468,7 +468,7 @@
return { status: 200, statusText: "", headers: undefined }; return { status: 200, statusText: "", headers: undefined };
} }
// Fast path, if not a proxy // Fast path, if not a proxy
if (typeof init === "object" && !isProxy(init)) { if (typeof init === "object" && !core.isProxy(init)) {
// Not a proxy fast path // Not a proxy fast path
const status = init.status !== undefined const status = init.status !== undefined
? webidl.converters["unsigned short"](init.status) ? webidl.converters["unsigned short"](init.status)
@ -505,14 +505,14 @@
return response; return response;
} }
window.__bootstrap.fetch ??= {}; export {
window.__bootstrap.fetch.Response = Response; abortedNetworkError,
window.__bootstrap.fetch.ResponsePrototype = ResponsePrototype; fromInnerResponse,
window.__bootstrap.fetch.newInnerResponse = newInnerResponse; networkError,
window.__bootstrap.fetch.toInnerResponse = toInnerResponse; newInnerResponse,
window.__bootstrap.fetch.fromInnerResponse = fromInnerResponse; nullBodyStatus,
window.__bootstrap.fetch.redirectStatus = redirectStatus; redirectStatus,
window.__bootstrap.fetch.nullBodyStatus = nullBodyStatus; Response,
window.__bootstrap.fetch.networkError = networkError; ResponsePrototype,
window.__bootstrap.fetch.abortedNetworkError = abortedNetworkError; toInnerResponse,
})(globalThis); };

View file

@ -9,28 +9,32 @@
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference path="./lib.deno_fetch.d.ts" /> /// <reference path="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { byteLowerCase } = window.__bootstrap.infra; import { byteLowerCase } from "internal:ext/web/00_infra.js";
const { BlobPrototype } = window.__bootstrap.file; import { BlobPrototype } from "internal:ext/web/09_file.js";
const { errorReadableStream, ReadableStreamPrototype, readableStreamForRid } = import {
window.__bootstrap.streams; errorReadableStream,
const { InnerBody, extractBody } = window.__bootstrap.fetchBody; readableStreamForRid,
const { ReadableStreamPrototype,
toInnerRequest, } from "internal:ext/web/06_streams.js";
toInnerResponse, import { extractBody, InnerBody } from "internal:ext/fetch/22_body.js";
fromInnerResponse, import {
redirectStatus,
nullBodyStatus,
networkError,
abortedNetworkError,
processUrlList, processUrlList,
} = window.__bootstrap.fetch; toInnerRequest,
const abortSignal = window.__bootstrap.abortSignal; } from "internal:ext/fetch/23_request.js";
import {
abortedNetworkError,
fromInnerResponse,
networkError,
nullBodyStatus,
redirectStatus,
toInnerResponse,
} from "internal:ext/fetch/23_response.js";
import * as abortSignal from "internal:ext/web/03_abort_signal.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypePush, ArrayPrototypePush,
ArrayPrototypeSplice, ArrayPrototypeSplice,
@ -52,7 +56,7 @@
WeakMapPrototypeGet, WeakMapPrototypeGet,
WeakMapPrototypeHas, WeakMapPrototypeHas,
WeakMapPrototypeSet, WeakMapPrototypeSet,
} = window.__bootstrap.primordials; } = primordials;
const REQUEST_BODY_HEADER_NAMES = [ const REQUEST_BODY_HEADER_NAMES = [
"content-encoding", "content-encoding",
@ -185,9 +189,7 @@
req.clientRid, req.clientRid,
reqBody !== null, reqBody !== null,
req.body?.length, req.body?.length,
ObjectPrototypeIsPrototypeOf(Uint8ArrayPrototype, reqBody) ObjectPrototypeIsPrototypeOf(Uint8ArrayPrototype, reqBody) ? reqBody : null,
? reqBody
: null,
); );
function onAbort() { function onAbort() {
@ -580,7 +582,4 @@
} }
} }
window.__bootstrap.fetch ??= {}; export { fetch, handleWasmStreaming };
window.__bootstrap.fetch.fetch = fetch;
window.__bootstrap.fetch.handleWasmStreaming = handleWasmStreaming;
})(this);

View file

@ -5,17 +5,11 @@
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
declare namespace globalThis {
declare namespace __bootstrap {
declare var fetchUtil: {
requiredArguments(name: string, length: number, required: number): void;
};
declare var domIterable: { declare var domIterable: {
DomIterableMixin(base: any, dataSymbol: symbol): any; DomIterableMixin(base: any, dataSymbol: symbol): any;
}; };
declare namespace headers { declare module "internal:ext/fetch/20_headers.js" {
class Headers { class Headers {
} }
type HeaderList = [string, string][]; type HeaderList = [string, string][];
@ -39,19 +33,19 @@ declare namespace globalThis {
): "immutable" | "request" | "request-no-cors" | "response" | "none"; ): "immutable" | "request" | "request-no-cors" | "response" | "none";
} }
declare namespace formData { declare module "internal:ext/fetch/21_formdata.js" {
declare type FormData = typeof FormData; type FormData = typeof FormData;
declare function formDataToBlob( function formDataToBlob(
formData: globalThis.FormData, formData: FormData,
): Blob; ): Blob;
declare function parseFormData( function parseFormData(
body: Uint8Array, body: Uint8Array,
boundary: string | undefined, boundary: string | undefined,
): FormData; ): FormData;
declare function formDataFromEntries(entries: FormDataEntry[]): FormData; function formDataFromEntries(entries: FormDataEntry[]): FormData;
} }
declare namespace fetchBody { declare module "internal:ext/fetch/22_body.js" {
function mixinBody( function mixinBody(
prototype: any, prototype: any,
bodySymbol: symbol, bodySymbol: symbol,
@ -72,7 +66,7 @@ declare namespace globalThis {
}; };
} }
declare namespace fetch { declare module "internal:ext/fetch/26_fetch.js" {
function toInnerRequest(request: Request): InnerRequest; function toInnerRequest(request: Request): InnerRequest;
function fromInnerRequest( function fromInnerRequest(
inner: InnerRequest, inner: InnerRequest,
@ -92,7 +86,7 @@ declare namespace globalThis {
method: string, method: string,
url: any, url: any,
headerList?: [string, string][], headerList?: [string, string][],
body?: globalThis.__bootstrap.fetchBody.InnerBody, body?: fetchBody.InnerBody,
): InnerResponse; ): InnerResponse;
function toInnerResponse(response: Response): InnerResponse; function toInnerResponse(response: Response): InnerResponse;
function fromInnerResponse( function fromInnerResponse(
@ -106,5 +100,3 @@ declare namespace globalThis {
): Response; ): Response;
function networkError(error: string): InnerResponse; function networkError(error: string): InnerResponse;
} }
}
}

View file

@ -97,9 +97,8 @@ where
{ {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web", "deno_url", "deno_console"]) .dependencies(vec!["deno_webidl", "deno_web", "deno_url", "deno_console"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/fetch", prefix "internal:ext/fetch",
"01_fetch_util.js",
"20_headers.js", "20_headers.js",
"21_formdata.js", "21_formdata.js",
"22_body.js", "22_body.js",

View file

@ -1,10 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const __bootstrap = window.__bootstrap; const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeMap, ArrayPrototypeMap,
ArrayPrototypeJoin, ArrayPrototypeJoin,
@ -26,7 +25,7 @@
MathCeil, MathCeil,
SafeMap, SafeMap,
SafeArrayIterator, SafeArrayIterator,
} = window.__bootstrap.primordials; } = primordials;
const U32_BUFFER = new Uint32Array(2); const U32_BUFFER = new Uint32Array(2);
const U64_BUFFER = new BigUint64Array(U32_BUFFER.buffer); const U64_BUFFER = new BigUint64Array(U32_BUFFER.buffer);
@ -495,16 +494,16 @@
} }
function dlopen(path, symbols) { function dlopen(path, symbols) {
// TODO(@crowlKats): remove me
// URL support is progressively enhanced by util in `runtime/js`. // URL support is progressively enhanced by util in `runtime/js`.
const pathFromURL = __bootstrap.util.pathFromURL ?? ((p) => p); const pathFromURL = internals.pathFromURL ?? ((p) => p);
return new DynamicLibrary(pathFromURL(path), symbols); return new DynamicLibrary(pathFromURL(path), symbols);
} }
window.__bootstrap.ffi = { export {
dlopen, dlopen,
UnsafeCallback, UnsafeCallback,
UnsafeFnPointer,
UnsafePointer, UnsafePointer,
UnsafePointerView, UnsafePointerView,
UnsafeFnPointer,
}; };
})(this);

View file

@ -84,7 +84,7 @@ pub(crate) struct FfiState {
pub fn init<P: FfiPermissions + 'static>(unstable: bool) -> Extension { pub fn init<P: FfiPermissions + 'static>(unstable: bool) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/ffi", prefix "internal:ext/ffi",
"00_ffi.js", "00_ffi.js",
)) ))

View file

@ -1,31 +1,30 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict"; const core = globalThis.Deno.core;
const ops = core.ops;
((window) => { const primordials = globalThis.__bootstrap.primordials;
const { BlobPrototype } = window.__bootstrap.file; import { BlobPrototype } from "internal:ext/web/09_file.js";
const { TcpConn } = window.__bootstrap.net; import { TcpConn } from "internal:ext/net/01_net.js";
const { fromFlashRequest, toInnerResponse, _flash } = import { toInnerResponse } from "internal:ext/fetch/23_response.js";
window.__bootstrap.fetch; import { _flash, fromFlashRequest } from "internal:ext/fetch/23_request.js";
const core = window.Deno.core; import { Event } from "internal:ext/web/02_event.js";
const { Event } = window.__bootstrap.event; import {
const {
ReadableStream,
ReadableStreamPrototype,
getReadableStreamResourceBacking,
readableStreamClose,
_state, _state,
} = window.__bootstrap.streams; getReadableStreamResourceBacking,
const { ReadableStream,
WebSocket, readableStreamClose,
_rid, ReadableStreamPrototype,
_readyState, } from "internal:ext/web/06_streams.js";
import {
_eventLoop, _eventLoop,
_protocol,
_idleTimeoutDuration, _idleTimeoutDuration,
_idleTimeoutTimeout, _idleTimeoutTimeout,
_protocol,
_readyState,
_rid,
_serverHandleIdleTimeout, _serverHandleIdleTimeout,
} = window.__bootstrap.webSocket; WebSocket,
const { _ws } = window.__bootstrap.http; } from "internal:ext/websocket/01_websocket.js";
import { _ws } from "internal:ext/http/01_http.js";
const { const {
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
PromisePrototype, PromisePrototype,
@ -36,7 +35,7 @@
TypeError, TypeError,
Uint8Array, Uint8Array,
Uint8ArrayPrototype, Uint8ArrayPrototype,
} = window.__bootstrap.primordials; } = primordials;
const statusCodes = { const statusCodes = {
100: "Continue", 100: "Continue",
@ -189,7 +188,7 @@
} }
function prepareFastCalls() { function prepareFastCalls() {
return core.ops.op_flash_make_request(); return ops.op_flash_make_request();
} }
function hostnameForDisplay(hostname) { function hostnameForDisplay(hostname) {
@ -213,7 +212,7 @@
nwritten = respondFast(requestId, response, end); nwritten = respondFast(requestId, response, end);
} else { } else {
// string // string
nwritten = core.ops.op_flash_respond( nwritten = ops.op_flash_respond(
server, server,
requestId, requestId,
response, response,
@ -560,11 +559,11 @@
() => methods[method], () => methods[method],
/* urlCb */ /* urlCb */
() => { () => {
const path = core.ops.op_flash_path(serverId, i); const path = ops.op_flash_path(serverId, i);
return `${server.transport}://${server.hostname}:${server.port}${path}`; return `${server.transport}://${server.hostname}:${server.port}${path}`;
}, },
/* headersCb */ /* headersCb */
() => core.ops.op_flash_headers(serverId, i), () => ops.op_flash_headers(serverId, i),
); );
let resp; let resp;
@ -638,7 +637,7 @@
}); });
function tryRespondChunked(token, chunk, shutdown) { function tryRespondChunked(token, chunk, shutdown) {
const nwritten = core.ops.op_try_flash_respond_chunked( const nwritten = ops.op_try_flash_respond_chunked(
serverId, serverId,
token, token,
chunk ?? new Uint8Array(), chunk ?? new Uint8Array(),
@ -672,10 +671,10 @@
let respondFast = (token, response, shutdown) => let respondFast = (token, response, shutdown) =>
fastOp.respond(token, response, shutdown); fastOp.respond(token, response, shutdown);
if (serverId > 0) { if (serverId > 0) {
nextRequestSync = () => core.ops.op_flash_next_server(serverId); nextRequestSync = () => ops.op_flash_next_server(serverId);
getMethodSync = (token) => core.ops.op_flash_method(serverId, token); getMethodSync = (token) => ops.op_flash_method(serverId, token);
respondFast = (token, response, shutdown) => respondFast = (token, response, shutdown) =>
core.ops.op_flash_respond(serverId, token, response, null, shutdown); ops.op_flash_respond(serverId, token, response, null, shutdown);
} }
if (!dateInterval) { if (!dateInterval) {
@ -694,7 +693,7 @@
function createRequestBodyStream(serverId, token) { function createRequestBodyStream(serverId, token) {
// The first packet is left over bytes after parsing the request // The first packet is left over bytes after parsing the request
const firstRead = core.ops.op_flash_first_packet( const firstRead = ops.op_flash_first_packet(
serverId, serverId,
token, token,
); );
@ -751,13 +750,9 @@
req.headers; req.headers;
const { serverId, streamRid } = req[_flash]; const { serverId, streamRid } = req[_flash];
const connRid = core.ops.op_flash_upgrade_http(streamRid, serverId); const connRid = ops.op_flash_upgrade_http(streamRid, serverId);
// TODO(@littledivy): return already read first packet too. // TODO(@littledivy): return already read first packet too.
return [new TcpConn(connRid), new Uint8Array()]; return [new TcpConn(connRid), new Uint8Array()];
} }
window.__bootstrap.flash = { export { createServe, upgradeHttpRaw };
createServe,
upgradeHttpRaw,
};
})(this);

View file

@ -1514,7 +1514,7 @@ pub fn init<P: FlashPermissions + 'static>(unstable: bool) -> Extension {
"deno_websocket", "deno_websocket",
"deno_http", "deno_http",
]) ])
.js(deno_core::include_js_files!( .esm(deno_core::include_js_files!(
prefix "internal:ext/flash", prefix "internal:ext/flash",
"01_http.js", "01_http.js",
)) ))

View file

@ -1,44 +1,43 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict"; const core = globalThis.Deno.core;
const primordials = globalThis.__bootstrap.primordials;
((window) => {
const webidl = window.__bootstrap.webidl;
const { InnerBody } = window.__bootstrap.fetchBody;
const { Event } = window.__bootstrap.event;
const { setEventTargetData } = window.__bootstrap.eventTarget;
const { BlobPrototype } = window.__bootstrap.file;
const {
ResponsePrototype,
fromInnerRequest,
toInnerResponse,
newInnerRequest,
newInnerResponse,
fromInnerResponse,
_flash,
} = window.__bootstrap.fetch;
const core = window.Deno.core;
const { BadResourcePrototype, InterruptedPrototype, ops } = core; const { BadResourcePrototype, InterruptedPrototype, ops } = core;
const { ReadableStreamPrototype } = window.__bootstrap.streams; import * as webidl from "internal:ext/webidl/00_webidl.js";
const abortSignal = window.__bootstrap.abortSignal; import { InnerBody } from "internal:ext/fetch/22_body.js";
const { import { Event, setEventTargetData } from "internal:ext/web/02_event.js";
WebSocket, import { BlobPrototype } from "internal:ext/web/09_file.js";
_rid, import {
_readyState, fromInnerResponse,
newInnerResponse,
ResponsePrototype,
toInnerResponse,
} from "internal:ext/fetch/23_response.js";
import {
_flash,
fromInnerRequest,
newInnerRequest,
} from "internal:ext/fetch/23_request.js";
import * as abortSignal from "internal:ext/web/03_abort_signal.js";
import {
_eventLoop, _eventLoop,
_protocol,
_server,
_idleTimeoutDuration, _idleTimeoutDuration,
_idleTimeoutTimeout, _idleTimeoutTimeout,
_protocol,
_readyState,
_rid,
_server,
_serverHandleIdleTimeout, _serverHandleIdleTimeout,
} = window.__bootstrap.webSocket; WebSocket,
const { TcpConn, UnixConn } = window.__bootstrap.net; } from "internal:ext/websocket/01_websocket.js";
const { TlsConn } = window.__bootstrap.tls; import { TcpConn, UnixConn } from "internal:ext/net/01_net.js";
const { import { TlsConn } from "internal:ext/net/02_tls.js";
import {
Deferred, Deferred,
getReadableStreamResourceBacking, getReadableStreamResourceBacking,
readableStreamForRid,
readableStreamClose, readableStreamClose,
} = window.__bootstrap.streams; readableStreamForRid,
ReadableStreamPrototype,
} from "internal:ext/web/06_streams.js";
const { const {
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
ArrayPrototypePush, ArrayPrototypePush,
@ -57,7 +56,7 @@
TypeError, TypeError,
Uint8Array, Uint8Array,
Uint8ArrayPrototype, Uint8ArrayPrototype,
} = window.__bootstrap.primordials; } = primordials;
const connErrorSymbol = Symbol("connError"); const connErrorSymbol = Symbol("connError");
const _deferred = Symbol("upgradeHttpDeferred"); const _deferred = Symbol("upgradeHttpDeferred");
@ -469,10 +468,4 @@
return req[_deferred].promise; return req[_deferred].promise;
} }
window.__bootstrap.http = { export { _ws, HttpConn, upgradeHttp, upgradeWebSocket };
HttpConn,
upgradeWebSocket,
upgradeHttp,
_ws,
};
})(this);

View file

@ -80,7 +80,7 @@ mod reader_stream;
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_web", "deno_net", "deno_fetch", "deno_websocket"]) .dependencies(vec!["deno_web", "deno_net", "deno_fetch", "deno_websocket"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/http", prefix "internal:ext/http",
"01_http.js", "01_http.js",
)) ))

View file

@ -1,15 +1,14 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const { BadResourcePrototype, InterruptedPrototype, ops } = core; const { BadResourcePrototype, InterruptedPrototype, ops } = core;
const { import {
readableStreamForRidUnrefable, readableStreamForRidUnrefable,
readableStreamForRidUnrefableRef, readableStreamForRidUnrefableRef,
readableStreamForRidUnrefableUnref, readableStreamForRidUnrefableUnref,
writableStreamForRid, writableStreamForRid,
} = window.__bootstrap.streams; } from "internal:ext/web/06_streams.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
Error, Error,
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
@ -19,7 +18,7 @@
TypedArrayPrototypeSubarray, TypedArrayPrototypeSubarray,
TypeError, TypeError,
Uint8Array, Uint8Array,
} = window.__bootstrap.primordials; } = primordials;
const promiseIdSymbol = SymbolFor("Deno.core.internalPromiseId"); const promiseIdSymbol = SymbolFor("Deno.core.internalPromiseId");
@ -408,16 +407,15 @@
} }
} }
window.__bootstrap.net = { export {
connect,
Conn, Conn,
connect,
createListenDatagram,
Datagram,
listen,
Listener,
resolveDns,
shutdown,
TcpConn, TcpConn,
UnixConn, UnixConn,
listen,
createListenDatagram,
Listener,
shutdown,
Datagram,
resolveDns,
}; };
})(this);

View file

@ -1,11 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const { Listener, Conn } = window.__bootstrap.net; import { Conn, Listener } from "internal:ext/net/01_net.js";
const { TypeError } = window.__bootstrap.primordials; const primordials = globalThis.__bootstrap.primordials;
const { TypeError } = primordials;
function opStartTls(args) { function opStartTls(args) {
return core.opAsync("op_tls_start", args); return core.opAsync("op_tls_start", args);
@ -96,11 +95,4 @@
return new TlsConn(rid, remoteAddr, localAddr); return new TlsConn(rid, remoteAddr, localAddr);
} }
window.__bootstrap.tls = { export { connectTls, listenTls, startTls, TlsConn, TlsListener };
startTls,
listenTls,
connectTls,
TlsConn,
TlsListener,
};
})(this);

View file

@ -86,7 +86,7 @@ pub fn init<P: NetPermissions + 'static>(
ops.extend(ops_tls::init::<P>()); ops.extend(ops_tls::init::<P>());
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_web"]) .dependencies(vec!["deno_web"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/net", prefix "internal:ext/net",
"01_net.js", "01_net.js",
"02_tls.js", "02_tls.js",

View file

@ -2,9 +2,8 @@
// deno-lint-ignore-file // deno-lint-ignore-file
"use strict"; const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
((window) => {
const { const {
ArrayPrototypePush, ArrayPrototypePush,
ArrayPrototypeFilter, ArrayPrototypeFilter,
@ -17,7 +16,7 @@
ReflectOwnKeys, ReflectOwnKeys,
Set, Set,
SetPrototypeHas, SetPrototypeHas,
} = window.__bootstrap.primordials; } = primordials;
function assert(cond) { function assert(cond) {
if (!cond) { if (!cond) {
@ -116,13 +115,9 @@
}); });
} }
window.__bootstrap.internals = { internals.node = {
...window.__bootstrap.internals ?? {},
node: {
globalThis: nodeGlobalThis, globalThis: nodeGlobalThis,
initialize, initialize,
nativeModuleExports, nativeModuleExports,
builtinModules, builtinModules,
},
}; };
})(globalThis);

View file

@ -2,9 +2,10 @@
// deno-lint-ignore-file // deno-lint-ignore-file
"use strict"; const core = globalThis.Deno.core;
const ops = core.ops;
((window) => { const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayIsArray, ArrayIsArray,
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
@ -37,10 +38,8 @@
RegExpPrototypeTest, RegExpPrototypeTest,
Error, Error,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const core = window.Deno.core; const node = internals.node;
const ops = core.ops;
const { node } = window.__bootstrap.internals;
// Map used to store CJS parsing data. // Map used to store CJS parsing data.
const cjsParseCache = new SafeWeakMap(); const cjsParseCache = new SafeWeakMap();
@ -113,7 +112,7 @@
requestPath, requestPath,
"package.json", "package.json",
); );
const pkg = core.ops.op_require_read_package_scope(packageJsonPath)?.main; const pkg = ops.op_require_read_package_scope(packageJsonPath)?.main;
if (!pkg) { if (!pkg) {
return tryExtensions( return tryExtensions(
pathResolve(requestPath, "index"), pathResolve(requestPath, "index"),
@ -316,7 +315,7 @@
return; return;
} }
return core.ops.op_require_resolve_exports( return ops.op_require_resolve_exports(
usesLocalNodeModulesDir, usesLocalNodeModulesDir,
modulesPath, modulesPath,
request, request,
@ -366,7 +365,7 @@
} }
} }
const isDenoDirPackage = core.ops.op_require_is_deno_dir_package( const isDenoDirPackage = ops.op_require_is_deno_dir_package(
curPath, curPath,
); );
const isRelative = ops.op_require_is_request_relative( const isRelative = ops.op_require_is_request_relative(
@ -417,16 +416,16 @@
Module._resolveLookupPaths = function (request, parent) { Module._resolveLookupPaths = function (request, parent) {
const paths = []; const paths = [];
if (core.ops.op_require_is_request_relative(request) && parent?.filename) { if (ops.op_require_is_request_relative(request) && parent?.filename) {
ArrayPrototypePush( ArrayPrototypePush(
paths, paths,
core.ops.op_require_path_dirname(parent.filename), ops.op_require_path_dirname(parent.filename),
); );
return paths; return paths;
} }
if (parent?.filename && parent.filename.length > 0) { if (parent?.filename && parent.filename.length > 0) {
const denoDirPath = core.ops.op_require_resolve_deno_dir( const denoDirPath = ops.op_require_resolve_deno_dir(
request, request,
parent.filename, parent.filename,
); );
@ -592,7 +591,7 @@
if (parent?.filename) { if (parent?.filename) {
if (request[0] === "#") { if (request[0] === "#") {
const maybeResolved = core.ops.op_require_package_imports_resolve( const maybeResolved = ops.op_require_package_imports_resolve(
parent.filename, parent.filename,
request, request,
); );
@ -741,7 +740,7 @@
if (hasInspectBrk && !hasBrokenOnInspectBrk) { if (hasInspectBrk && !hasBrokenOnInspectBrk) {
hasBrokenOnInspectBrk = true; hasBrokenOnInspectBrk = true;
core.ops.op_require_break_on_next_statement(); ops.op_require_break_on_next_statement();
} }
const result = compiledWrapper.call( const result = compiledWrapper.call(
@ -763,7 +762,7 @@
const content = ops.op_require_read_file(filename); const content = ops.op_require_read_file(filename);
if (StringPrototypeEndsWith(filename, ".js")) { if (StringPrototypeEndsWith(filename, ".js")) {
const pkg = core.ops.op_require_read_closest_package_json(filename); const pkg = ops.op_require_read_closest_package_json(filename);
if (pkg && pkg.exists && pkg.typ == "module") { if (pkg && pkg.exists && pkg.typ == "module") {
let message = `Trying to import ESM module: ${filename}`; let message = `Trying to import ESM module: ${filename}`;
@ -871,7 +870,7 @@
`The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received ${filenameOrUrl}`, `The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received ${filenameOrUrl}`,
); );
} }
const filename = core.ops.op_require_as_file_path(fileUrlStr); const filename = ops.op_require_as_file_path(fileUrlStr);
return createRequireFromPath(filename); return createRequireFromPath(filename);
} }
@ -925,9 +924,7 @@
return ArrayPrototypeJoin(parts, "/"); return ArrayPrototypeJoin(parts, "/");
} }
window.__bootstrap.internals = { internals.require = {
...window.__bootstrap.internals ?? {},
require: {
setUsesLocalNodeModulesDir() { setUsesLocalNodeModulesDir() {
usesLocalNodeModulesDir = true; usesLocalNodeModulesDir = true;
}, },
@ -939,6 +936,4 @@
toRealPath, toRealPath,
cjsParseCache, cjsParseCache,
readPackageScope, readPackageScope,
},
}; };
})(globalThis);

View file

@ -85,7 +85,7 @@ pub fn init<P: NodePermissions + 'static>(
maybe_npm_resolver: Option<Rc<dyn RequireNpmResolver>>, maybe_npm_resolver: Option<Rc<dyn RequireNpmResolver>>,
) -> Extension { ) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/node", prefix "internal:ext/node",
"01_node.js", "01_node.js",
"02_require.js", "02_require.js",

View file

@ -5,12 +5,10 @@
/// <reference path="../../core/lib.deno_core.d.ts" /> /// <reference path="../../core/lib.deno_core.d.ts" />
/// <reference path="../webidl/internal.d.ts" /> /// <reference path="../webidl/internal.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayIsArray, ArrayIsArray,
ArrayPrototypeMap, ArrayPrototypeMap,
@ -26,7 +24,7 @@
SymbolFor, SymbolFor,
SymbolIterator, SymbolIterator,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const _list = Symbol("list"); const _list = Symbol("list");
const _urlObject = Symbol("url object"); const _urlObject = Symbol("url object");
@ -58,7 +56,7 @@
if (maybeBase === undefined) { if (maybeBase === undefined) {
status = ops.op_url_parse(href, componentsBuf.buffer); status = ops.op_url_parse(href, componentsBuf.buffer);
} else { } else {
status = core.ops.op_url_parse_with_base( status = ops.op_url_parse_with_base(
href, href,
maybeBase, maybeBase,
componentsBuf.buffer, componentsBuf.buffer,
@ -71,7 +69,7 @@
if (status === 0) { if (status === 0) {
return href; return href;
} else if (status === 1) { } else if (status === 1) {
return core.ops.op_url_get_serialization(); return ops.op_url_get_serialization();
} else { } else {
throw new TypeError( throw new TypeError(
`Invalid URL: '${href}'` + `Invalid URL: '${href}'` +
@ -800,11 +798,10 @@
return webidl.converters.USVString(V, opts); return webidl.converters.USVString(V, opts);
}; };
window.__bootstrap.url = { export {
parseUrlEncoded,
URL, URL,
URLPrototype, URLPrototype,
URLSearchParams, URLSearchParams,
URLSearchParamsPrototype, URLSearchParamsPrototype,
parseUrlEncoded,
}; };
})(this);

View file

@ -7,12 +7,10 @@
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference path="./lib.deno_url.d.ts" /> /// <reference path="./lib.deno_url.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeMap, ArrayPrototypeMap,
ObjectKeys, ObjectKeys,
@ -23,7 +21,7 @@
Symbol, Symbol,
SymbolFor, SymbolFor,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const _components = Symbol("components"); const _components = Symbol("components");
@ -268,7 +266,4 @@
return webidl.converters.USVString(V, opts); return webidl.converters.USVString(V, opts);
}; };
window.__bootstrap.urlPattern = { export { URLPattern };
URLPattern,
};
})(globalThis);

View file

@ -12,9 +12,11 @@ fn setup() -> Vec<Extension> {
deno_webidl::init(), deno_webidl::init(),
deno_url::init(), deno_url::init(),
Extension::builder("bench_setup") Extension::builder("bench_setup")
.js(vec![( .esm(vec![(
"setup", "internal:setup",
"const { URL } = globalThis.__bootstrap.url;", r#"import { URL } from "internal:ext/url/00_url.js";
globalThis.URL = URL;
"#,
)]) )])
.build(), .build(),
] ]

20
ext/url/internal.d.ts vendored
View file

@ -1,20 +1,14 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-var
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
declare namespace globalThis { declare module "internal:ext/url/00_url.js" {
declare namespace __bootstrap { const URL: typeof URL;
declare var url: { const URLSearchParams: typeof URLSearchParams;
URL: typeof URL; function parseUrlEncoded(bytes: Uint8Array): [string, string][];
URLSearchParams: typeof URLSearchParams; }
parseUrlEncoded(bytes: Uint8Array): [string, string][];
};
declare var urlPattern: { declare module "internal:ext/url/01_urlpattern.js" {
URLPattern: typeof URLPattern; const URLPattern: typeof URLPattern;
};
}
} }

View file

@ -20,7 +20,7 @@ use crate::urlpattern::op_urlpattern_process_match_input;
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl"]) .dependencies(vec!["deno_webidl"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/url", prefix "internal:ext/url",
"00_url.js", "00_url.js",
"01_urlpattern.js", "01_urlpattern.js",

View file

@ -6,11 +6,9 @@
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = Deno.core;
const ops = core.ops; const ops = core.ops;
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeJoin, ArrayPrototypeJoin,
ArrayPrototypeMap, ArrayPrototypeMap,
@ -30,7 +28,7 @@
StringPrototypeToLowerCase, StringPrototypeToLowerCase,
StringPrototypeToUpperCase, StringPrototypeToUpperCase,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const ASCII_DIGIT = ["\u0030-\u0039"]; const ASCII_DIGIT = ["\u0030-\u0039"];
const ASCII_UPPER_ALPHA = ["\u0041-\u005A"]; const ASCII_UPPER_ALPHA = ["\u0041-\u005A"];
@ -308,32 +306,31 @@
return result; return result;
} }
window.__bootstrap.infra = { export {
collectSequenceOfCodepoints,
ASCII_DIGIT,
ASCII_UPPER_ALPHA,
ASCII_LOWER_ALPHA,
ASCII_ALPHA, ASCII_ALPHA,
ASCII_ALPHANUMERIC, ASCII_ALPHANUMERIC,
HTTP_TAB_OR_SPACE, ASCII_DIGIT,
HTTP_WHITESPACE, ASCII_LOWER_ALPHA,
HTTP_TOKEN_CODE_POINT, ASCII_UPPER_ALPHA,
HTTP_TOKEN_CODE_POINT_RE, assert,
AssertionError,
byteLowerCase,
byteUpperCase,
collectHttpQuotedString,
collectSequenceOfCodepoints,
forgivingBase64Decode,
forgivingBase64Encode,
HTTP_QUOTED_STRING_TOKEN_POINT, HTTP_QUOTED_STRING_TOKEN_POINT,
HTTP_QUOTED_STRING_TOKEN_POINT_RE, HTTP_QUOTED_STRING_TOKEN_POINT_RE,
HTTP_TAB_OR_SPACE,
HTTP_TAB_OR_SPACE_PREFIX_RE, HTTP_TAB_OR_SPACE_PREFIX_RE,
HTTP_TAB_OR_SPACE_SUFFIX_RE, HTTP_TAB_OR_SPACE_SUFFIX_RE,
HTTP_TOKEN_CODE_POINT,
HTTP_TOKEN_CODE_POINT_RE,
HTTP_WHITESPACE,
HTTP_WHITESPACE_PREFIX_RE, HTTP_WHITESPACE_PREFIX_RE,
HTTP_WHITESPACE_SUFFIX_RE, HTTP_WHITESPACE_SUFFIX_RE,
httpTrim, httpTrim,
regexMatcher, regexMatcher,
byteUpperCase,
byteLowerCase,
collectHttpQuotedString,
forgivingBase64Encode,
forgivingBase64Decode,
AssertionError,
assert,
serializeJSValueToJSONString, serializeJSValueToJSONString,
}; };
})(globalThis);

View file

@ -7,9 +7,7 @@
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
"use strict"; const primordials = globalThis.__bootstrap.primordials;
((window) => {
const { const {
ArrayPrototypeSlice, ArrayPrototypeSlice,
Error, Error,
@ -21,9 +19,9 @@
ObjectSetPrototypeOf, ObjectSetPrototypeOf,
Symbol, Symbol,
SymbolFor, SymbolFor,
} = window.__bootstrap.primordials; } = primordials;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const consoleInternal = window.__bootstrap.console; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const _name = Symbol("name"); const _name = Symbol("name");
const _message = Symbol("message"); const _message = Symbol("message");
@ -147,7 +145,7 @@
if (ObjectPrototypeIsPrototypeOf(DOMExceptionPrototype, this)) { if (ObjectPrototypeIsPrototypeOf(DOMExceptionPrototype, this)) {
return `DOMException: ${this[_message]}`; return `DOMException: ${this[_message]}`;
} else { } else {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: false, evaluate: false,
keys: [ keys: [
@ -199,5 +197,4 @@
ObjectDefineProperty(DOMException.prototype, key, desc); ObjectDefineProperty(DOMException.prototype, key, desc);
} }
window.__bootstrap.domException = { DOMException }; export default DOMException;
})(this);

View file

@ -6,9 +6,7 @@
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
"use strict"; const primordials = globalThis.__bootstrap.primordials;
((window) => {
const { const {
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
Map, Map,
@ -19,16 +17,16 @@
SafeMapIterator, SafeMapIterator,
StringPrototypeReplaceAll, StringPrototypeReplaceAll,
StringPrototypeToLowerCase, StringPrototypeToLowerCase,
} = window.__bootstrap.primordials; } = primordials;
const { import {
collectHttpQuotedString,
collectSequenceOfCodepoints, collectSequenceOfCodepoints,
HTTP_QUOTED_STRING_TOKEN_POINT_RE,
HTTP_TOKEN_CODE_POINT_RE,
HTTP_WHITESPACE, HTTP_WHITESPACE,
HTTP_WHITESPACE_PREFIX_RE, HTTP_WHITESPACE_PREFIX_RE,
HTTP_WHITESPACE_SUFFIX_RE, HTTP_WHITESPACE_SUFFIX_RE,
HTTP_QUOTED_STRING_TOKEN_POINT_RE, } from "internal:ext/web/00_infra.js";
HTTP_TOKEN_CODE_POINT_RE,
collectHttpQuotedString,
} = window.__bootstrap.infra;
/** /**
* @typedef MimeType * @typedef MimeType
@ -251,10 +249,4 @@
return mimeType; return mimeType;
} }
window.__bootstrap.mimesniff = { export { essence, extractMimeType, parseMimeType, serializeMimeType };
parseMimeType,
essence,
serializeMimeType,
extractMimeType,
};
})(this);

View file

@ -4,14 +4,13 @@
// Many parts of the DOM are not implemented in Deno, but the logic for those // Many parts of the DOM are not implemented in Deno, but the logic for those
// parts still exists. This means you will observe a lot of strange structures // parts still exists. This means you will observe a lot of strange structures
// and impossible logic branches based on what Deno currently supports. // and impossible logic branches based on what Deno currently supports.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { DOMException } = window.__bootstrap.domException; import DOMException from "internal:ext/web/01_dom_exception.js";
const consoleInternal = window.__bootstrap.console; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeFilter, ArrayPrototypeFilter,
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
@ -40,7 +39,15 @@
SymbolFor, SymbolFor,
SymbolToStringTag, SymbolToStringTag,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
// This should be set via setGlobalThis this is required so that if even
// user deletes globalThis it is still usable
let globalThis_;
function saveGlobalThisReference(val) {
globalThis_ = val;
}
// accessors for non runtime visible data // accessors for non runtime visible data
@ -198,7 +205,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(Event.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(Event.prototype, this),
keys: EVENT_PROPS, keys: EVENT_PROPS,
@ -947,7 +954,7 @@
callback, callback,
options, options,
) { ) {
const self = this ?? globalThis; const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype); webidl.assertBranded(self, EventTargetPrototype);
const prefix = "Failed to execute 'addEventListener' on 'EventTarget'"; const prefix = "Failed to execute 'addEventListener' on 'EventTarget'";
@ -1005,7 +1012,7 @@
callback, callback,
options, options,
) { ) {
const self = this ?? globalThis; const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype); webidl.assertBranded(self, EventTargetPrototype);
webidl.requiredArguments(arguments.length, 2, { webidl.requiredArguments(arguments.length, 2, {
prefix: "Failed to execute 'removeEventListener' on 'EventTarget'", prefix: "Failed to execute 'removeEventListener' on 'EventTarget'",
@ -1043,7 +1050,7 @@
// `globalThis` directly here, because it could be deleted by user. // `globalThis` directly here, because it could be deleted by user.
// Instead use saved reference to global scope when the script was // Instead use saved reference to global scope when the script was
// executed. // executed.
const self = this ?? window; const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype); webidl.assertBranded(self, EventTargetPrototype);
webidl.requiredArguments(arguments.length, 1, { webidl.requiredArguments(arguments.length, 1, {
prefix: "Failed to execute 'dispatchEvent' on 'EventTarget'", prefix: "Failed to execute 'dispatchEvent' on 'EventTarget'",
@ -1130,7 +1137,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(ErrorEvent.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(ErrorEvent.prototype, this),
keys: [ keys: [
@ -1191,7 +1198,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(CloseEvent.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(CloseEvent.prototype, this),
keys: [ keys: [
@ -1224,7 +1231,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(MessageEvent.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(MessageEvent.prototype, this),
keys: [ keys: [
@ -1257,7 +1264,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(CustomEvent.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(CustomEvent.prototype, this),
keys: [ keys: [
@ -1287,7 +1294,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(ProgressEvent.prototype, this), evaluate: ObjectPrototypeIsPrototypeOf(ProgressEvent.prototype, this),
keys: [ keys: [
@ -1335,7 +1342,7 @@
} }
[SymbolFor("Deno.privateCustomInspect")](inspect) { [SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
PromiseRejectionEvent.prototype, PromiseRejectionEvent.prototype,
@ -1480,14 +1487,14 @@
error, error,
}); });
// Avoid recursing `reportException()` via error handlers more than once. // Avoid recursing `reportException()` via error handlers more than once.
if (reportExceptionStackedCalls > 1 || window.dispatchEvent(event)) { if (reportExceptionStackedCalls > 1 || globalThis_.dispatchEvent(event)) {
ops.op_dispatch_exception(error); ops.op_dispatch_exception(error);
} }
reportExceptionStackedCalls--; reportExceptionStackedCalls--;
} }
function checkThis(thisArg) { function checkThis(thisArg) {
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis) { if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis_) {
throw new TypeError("Illegal invocation"); throw new TypeError("Illegal invocation");
} }
} }
@ -1500,24 +1507,22 @@
reportException(error); reportException(error);
} }
window.__bootstrap.eventTarget = { export {
EventTarget,
setEventTargetData,
listenerCount,
};
window.__bootstrap.event = {
reportException,
setIsTrusted,
setTarget,
defineEventHandler,
_skipInternalInit, _skipInternalInit,
Event,
ErrorEvent,
CloseEvent, CloseEvent,
MessageEvent,
CustomEvent, CustomEvent,
defineEventHandler,
ErrorEvent,
Event,
EventTarget,
listenerCount,
MessageEvent,
ProgressEvent, ProgressEvent,
PromiseRejectionEvent, PromiseRejectionEvent,
reportError, reportError,
reportException,
saveGlobalThisReference,
setEventTargetData,
setIsTrusted,
setTarget,
}; };
})(this);

View file

@ -6,11 +6,9 @@
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
"use strict"; const core = globalThis.Deno.core;
import DOMException from "internal:ext/web/01_dom_exception.js";
((window) => { const primordials = globalThis.__bootstrap.primordials;
const core = window.Deno.core;
const { DOMException } = window.__bootstrap.domException;
const { const {
ArrayBuffer, ArrayBuffer,
ArrayBufferPrototype, ArrayBufferPrototype,
@ -40,7 +38,7 @@
BigUint64Array, BigUint64Array,
Float32Array, Float32Array,
Float64Array, Float64Array,
} = window.__bootstrap.primordials; } = primordials;
const objectCloneMemo = new WeakMap(); const objectCloneMemo = new WeakMap();
@ -139,5 +137,4 @@
} }
} }
window.__bootstrap.structuredClone = structuredClone; export { structuredClone };
})(globalThis);

View file

@ -1,9 +1,8 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypePush, ArrayPrototypePush,
ArrayPrototypeShift, ArrayPrototypeShift,
@ -22,10 +21,10 @@
SymbolFor, SymbolFor,
TypeError, TypeError,
indirectEval, indirectEval,
} = window.__bootstrap.primordials; } = primordials;
const { webidl } = window.__bootstrap; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { reportException } = window.__bootstrap.event; import { reportException } from "internal:ext/web/02_event.js";
const { assert } = window.__bootstrap.infra; import { assert } from "internal:ext/web/00_infra.js";
const hrU8 = new Uint8Array(8); const hrU8 = new Uint8Array(8);
const hr = new Uint32Array(hrU8.buffer); const hr = new Uint32Array(hrU8.buffer);
@ -217,8 +216,7 @@
function runAfterTimeout(cb, millis, timerInfo) { function runAfterTimeout(cb, millis, timerInfo) {
const cancelRid = timerInfo.cancelRid; const cancelRid = timerInfo.cancelRid;
const sleepPromise = core.opAsync("op_sleep", millis, cancelRid); const sleepPromise = core.opAsync("op_sleep", millis, cancelRid);
timerInfo.promiseId = timerInfo.promiseId = sleepPromise[SymbolFor("Deno.core.internalPromiseId")];
sleepPromise[SymbolFor("Deno.core.internalPromiseId")];
if (!timerInfo.isRef) { if (!timerInfo.isRef) {
core.unrefOp(timerInfo.promiseId); core.unrefOp(timerInfo.promiseId);
} }
@ -362,14 +360,13 @@
core.unrefOp(timerInfo.promiseId); core.unrefOp(timerInfo.promiseId);
} }
window.__bootstrap.timers = { export {
setTimeout,
setInterval,
clearTimeout,
clearInterval, clearInterval,
clearTimeout,
handleTimerMacrotask, handleTimerMacrotask,
opNow, opNow,
refTimer, refTimer,
setInterval,
setTimeout,
unrefTimer, unrefTimer,
}; };
})(this);

View file

@ -1,13 +1,17 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
// @ts-check // @ts-check
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { import * as webidl from "internal:ext/webidl/00_webidl.js";
const webidl = window.__bootstrap.webidl; import {
const { Event, setIsTrusted, defineEventHandler } = window.__bootstrap.event; defineEventHandler,
const { EventTarget, listenerCount } = window.__bootstrap.eventTarget; Event,
EventTarget,
listenerCount,
setIsTrusted,
} from "internal:ext/web/02_event.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
SafeArrayIterator, SafeArrayIterator,
SafeSetIterator, SafeSetIterator,
@ -16,8 +20,12 @@
SetPrototypeDelete, SetPrototypeDelete,
Symbol, Symbol,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const { setTimeout, refTimer, unrefTimer } = window.__bootstrap.timers; import {
refTimer,
setTimeout,
unrefTimer,
} from "internal:ext/web/02_timers.js";
const add = Symbol("[[add]]"); const add = Symbol("[[add]]");
const signalAbort = Symbol("[[signalAbort]]"); const signalAbort = Symbol("[[signalAbort]]");
@ -181,20 +189,17 @@
if (parentSignal.aborted) { if (parentSignal.aborted) {
followingSignal[signalAbort](parentSignal.reason); followingSignal[signalAbort](parentSignal.reason);
} else { } else {
parentSignal[add](() => parentSignal[add](() => followingSignal[signalAbort](parentSignal.reason));
followingSignal[signalAbort](parentSignal.reason)
);
} }
} }
window.__bootstrap.abortSignal = { export {
AbortSignal,
AbortController, AbortController,
AbortSignal,
AbortSignalPrototype, AbortSignalPrototype,
add, add,
signalAbort,
remove,
follow, follow,
newSignal, newSignal,
remove,
signalAbort,
}; };
})(this);

View file

@ -1,16 +1,15 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
// @ts-check // @ts-check
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { import { EventTarget } from "internal:ext/web/02_event.js";
const { EventTarget } = window.__bootstrap.eventTarget; const primordials = globalThis.__bootstrap.primordials;
const { const {
Symbol, Symbol,
SymbolToStringTag, SymbolToStringTag,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const illegalConstructorKey = Symbol("illegalConstructorKey"); const illegalConstructorKey = Symbol("illegalConstructorKey");
@ -53,27 +52,32 @@
} }
} }
window.__bootstrap.globalInterfaces = { const dedicatedWorkerGlobalScopeConstructorDescriptor = {
DedicatedWorkerGlobalScope,
Window,
WorkerGlobalScope,
dedicatedWorkerGlobalScopeConstructorDescriptor: {
configurable: true, configurable: true,
enumerable: false, enumerable: false,
value: DedicatedWorkerGlobalScope, value: DedicatedWorkerGlobalScope,
writable: true, writable: true,
}, };
windowConstructorDescriptor: {
const windowConstructorDescriptor = {
configurable: true, configurable: true,
enumerable: false, enumerable: false,
value: Window, value: Window,
writable: true, writable: true,
}, };
workerGlobalScopeConstructorDescriptor: {
const workerGlobalScopeConstructorDescriptor = {
configurable: true, configurable: true,
enumerable: false, enumerable: false,
value: WorkerGlobalScope, value: WorkerGlobalScope,
writable: true, writable: true,
},
}; };
})(this);
export {
DedicatedWorkerGlobalScope,
dedicatedWorkerGlobalScopeConstructorDescriptor,
Window,
windowConstructorDescriptor,
WorkerGlobalScope,
workerGlobalScopeConstructorDescriptor,
};

View file

@ -6,17 +6,15 @@
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { DOMException } = window.__bootstrap.domException; import DOMException from "internal:ext/web/01_dom_exception.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
TypeErrorPrototype, TypeErrorPrototype,
} = window.__bootstrap.primordials; } = primordials;
/** /**
* @param {string} data * @param {string} data
@ -66,8 +64,4 @@
} }
} }
window.__bootstrap.base64 = { export { atob, btoa };
atob,
btoa,
};
})(globalThis);

View file

@ -5,13 +5,18 @@
/// <reference path="./06_streams_types.d.ts" /> /// <reference path="./06_streams_types.d.ts" />
/// <reference path="./lib.deno_web.d.ts" /> /// <reference path="./lib.deno_web.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { add, remove, signalAbort, newSignal, AbortSignalPrototype } = import {
window.__bootstrap.abortSignal; AbortSignalPrototype,
add,
newSignal,
remove,
signalAbort,
} from "internal:ext/web/03_abort_signal.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayBuffer, ArrayBuffer,
ArrayBufferPrototype, ArrayBufferPrototype,
@ -62,10 +67,9 @@
WeakMapPrototypeGet, WeakMapPrototypeGet,
WeakMapPrototypeHas, WeakMapPrototypeHas,
WeakMapPrototypeSet, WeakMapPrototypeSet,
} = globalThis.__bootstrap.primordials; } = primordials;
const consoleInternal = window.__bootstrap.console; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const ops = core.ops; import { assert, AssertionError } from "internal:ext/web/00_infra.js";
const { AssertionError, assert } = window.__bootstrap.infra;
/** @template T */ /** @template T */
class Deferred { class Deferred {
@ -1728,8 +1732,7 @@
pullIntoDescriptor, pullIntoDescriptor,
) )
) { ) {
const filledView = const filledView = readableByteStreamControllerConvertPullIntoDescriptor(
readableByteStreamControllerConvertPullIntoDescriptor(
pullIntoDescriptor, pullIntoDescriptor,
); );
readableByteStreamControllerHandleQueueDrain(controller); readableByteStreamControllerHandleQueueDrain(controller);
@ -2330,8 +2333,7 @@
}); });
} }
shutdownWithAction( shutdownWithAction(
() => () => SafePromiseAll(ArrayPrototypeMap(actions, (action) => action())),
SafePromiseAll(ArrayPrototypeMap(actions, (action) => action())),
true, true,
error, error,
); );
@ -2453,9 +2455,7 @@
return transformPromiseWith( return transformPromiseWith(
currentWrite, currentWrite,
() => () =>
oldCurrentWrite !== currentWrite oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined,
? waitForWritesToFinish()
: undefined,
); );
} }
@ -4551,7 +4551,7 @@
context: "Argument 1", context: "Argument 1",
}); });
this[webidl.brand] = webidl.brand; this[webidl.brand] = webidl.brand;
this[_globalObject] = window; this[_globalObject] = globalThis;
this[_highWaterMark] = init.highWaterMark; this[_highWaterMark] = init.highWaterMark;
} }
@ -4569,7 +4569,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
ByteLengthQueuingStrategyPrototype, ByteLengthQueuingStrategyPrototype,
@ -4584,8 +4584,7 @@
} }
webidl.configurePrototype(ByteLengthQueuingStrategy); webidl.configurePrototype(ByteLengthQueuingStrategy);
const ByteLengthQueuingStrategyPrototype = const ByteLengthQueuingStrategyPrototype = ByteLengthQueuingStrategy.prototype;
ByteLengthQueuingStrategy.prototype;
/** @type {WeakMap<typeof globalThis, (chunk: ArrayBufferView) => number>} */ /** @type {WeakMap<typeof globalThis, (chunk: ArrayBufferView) => number>} */
const byteSizeFunctionWeakMap = new WeakMap(); const byteSizeFunctionWeakMap = new WeakMap();
@ -4608,7 +4607,7 @@
context: "Argument 1", context: "Argument 1",
}); });
this[webidl.brand] = webidl.brand; this[webidl.brand] = webidl.brand;
this[_globalObject] = window; this[_globalObject] = globalThis;
this[_highWaterMark] = init.highWaterMark; this[_highWaterMark] = init.highWaterMark;
} }
@ -4626,7 +4625,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
CountQueuingStrategyPrototype, CountQueuingStrategyPrototype,
@ -4897,8 +4896,7 @@
} }
// TODO(lucacasonato): should be moved to webidl crate // TODO(lucacasonato): should be moved to webidl crate
ReadableStream.prototype[SymbolAsyncIterator] = ReadableStream.prototype[SymbolAsyncIterator] = ReadableStream.prototype.values;
ReadableStream.prototype.values;
ObjectDefineProperty(ReadableStream.prototype, SymbolAsyncIterator, { ObjectDefineProperty(ReadableStream.prototype, SymbolAsyncIterator, {
writable: true, writable: true,
enumerable: false, enumerable: false,
@ -5153,8 +5151,7 @@
respond(bytesWritten) { respond(bytesWritten) {
webidl.assertBranded(this, ReadableStreamBYOBRequestPrototype); webidl.assertBranded(this, ReadableStreamBYOBRequestPrototype);
const prefix = const prefix = "Failed to execute 'respond' on 'ReadableStreamBYOBRequest'";
"Failed to execute 'respond' on 'ReadableStreamBYOBRequest'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
bytesWritten = webidl.converters["unsigned long long"](bytesWritten, { bytesWritten = webidl.converters["unsigned long long"](bytesWritten, {
enforceRange: true, enforceRange: true,
@ -5198,8 +5195,7 @@
} }
webidl.configurePrototype(ReadableStreamBYOBRequest); webidl.configurePrototype(ReadableStreamBYOBRequest);
const ReadableStreamBYOBRequestPrototype = const ReadableStreamBYOBRequestPrototype = ReadableStreamBYOBRequest.prototype;
ReadableStreamBYOBRequest.prototype;
class ReadableByteStreamController { class ReadableByteStreamController {
/** @type {number | undefined} */ /** @type {number | undefined} */
@ -5312,7 +5308,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
ReadableByteStreamControllerPrototype, ReadableByteStreamControllerPrototype,
@ -5459,7 +5455,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
ReadableStreamDefaultController.prototype, ReadableStreamDefaultController.prototype,
@ -5683,7 +5679,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
TransformStreamDefaultController.prototype, TransformStreamDefaultController.prototype,
@ -5960,7 +5956,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
WritableStreamDefaultWriter.prototype, WritableStreamDefaultWriter.prototype,
@ -6028,7 +6024,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
WritableStreamDefaultController.prototype, WritableStreamDefaultController.prototype,
@ -6217,39 +6213,38 @@
{ key: "signal", converter: webidl.converters.AbortSignal }, { key: "signal", converter: webidl.converters.AbortSignal },
]); ]);
window.__bootstrap.streams = { export {
// Non-Public // Non-Public
_state, _state,
isReadableStreamDisturbed, // Exposed in global runtime scope
errorReadableStream, ByteLengthQueuingStrategy,
CountQueuingStrategy,
createProxy, createProxy,
writableStreamClose, Deferred,
errorReadableStream,
getReadableStreamResourceBacking,
getWritableStreamResourceBacking,
isReadableStreamDisturbed,
ReadableByteStreamController,
ReadableStream,
ReadableStreamBYOBReader,
ReadableStreamBYOBRequest,
readableStreamClose, readableStreamClose,
readableStreamCollectIntoUint8Array, readableStreamCollectIntoUint8Array,
ReadableStreamDefaultController,
ReadableStreamDefaultReader,
readableStreamDisturb, readableStreamDisturb,
readableStreamForRid, readableStreamForRid,
readableStreamForRidUnrefable, readableStreamForRidUnrefable,
readableStreamForRidUnrefableRef, readableStreamForRidUnrefableRef,
readableStreamForRidUnrefableUnref, readableStreamForRidUnrefableUnref,
readableStreamThrowIfErrored,
getReadableStreamResourceBacking,
writableStreamForRid,
getWritableStreamResourceBacking,
Deferred,
// Exposed in global runtime scope
ByteLengthQueuingStrategy,
CountQueuingStrategy,
ReadableStream,
ReadableStreamPrototype, ReadableStreamPrototype,
ReadableStreamDefaultReader, readableStreamThrowIfErrored,
TransformStream, TransformStream,
WritableStream,
WritableStreamDefaultWriter,
WritableStreamDefaultController,
ReadableByteStreamController,
ReadableStreamBYOBReader,
ReadableStreamBYOBRequest,
ReadableStreamDefaultController,
TransformStreamDefaultController, TransformStreamDefaultController,
WritableStream,
writableStreamClose,
WritableStreamDefaultController,
WritableStreamDefaultWriter,
writableStreamForRid,
}; };
})(this);

View file

@ -9,12 +9,10 @@
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
PromiseReject, PromiseReject,
PromiseResolve, PromiseResolve,
@ -27,7 +25,7 @@
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
ArrayBufferIsView, ArrayBufferIsView,
Uint32Array, Uint32Array,
} = window.__bootstrap.primordials; } = primordials;
class TextDecoder { class TextDecoder {
/** @type {string} */ /** @type {string} */
@ -435,11 +433,10 @@
return null; return null;
} }
window.__bootstrap.encoding = { export {
TextEncoder,
TextDecoder,
TextEncoderStream,
TextDecoderStream,
decode, decode,
TextDecoder,
TextDecoderStream,
TextEncoder,
TextEncoderStream,
}; };
})(this);

View file

@ -9,12 +9,11 @@
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayBufferPrototypeSlice, ArrayBufferPrototypeSlice,
@ -38,8 +37,8 @@
TypedArrayPrototypeSet, TypedArrayPrototypeSet,
TypeError, TypeError,
Uint8Array, Uint8Array,
} = window.__bootstrap.primordials; } = primordials;
const consoleInternal = window.__bootstrap.console; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
// TODO(lucacasonato): this needs to not be hardcoded and instead depend on // TODO(lucacasonato): this needs to not be hardcoded and instead depend on
// host os. // host os.
@ -384,7 +383,7 @@
} }
[SymbolFor("Deno.customInspect")](inspect) { [SymbolFor("Deno.customInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(BlobPrototype, this), evaluate: ObjectPrototypeIsPrototypeOf(BlobPrototype, this),
keys: [ keys: [
@ -627,12 +626,11 @@
return blob; return blob;
} }
window.__bootstrap.file = { export {
blobFromObjectUrl,
getParts,
Blob, Blob,
blobFromObjectUrl,
BlobPrototype, BlobPrototype,
File, File,
FilePrototype, FilePrototype,
getParts,
}; };
})(this);

View file

@ -10,17 +10,15 @@
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict"; const core = globalThis.Deno.core;
const ops = core.ops;
((window) => { import * as webidl from "internal:ext/webidl/00_webidl.js";
const core = window.Deno.core; const primordials = globalThis.__bootstrap.primordials;
const webidl = window.__bootstrap.webidl; import { forgivingBase64Encode } from "internal:ext/web/00_infra.js";
const { forgivingBase64Encode } = window.__bootstrap.infra; import { EventTarget, ProgressEvent } from "internal:ext/web/02_event.js";
const { ProgressEvent } = window.__bootstrap.event; import { decode, TextDecoder } from "internal:ext/web/08_text_encoding.js";
const { EventTarget } = window.__bootstrap.eventTarget; import { parseMimeType } from "internal:ext/web/01_mimesniff.js";
const { decode, TextDecoder } = window.__bootstrap.encoding; import DOMException from "internal:ext/web/01_dom_exception.js";
const { parseMimeType } = window.__bootstrap.mimesniff;
const { DOMException } = window.__bootstrap.domException;
const { const {
ArrayPrototypePush, ArrayPrototypePush,
ArrayPrototypeReduce, ArrayPrototypeReduce,
@ -37,7 +35,7 @@
TypeError, TypeError,
Uint8Array, Uint8Array,
Uint8ArrayPrototype, Uint8ArrayPrototype,
} = window.__bootstrap.primordials; } = primordials;
const state = Symbol("[[state]]"); const state = Symbol("[[state]]");
const result = Symbol("[[result]]"); const result = Symbol("[[result]]");
@ -169,7 +167,7 @@
break; break;
} }
case "BinaryString": case "BinaryString":
this[result] = core.ops.op_encode_binary_string(bytes); this[result] = ops.op_encode_binary_string(bytes);
break; break;
case "Text": { case "Text": {
let decoder = undefined; let decoder = undefined;
@ -490,7 +488,4 @@
return wrappedHandler; return wrappedHandler;
} }
window.__bootstrap.fileReader = { export { FileReader };
FileReader,
};
})(this);

View file

@ -10,14 +10,12 @@
/// <reference path="../url/lib.deno_url.d.ts" /> /// <reference path="../url/lib.deno_url.d.ts" />
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { getParts } = window.__bootstrap.file; import { getParts } from "internal:ext/web/09_file.js";
const { URL } = window.__bootstrap.url; import { URL } from "internal:ext/url/00_url.js";
/** /**
* @param {Blob} blob * @param {Blob} blob
@ -31,12 +29,7 @@
prefix, prefix,
}); });
const url = ops.op_blob_create_object_url( return ops.op_blob_create_object_url(blob.type, getParts(blob));
blob.type,
getParts(blob),
);
return url;
} }
/** /**
@ -56,4 +49,3 @@
URL.createObjectURL = createObjectURL; URL.createObjectURL = createObjectURL;
URL.revokeObjectURL = revokeObjectURL; URL.revokeObjectURL = revokeObjectURL;
})(globalThis);

View file

@ -1,11 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { import { URL } from "internal:ext/url/00_url.js";
const { URL } = window.__bootstrap.url; import DOMException from "internal:ext/web/01_dom_exception.js";
const { DOMException } = window.__bootstrap.domException; const primordials = globalThis.__bootstrap.primordials;
const { const {
Error, Error,
ObjectDefineProperties, ObjectDefineProperties,
@ -16,7 +15,7 @@
WeakMap, WeakMap,
WeakMapPrototypeGet, WeakMapPrototypeGet,
WeakMapPrototypeSet, WeakMapPrototypeSet,
} = window.__bootstrap.primordials; } = primordials;
const locationConstructorKey = Symbol("locationConstuctorKey"); const locationConstructorKey = Symbol("locationConstuctorKey");
@ -363,18 +362,23 @@
workerLocation = new WorkerLocation(href, locationConstructorKey); workerLocation = new WorkerLocation(href, locationConstructorKey);
} }
window.__bootstrap.location = { function getLocationHref() {
locationConstructorDescriptor: { return location?.href;
}
const locationConstructorDescriptor = {
value: Location, value: Location,
configurable: true, configurable: true,
writable: true, writable: true,
}, };
workerLocationConstructorDescriptor: {
const workerLocationConstructorDescriptor = {
value: WorkerLocation, value: WorkerLocation,
configurable: true, configurable: true,
writable: true, writable: true,
}, };
locationDescriptor: {
const locationDescriptor = {
get() { get() {
return location; return location;
}, },
@ -382,8 +386,8 @@
throw new DOMException(`Cannot set "location".`, "NotSupportedError"); throw new DOMException(`Cannot set "location".`, "NotSupportedError");
}, },
enumerable: true, enumerable: true,
}, };
workerLocationDescriptor: { const workerLocationDescriptor = {
get() { get() {
if (workerLocation == null) { if (workerLocation == null) {
throw new Error( throw new Error(
@ -394,10 +398,13 @@
}, },
configurable: true, configurable: true,
enumerable: true, enumerable: true,
},
setLocationHref,
getLocationHref() {
return location?.href;
},
}; };
})(this);
export {
getLocationHref,
locationConstructorDescriptor,
locationDescriptor,
setLocationHref,
workerLocationConstructorDescriptor,
workerLocationDescriptor,
};

View file

@ -6,15 +6,17 @@
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference path="./lib.deno_web.d.ts" /> /// <reference path="./lib.deno_web.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const { InterruptedPrototype, ops } = core; const { InterruptedPrototype, ops } = core;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { EventTarget, setEventTargetData } = window.__bootstrap.eventTarget; import {
const { MessageEvent, defineEventHandler } = window.__bootstrap.event; defineEventHandler,
const { DOMException } = window.__bootstrap.domException; EventTarget,
MessageEvent,
setEventTargetData,
} from "internal:ext/web/02_event.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayPrototypeFilter, ArrayPrototypeFilter,
@ -26,7 +28,7 @@
SymbolFor, SymbolFor,
SymbolIterator, SymbolIterator,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
class MessageChannel { class MessageChannel {
/** @type {MessagePort} */ /** @type {MessagePort} */
@ -194,7 +196,7 @@
} }
/** /**
* @param {globalThis.__bootstrap.messagePort.MessageData} messageData * @param {messagePort.MessageData} messageData
* @returns {[any, object[]]} * @returns {[any, object[]]}
*/ */
function deserializeJsMessageData(messageData) { function deserializeJsMessageData(messageData) {
@ -240,14 +242,14 @@
/** /**
* @param {any} data * @param {any} data
* @param {object[]} transferables * @param {object[]} transferables
* @returns {globalThis.__bootstrap.messagePort.MessageData} * @returns {messagePort.MessageData}
*/ */
function serializeJsMessageData(data, transferables) { function serializeJsMessageData(data, transferables) {
const transferredArrayBuffers = []; const transferredArrayBuffers = [];
for (let i = 0, j = 0; i < transferables.length; i++) { for (let i = 0, j = 0; i < transferables.length; i++) {
const ab = transferables[i]; const ab = transferables[i];
if (ObjectPrototypeIsPrototypeOf(ArrayBufferPrototype, ab)) { if (ObjectPrototypeIsPrototypeOf(ArrayBufferPrototype, ab)) {
if (ab.byteLength === 0 && core.ops.op_arraybuffer_was_detached(ab)) { if (ab.byteLength === 0 && ops.op_arraybuffer_was_detached(ab)) {
throw new DOMException( throw new DOMException(
`ArrayBuffer at index ${j} is already detached`, `ArrayBuffer at index ${j} is already detached`,
"DataCloneError", "DataCloneError",
@ -268,7 +270,7 @@
throw new DOMException(err, "DataCloneError"); throw new DOMException(err, "DataCloneError");
}); });
/** @type {globalThis.__bootstrap.messagePort.Transferable[]} */ /** @type {messagePort.Transferable[]} */
const serializedTransferables = []; const serializedTransferables = [];
let arrayBufferI = 0; let arrayBufferI = 0;
@ -332,12 +334,11 @@
return deserializeJsMessageData(messageData)[0]; return deserializeJsMessageData(messageData)[0];
} }
window.__bootstrap.messagePort = { export {
deserializeJsMessageData,
MessageChannel, MessageChannel,
MessagePort, MessagePort,
MessagePortPrototype, MessagePortPrototype,
deserializeJsMessageData,
serializeJsMessageData, serializeJsMessageData,
structuredClone, structuredClone,
}; };
})(globalThis);

View file

@ -5,13 +5,10 @@
/// <reference path="./internal.d.ts" /> /// <reference path="./internal.d.ts" />
/// <reference path="./lib.deno_web.d.ts" /> /// <reference path="./lib.deno_web.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { TransformStream } = window.__bootstrap.streams; import { TransformStream } from "internal:ext/web/06_streams.js";
webidl.converters.CompressionFormat = webidl.createEnumConverter( webidl.converters.CompressionFormat = webidl.createEnumConverter(
"CompressionFormat", "CompressionFormat",
@ -124,8 +121,4 @@
webidl.configurePrototype(DecompressionStream); webidl.configurePrototype(DecompressionStream);
const DecompressionStreamPrototype = DecompressionStream.prototype; const DecompressionStreamPrototype = DecompressionStream.prototype;
window.__bootstrap.compression = { export { CompressionStream, DecompressionStream };
CompressionStream,
DecompressionStream,
};
})(globalThis);

View file

@ -1,7 +1,6 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeFilter, ArrayPrototypeFilter,
ArrayPrototypeFind, ArrayPrototypeFind,
@ -14,13 +13,13 @@
Symbol, Symbol,
SymbolFor, SymbolFor,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
import * as webidl from "internal:ext/webidl/00_webidl.js";
const { webidl, structuredClone } = window.__bootstrap; import { structuredClone } from "internal:ext/web/02_structured_clone.js";
const consoleInternal = window.__bootstrap.console; import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const { EventTarget } = window.__bootstrap.eventTarget; import { EventTarget } from "internal:ext/web/02_event.js";
const { opNow } = window.__bootstrap.timers; import { opNow } from "internal:ext/web/02_timers.js";
const { DOMException } = window.__bootstrap.domException; import DOMException from "internal:ext/web/01_dom_exception.js";
const illegalConstructorKey = Symbol("illegalConstructorKey"); const illegalConstructorKey = Symbol("illegalConstructorKey");
const customInspect = SymbolFor("Deno.customInspect"); const customInspect = SymbolFor("Deno.customInspect");
@ -183,7 +182,7 @@
} }
[customInspect](inspect) { [customInspect](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
PerformanceEntryPrototype, PerformanceEntryPrototype,
@ -254,7 +253,7 @@
} }
[customInspect](inspect) { [customInspect](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(PerformanceMarkPrototype, this), evaluate: ObjectPrototypeIsPrototypeOf(PerformanceMarkPrototype, this),
keys: [ keys: [
@ -310,7 +309,7 @@
} }
[customInspect](inspect) { [customInspect](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf( evaluate: ObjectPrototypeIsPrototypeOf(
PerformanceMeasurePrototype, PerformanceMeasurePrototype,
@ -568,7 +567,7 @@
} }
[customInspect](inspect) { [customInspect](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({ return inspect(createFilteredInspectProxy({
object: this, object: this,
evaluate: ObjectPrototypeIsPrototypeOf(PerformancePrototype, this), evaluate: ObjectPrototypeIsPrototypeOf(PerformancePrototype, this),
keys: [], keys: [],
@ -583,12 +582,13 @@
PerformancePrototype, PerformancePrototype,
); );
window.__bootstrap.performance = { const performance = new Performance(illegalConstructorKey);
export {
Performance,
performance,
PerformanceEntry, PerformanceEntry,
PerformanceMark, PerformanceMark,
PerformanceMeasure, PerformanceMeasure,
Performance,
performance: new Performance(illegalConstructorKey),
setTimeOrigin, setTimeOrigin,
}; };
})(this);

View file

@ -29,11 +29,12 @@ fn setup() -> Vec<Extension> {
deno_console::init(), deno_console::init(),
deno_web::init::<Permissions>(BlobStore::default(), None), deno_web::init::<Permissions>(BlobStore::default(), None),
Extension::builder("bench_setup") Extension::builder("bench_setup")
.js(vec![( .esm(vec![(
"setup", "internal:setup",
r#" r#"
const { TextDecoder } = globalThis.__bootstrap.encoding; import { TextDecoder } from "internal:ext/web/08_text_encoding.js";
const hello12k = Deno.core.encode("hello world\n".repeat(1e3)); globalThis.TextDecoder = TextDecoder;
globalThis.hello12k = Deno.core.encode("hello world\n".repeat(1e3));
"#, "#,
)]) )])
.state(|state| { .state(|state| {

View file

@ -28,9 +28,10 @@ fn setup() -> Vec<Extension> {
deno_console::init(), deno_console::init(),
deno_web::init::<Permissions>(BlobStore::default(), None), deno_web::init::<Permissions>(BlobStore::default(), None),
Extension::builder("bench_setup") Extension::builder("bench_setup")
.js(vec![ .esm(vec![
("setup", r#" ("internal:setup", r#"
const { setTimeout, handleTimerMacrotask } = globalThis.__bootstrap.timers; import { setTimeout, handleTimerMacrotask } from "internal:ext/web/02_timers.js";
globalThis.setTimeout = setTimeout;
Deno.core.setMacrotaskCallback(handleTimerMacrotask); Deno.core.setMacrotaskCallback(handleTimerMacrotask);
"#), "#),
]) ])

143
ext/web/internal.d.ts vendored
View file

@ -1,14 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
// deno-lint-ignore-file no-var
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
declare namespace globalThis { declare module "internal:ext/web/00_infra.js" {
declare namespace __bootstrap { function collectSequenceOfCodepoints(
declare var infra: {
collectSequenceOfCodepoints(
input: string, input: string,
position: number, position: number,
condition: (char: string) => boolean, condition: (char: string) => boolean,
@ -16,26 +12,26 @@ declare namespace globalThis {
result: string; result: string;
position: number; position: number;
}; };
ASCII_DIGIT: string[]; const ASCII_DIGIT: string[];
ASCII_UPPER_ALPHA: string[]; const ASCII_UPPER_ALPHA: string[];
ASCII_LOWER_ALPHA: string[]; const ASCII_LOWER_ALPHA: string[];
ASCII_ALPHA: string[]; const ASCII_ALPHA: string[];
ASCII_ALPHANUMERIC: string[]; const ASCII_ALPHANUMERIC: string[];
HTTP_TAB_OR_SPACE: string[]; const HTTP_TAB_OR_SPACE: string[];
HTTP_WHITESPACE: string[]; const HTTP_WHITESPACE: string[];
HTTP_TOKEN_CODE_POINT: string[]; const HTTP_TOKEN_CODE_POINT: string[];
HTTP_TOKEN_CODE_POINT_RE: RegExp; const HTTP_TOKEN_CODE_POINT_RE: RegExp;
HTTP_QUOTED_STRING_TOKEN_POINT: string[]; const HTTP_QUOTED_STRING_TOKEN_POINT: string[];
HTTP_QUOTED_STRING_TOKEN_POINT_RE: RegExp; const HTTP_QUOTED_STRING_TOKEN_POINT_RE: RegExp;
HTTP_TAB_OR_SPACE_PREFIX_RE: RegExp; const HTTP_TAB_OR_SPACE_PREFIX_RE: RegExp;
HTTP_TAB_OR_SPACE_SUFFIX_RE: RegExp; const HTTP_TAB_OR_SPACE_SUFFIX_RE: RegExp;
HTTP_WHITESPACE_PREFIX_RE: RegExp; const HTTP_WHITESPACE_PREFIX_RE: RegExp;
HTTP_WHITESPACE_SUFFIX_RE: RegExp; const HTTP_WHITESPACE_SUFFIX_RE: RegExp;
httpTrim(s: string): string; function httpTrim(s: string): string;
regexMatcher(chars: string[]): string; function regexMatcher(chars: string[]): string;
byteUpperCase(s: string): string; function byteUpperCase(s: string): string;
byteLowerCase(s: string): string; function byteLowerCase(s: string): string;
collectHttpQuotedString( function collectHttpQuotedString(
input: string, input: string,
position: number, position: number,
extractValue: boolean, extractValue: boolean,
@ -43,78 +39,73 @@ declare namespace globalThis {
result: string; result: string;
position: number; position: number;
}; };
forgivingBase64Encode(data: Uint8Array): string; function forgivingBase64Encode(data: Uint8Array): string;
forgivingBase64Decode(data: string): Uint8Array; function forgivingBase64Decode(data: string): Uint8Array;
serializeJSValueToJSONString(value: unknown): string; function serializeJSValueToJSONString(value: unknown): string;
}; }
declare var domException: { declare module "internal:ext/web/01_dom_exception.js" {
DOMException: typeof DOMException; export = DOMException;
}; }
declare namespace mimesniff { declare module "internal:ext/web/01_mimesniff.js" {
declare interface MimeType { interface MimeType {
type: string; type: string;
subtype: string; subtype: string;
parameters: Map<string, string>; parameters: Map<string, string>;
} }
declare function parseMimeType(input: string): MimeType | null; function parseMimeType(input: string): MimeType | null;
declare function essence(mimeType: MimeType): string; function essence(mimeType: MimeType): string;
declare function serializeMimeType(mimeType: MimeType): string; function serializeMimeType(mimeType: MimeType): string;
declare function extractMimeType( function extractMimeType(
headerValues: string[] | null, headerValues: string[] | null,
): MimeType | null; ): MimeType | null;
} }
declare var eventTarget: { declare module "internal:ext/web/02_event.js" {
EventTarget: typeof EventTarget; const EventTarget: typeof EventTarget;
}; const Event: typeof event;
const ErrorEvent: typeof ErrorEvent;
const CloseEvent: typeof CloseEvent;
const MessageEvent: typeof MessageEvent;
const CustomEvent: typeof CustomEvent;
const ProgressEvent: typeof ProgressEvent;
const PromiseRejectionEvent: typeof PromiseRejectionEvent;
const reportError: typeof reportError;
}
declare var event: { declare module "internal:ext/web/12_location.js" {
Event: typeof event; function getLocationHref(): string | undefined;
ErrorEvent: typeof ErrorEvent; }
CloseEvent: typeof CloseEvent;
MessageEvent: typeof MessageEvent;
CustomEvent: typeof CustomEvent;
ProgressEvent: typeof ProgressEvent;
PromiseRejectionEvent: typeof PromiseRejectionEvent;
reportError: typeof reportError;
};
declare var location: { declare module "internal:ext/web/05_base64.js" {
getLocationHref(): string | undefined; function atob(data: string): string;
}; function btoa(data: string): string;
}
declare var base64: { declare module "internal:ext/web/09_file.js" {
atob(data: string): string; function blobFromObjectUrl(url: string): Blob | null;
btoa(data: string): string; function getParts(blob: Blob): string[];
}; const Blob: typeof Blob;
const File: typeof File;
}
declare var file: { declare module "internal:ext/web/06_streams.js" {
blobFromObjectUrl(url: string): Blob | null; const ReadableStream: typeof ReadableStream;
getParts(blob: Blob): string[]; function isReadableStreamDisturbed(stream: ReadableStream): boolean;
Blob: typeof Blob; function createProxy<T>(stream: ReadableStream<T>): ReadableStream<T>;
File: typeof File; }
};
declare var streams: { declare module "internal:ext/web/13_message_port.js" {
ReadableStream: typeof ReadableStream; type Transferable = {
isReadableStreamDisturbed(stream: ReadableStream): boolean;
createProxy<T>(stream: ReadableStream<T>): ReadableStream<T>;
};
declare namespace messagePort {
declare type Transferable = {
kind: "messagePort"; kind: "messagePort";
data: number; data: number;
} | { } | {
kind: "arrayBuffer"; kind: "arrayBuffer";
data: number; data: number;
}; };
declare interface MessageData { interface MessageData {
data: Uint8Array; data: Uint8Array;
transferables: Transferable[]; transferables: Transferable[];
} }
} }
}
}

View file

@ -64,7 +64,7 @@ pub fn init<P: TimersPermission + 'static>(
) -> Extension { ) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_console", "deno_url"]) .dependencies(vec!["deno_webidl", "deno_console", "deno_url"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/web", prefix "internal:ext/web",
"00_infra.js", "00_infra.js",
"01_dom_exception.js", "01_dom_exception.js",

View file

@ -6,14 +6,12 @@
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
/// <reference path="./lib.deno_webgpu.d.ts" /> /// <reference path="./lib.deno_webgpu.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; const primordials = globalThis.__bootstrap.primordials;
const eventTarget = window.__bootstrap.eventTarget; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { DOMException } = window.__bootstrap.domException; import { EventTarget } from "internal:ext/web/02_event.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
const { const {
ArrayBuffer, ArrayBuffer,
ArrayBufferIsView, ArrayBufferIsView,
@ -42,7 +40,7 @@
Uint32ArrayPrototype, Uint32ArrayPrototype,
Uint8Array, Uint8Array,
WeakRef, WeakRef,
} = window.__bootstrap.primordials; } = primordials;
const _rid = Symbol("[[rid]]"); const _rid = Symbol("[[rid]]");
const _size = Symbol("[[size]]"); const _size = Symbol("[[size]]");
@ -856,7 +854,7 @@
return device; return device;
} }
class GPUDevice extends eventTarget.EventTarget { class GPUDevice extends EventTarget {
/** @type {InnerGPUDevice} */ /** @type {InnerGPUDevice} */
[_device]; [_device];
@ -1805,9 +1803,7 @@
prefix, prefix,
context: "Argument 2", context: "Argument 2",
}); });
size = size === undefined size = size === undefined ? undefined : webidl.converters.GPUSize64(size, {
? undefined
: webidl.converters.GPUSize64(size, {
prefix, prefix,
context: "Argument 3", context: "Argument 3",
}); });
@ -2753,8 +2749,7 @@
*/ */
beginRenderPass(descriptor) { beginRenderPass(descriptor) {
webidl.assertBranded(this, GPUCommandEncoderPrototype); webidl.assertBranded(this, GPUCommandEncoderPrototype);
const prefix = const prefix = "Failed to execute 'beginRenderPass' on 'GPUCommandEncoder'";
"Failed to execute 'beginRenderPass' on 'GPUCommandEncoder'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
descriptor = webidl.converters.GPURenderPassDescriptor(descriptor, { descriptor = webidl.converters.GPURenderPassDescriptor(descriptor, {
prefix, prefix,
@ -3085,9 +3080,7 @@
{ {
texture: sourceTextureRid, texture: sourceTextureRid,
mipLevel: source.mipLevel, mipLevel: source.mipLevel,
origin: source.origin origin: source.origin ? normalizeGPUOrigin3D(source.origin) : undefined,
? normalizeGPUOrigin3D(source.origin)
: undefined,
aspect: source.aspect, aspect: source.aspect,
}, },
{ {
@ -3149,9 +3142,7 @@
{ {
texture: sourceTextureRid, texture: sourceTextureRid,
mipLevel: source.mipLevel, mipLevel: source.mipLevel,
origin: source.origin origin: source.origin ? normalizeGPUOrigin3D(source.origin) : undefined,
? normalizeGPUOrigin3D(source.origin)
: undefined,
aspect: source.aspect, aspect: source.aspect,
}, },
{ {
@ -3211,8 +3202,7 @@
*/ */
pushDebugGroup(groupLabel) { pushDebugGroup(groupLabel) {
webidl.assertBranded(this, GPUCommandEncoderPrototype); webidl.assertBranded(this, GPUCommandEncoderPrototype);
const prefix = const prefix = "Failed to execute 'pushDebugGroup' on 'GPUCommandEncoder'";
"Failed to execute 'pushDebugGroup' on 'GPUCommandEncoder'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
groupLabel = webidl.converters.USVString(groupLabel, { groupLabel = webidl.converters.USVString(groupLabel, {
prefix, prefix,
@ -3274,8 +3264,7 @@
*/ */
writeTimestamp(querySet, queryIndex) { writeTimestamp(querySet, queryIndex) {
webidl.assertBranded(this, GPUCommandEncoderPrototype); webidl.assertBranded(this, GPUCommandEncoderPrototype);
const prefix = const prefix = "Failed to execute 'writeTimestamp' on 'GPUCommandEncoder'";
"Failed to execute 'writeTimestamp' on 'GPUCommandEncoder'";
webidl.requiredArguments(arguments.length, 2, { prefix }); webidl.requiredArguments(arguments.length, 2, { prefix });
querySet = webidl.converters.GPUQuerySet(querySet, { querySet = webidl.converters.GPUQuerySet(querySet, {
prefix, prefix,
@ -3322,8 +3311,7 @@
destinationOffset, destinationOffset,
) { ) {
webidl.assertBranded(this, GPUCommandEncoderPrototype); webidl.assertBranded(this, GPUCommandEncoderPrototype);
const prefix = const prefix = "Failed to execute 'resolveQuerySet' on 'GPUCommandEncoder'";
"Failed to execute 'resolveQuerySet' on 'GPUCommandEncoder'";
webidl.requiredArguments(arguments.length, 5, { prefix }); webidl.requiredArguments(arguments.length, 5, { prefix });
querySet = webidl.converters.GPUQuerySet(querySet, { querySet = webidl.converters.GPUQuerySet(querySet, {
prefix, prefix,
@ -3467,8 +3455,7 @@
*/ */
setViewport(x, y, width, height, minDepth, maxDepth) { setViewport(x, y, width, height, minDepth, maxDepth) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'setViewport' on 'GPUComputePassEncoder'";
"Failed to execute 'setViewport' on 'GPUComputePassEncoder'";
webidl.requiredArguments(arguments.length, 6, { prefix }); webidl.requiredArguments(arguments.length, 6, { prefix });
x = webidl.converters.float(x, { prefix, context: "Argument 1" }); x = webidl.converters.float(x, { prefix, context: "Argument 1" });
y = webidl.converters.float(y, { prefix, context: "Argument 2" }); y = webidl.converters.float(y, { prefix, context: "Argument 2" });
@ -3775,8 +3762,7 @@
dynamicOffsetsDataLength, dynamicOffsetsDataLength,
) { ) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'setBindGroup' on 'GPURenderPassEncoder'";
"Failed to execute 'setBindGroup' on 'GPURenderPassEncoder'";
const device = assertDevice(this[_encoder], { const device = assertDevice(this[_encoder], {
prefix, prefix,
context: "encoder referenced by this", context: "encoder referenced by this",
@ -3884,8 +3870,7 @@
*/ */
setPipeline(pipeline) { setPipeline(pipeline) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'setPipeline' on 'GPURenderPassEncoder'";
"Failed to execute 'setPipeline' on 'GPURenderPassEncoder'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
pipeline = webidl.converters.GPURenderPipeline(pipeline, { pipeline = webidl.converters.GPURenderPipeline(pipeline, {
prefix, prefix,
@ -4083,8 +4068,7 @@
firstInstance = 0, firstInstance = 0,
) { ) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'drawIndexed' on 'GPURenderPassEncoder'";
"Failed to execute 'drawIndexed' on 'GPURenderPassEncoder'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
indexCount = webidl.converters.GPUSize32(indexCount, { indexCount = webidl.converters.GPUSize32(indexCount, {
prefix, prefix,
@ -4131,8 +4115,7 @@
*/ */
drawIndirect(indirectBuffer, indirectOffset) { drawIndirect(indirectBuffer, indirectOffset) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'drawIndirect' on 'GPURenderPassEncoder'";
"Failed to execute 'drawIndirect' on 'GPURenderPassEncoder'";
webidl.requiredArguments(arguments.length, 2, { prefix }); webidl.requiredArguments(arguments.length, 2, { prefix });
indirectBuffer = webidl.converters.GPUBuffer(indirectBuffer, { indirectBuffer = webidl.converters.GPUBuffer(indirectBuffer, {
prefix, prefix,
@ -4173,8 +4156,7 @@
*/ */
drawIndexedIndirect(indirectBuffer, indirectOffset) { drawIndexedIndirect(indirectBuffer, indirectOffset) {
webidl.assertBranded(this, GPURenderPassEncoderPrototype); webidl.assertBranded(this, GPURenderPassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'drawIndirect' on 'GPURenderPassEncoder'";
"Failed to execute 'drawIndirect' on 'GPURenderPassEncoder'";
webidl.requiredArguments(arguments.length, 2, { prefix }); webidl.requiredArguments(arguments.length, 2, { prefix });
indirectBuffer = webidl.converters.GPUBuffer(indirectBuffer, { indirectBuffer = webidl.converters.GPUBuffer(indirectBuffer, {
prefix, prefix,
@ -4260,8 +4242,7 @@
*/ */
setPipeline(pipeline) { setPipeline(pipeline) {
webidl.assertBranded(this, GPUComputePassEncoderPrototype); webidl.assertBranded(this, GPUComputePassEncoderPrototype);
const prefix = const prefix = "Failed to execute 'setPipeline' on 'GPUComputePassEncoder'";
"Failed to execute 'setPipeline' on 'GPUComputePassEncoder'";
webidl.requiredArguments(arguments.length, 1, { prefix }); webidl.requiredArguments(arguments.length, 1, { prefix });
pipeline = webidl.converters.GPUComputePipeline(pipeline, { pipeline = webidl.converters.GPUComputePipeline(pipeline, {
prefix, prefix,
@ -5223,43 +5204,43 @@
GPUObjectBaseMixin("GPUQuerySet", GPUQuerySet); GPUObjectBaseMixin("GPUQuerySet", GPUQuerySet);
const GPUQuerySetPrototype = GPUQuerySet.prototype; const GPUQuerySetPrototype = GPUQuerySet.prototype;
window.__bootstrap.webgpu = { const gpu = webidl.createBranded(GPU);
export {
_device, _device,
assertDevice, assertDevice,
createGPUTexture, createGPUTexture,
gpu: webidl.createBranded(GPU),
GPU, GPU,
gpu,
GPUAdapter, GPUAdapter,
GPUAdapterInfo, GPUAdapterInfo,
GPUSupportedLimits, GPUBindGroup,
GPUSupportedFeatures, GPUBindGroupLayout,
GPUDevice,
GPUDeviceLostInfo,
GPUQueue,
GPUBuffer, GPUBuffer,
GPUBufferUsage, GPUBufferUsage,
GPUColorWrite,
GPUCommandBuffer,
GPUCommandEncoder,
GPUComputePassEncoder,
GPUComputePipeline,
GPUDevice,
GPUDeviceLostInfo,
GPUError,
GPUMapMode, GPUMapMode,
GPUTextureUsage, GPUOutOfMemoryError,
GPUTexture,
GPUTextureView,
GPUSampler,
GPUBindGroupLayout,
GPUPipelineLayout, GPUPipelineLayout,
GPUBindGroup, GPUQuerySet,
GPUQueue,
GPURenderBundle,
GPURenderBundleEncoder,
GPURenderPassEncoder,
GPURenderPipeline,
GPUSampler,
GPUShaderModule, GPUShaderModule,
GPUShaderStage, GPUShaderStage,
GPUComputePipeline, GPUSupportedFeatures,
GPURenderPipeline, GPUSupportedLimits,
GPUColorWrite, GPUTexture,
GPUCommandEncoder, GPUTextureUsage,
GPURenderPassEncoder, GPUTextureView,
GPUComputePassEncoder,
GPUCommandBuffer,
GPURenderBundleEncoder,
GPURenderBundle,
GPUQuerySet,
GPUError,
GPUValidationError, GPUValidationError,
GPUOutOfMemoryError,
}; };
})(this);

View file

@ -3,43 +3,41 @@
// @ts-check // @ts-check
/// <reference path="../web/internal.d.ts" /> /// <reference path="../web/internal.d.ts" />
"use strict"; import * as webidl from "internal:ext/webidl/00_webidl.js";
import {
((window) => {
const webidl = window.__bootstrap.webidl;
const {
GPU, GPU,
GPUAdapter, GPUAdapter,
GPUSupportedLimits, GPUBindGroup,
GPUSupportedFeatures, GPUBindGroupLayout,
GPUDevice,
GPUQueue,
GPUBuffer, GPUBuffer,
GPUBufferUsage, GPUBufferUsage,
GPUColorWrite,
GPUCommandBuffer,
GPUCommandEncoder,
GPUComputePassEncoder,
GPUComputePipeline,
GPUDevice,
GPUMapMode, GPUMapMode,
GPUTextureUsage, GPUOutOfMemoryError,
GPUTexture,
GPUTextureView,
GPUSampler,
GPUBindGroupLayout,
GPUPipelineLayout, GPUPipelineLayout,
GPUBindGroup, GPUQuerySet,
GPUQueue,
GPURenderBundle,
GPURenderBundleEncoder,
GPURenderPassEncoder,
GPURenderPipeline,
GPUSampler,
GPUShaderModule, GPUShaderModule,
GPUShaderStage, GPUShaderStage,
GPUComputePipeline, GPUSupportedFeatures,
GPURenderPipeline, GPUSupportedLimits,
GPUColorWrite, GPUTexture,
GPUCommandEncoder, GPUTextureUsage,
GPURenderPassEncoder, GPUTextureView,
GPUComputePassEncoder,
GPUCommandBuffer,
GPURenderBundleEncoder,
GPURenderBundle,
GPUQuerySet,
GPUOutOfMemoryError,
GPUValidationError, GPUValidationError,
} = window.__bootstrap.webgpu; } from "internal:ext/webgpu/01_webgpu.js";
const { SymbolIterator, TypeError } = window.__bootstrap.primordials; const primordials = globalThis.__bootstrap.primordials;
const { SymbolIterator, TypeError } = primordials;
// This needs to be initialized after all of the base classes are implemented, // This needs to be initialized after all of the base classes are implemented,
// otherwise their converters might not be available yet. // otherwise their converters might not be available yet.
@ -993,8 +991,7 @@
}, },
{ {
key: "constants", key: "constants",
converter: converter: webidl.converters["record<USVString, GPUPipelineConstantValue>"],
webidl.converters["record<USVString, GPUPipelineConstantValue>"],
}, },
]; ];
webidl.converters["GPUProgrammableStage"] = webidl.createDictionaryConverter( webidl.converters["GPUProgrammableStage"] = webidl.createDictionaryConverter(
@ -2037,4 +2034,3 @@
// TYPEDEF: GPUFlagsConstant // TYPEDEF: GPUFlagsConstant
webidl.converters["GPUFlagsConstant"] = webidl.converters["unsigned long"]; webidl.converters["GPUFlagsConstant"] = webidl.converters["unsigned long"];
})(this);

View file

@ -6,14 +6,16 @@
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
/// <reference path="./lib.deno_webgpu.d.ts" /> /// <reference path="./lib.deno_webgpu.d.ts" />
"use strict"; const core = globalThis.Deno.core;
((window) => {
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { Symbol } = window.__bootstrap.primordials; const primordials = globalThis.__bootstrap.primordials;
const { _device, assertDevice, createGPUTexture } = window.__bootstrap.webgpu; const { Symbol } = primordials;
import {
_device,
assertDevice,
createGPUTexture,
} from "internal:ext/webgpu/01_webgpu.js";
const _surfaceRid = Symbol("[[surfaceRid]]"); const _surfaceRid = Symbol("[[surfaceRid]]");
const _configuration = Symbol("[[configuration]]"); const _configuration = Symbol("[[configuration]]");
@ -141,9 +143,4 @@
return canvasContext; return canvasContext;
} }
window.__bootstrap.webgpu = { export { createCanvasContext, GPUCanvasContext };
...window.__bootstrap.webgpu,
GPUCanvasContext,
createCanvasContext,
};
})(this);

View file

@ -6,11 +6,8 @@
/// <reference path="../web/lib.deno_web.d.ts" /> /// <reference path="../web/lib.deno_web.d.ts" />
/// <reference path="./lib.deno_webgpu.d.ts" /> /// <reference path="./lib.deno_webgpu.d.ts" />
"use strict"; import * as webidl from "internal:ext/webidl/00_webidl.js";
import { GPUTextureUsage } from "internal:ext/webgpu/01_webgpu.js";
((window) => {
const webidl = window.__bootstrap.webidl;
const { GPUTextureUsage } = window.__bootstrap.webgpu;
// ENUM: GPUCanvasAlphaMode // ENUM: GPUCanvasAlphaMode
webidl.converters["GPUCanvasAlphaMode"] = webidl.createEnumConverter( webidl.converters["GPUCanvasAlphaMode"] = webidl.createEnumConverter(
@ -83,4 +80,3 @@
"GPUCanvasConfiguration", "GPUCanvasConfiguration",
dictMembersGPUCanvasConfiguration, dictMembersGPUCanvasConfiguration,
); );
})(this);

View file

@ -119,7 +119,7 @@ impl Resource for WebGpuQuerySet {
pub fn init(unstable: bool) -> Extension { pub fn init(unstable: bool) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web"]) .dependencies(vec!["deno_webidl", "deno_web"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/webgpu", prefix "internal:ext/webgpu",
"01_webgpu.js", "01_webgpu.js",
"02_idl_types.js", "02_idl_types.js",

View file

@ -15,8 +15,8 @@ use wgpu_types::SurfaceStatus;
pub fn init_surface(unstable: bool) -> Extension { pub fn init_surface(unstable: bool) -> Extension {
Extension::builder("deno_webgpu_surface") Extension::builder("deno_webgpu_surface")
.dependencies(vec!["deno_webidl", "deno_web", "deno_webgpu"]) .dependencies(vec!["deno_webidl", "deno_web", "deno_webgpu"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:deno_webgpu", prefix "internal:ext/webgpu",
"03_surface.js", "03_surface.js",
"04_surface_idl_types.js", "04_surface_idl_types.js",
)) ))

View file

@ -6,10 +6,8 @@
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
"use strict"; const core = globalThis.Deno.core;
const primordials = globalThis.__bootstrap.primordials;
((window) => {
const core = window.Deno.core;
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayBufferIsView, ArrayBufferIsView,
@ -83,7 +81,7 @@
Uint32Array, Uint32Array,
Uint8Array, Uint8Array,
Uint8ClampedArray, Uint8ClampedArray,
} = window.__bootstrap.primordials; } = primordials;
function makeException(ErrorType, message, opts = {}) { function makeException(ErrorType, message, opts = {}) {
return new ErrorType( return new ErrorType(
@ -1165,27 +1163,25 @@
} }
} }
window.__bootstrap ??= {}; export {
window.__bootstrap.webidl = { assertBranded,
type, brand,
makeException, configurePrototype,
converters, converters,
requiredArguments, createBranded,
createDictionaryConverter, createDictionaryConverter,
createEnumConverter, createEnumConverter,
createNullableConverter,
createSequenceConverter,
createRecordConverter,
createPromiseConverter,
invokeCallbackFunction,
createInterfaceConverter, createInterfaceConverter,
brand, createNullableConverter,
createBranded, createPromiseConverter,
assertBranded, createRecordConverter,
createSequenceConverter,
illegalConstructor, illegalConstructor,
invokeCallbackFunction,
makeException,
mixinPairIterable, mixinPairIterable,
configurePrototype, requiredArguments,
setlike, setlike,
setlikeInner, setlikeInner,
type,
}; };
})(this);

View file

@ -2,7 +2,10 @@
// deno-lint-ignore-file // deno-lint-ignore-file
const { createDictionaryConverter, converters } = globalThis.__bootstrap.webidl; import {
converters,
createDictionaryConverter,
} from "internal:ext/webidl/00_webidl.js";
const TextDecodeOptions = createDictionaryConverter( const TextDecodeOptions = createDictionaryConverter(
"TextDecodeOptions", "TextDecodeOptions",
@ -14,6 +17,7 @@ const TextDecodeOptions = createDictionaryConverter(
}, },
], ],
); );
globalThis.TextDecodeOptions = TextDecodeOptions;
// Sanity check // Sanity check
{ {
@ -33,3 +37,4 @@ function handwrittenConverter(V) {
} }
return defaultValue; return defaultValue;
} }
globalThis.handwrittenConverter = handwrittenConverter;

View file

@ -11,7 +11,7 @@ fn setup() -> Vec<Extension> {
vec![ vec![
deno_webidl::init(), deno_webidl::init(),
Extension::builder("deno_webidl_bench") Extension::builder("deno_webidl_bench")
.js(vec![("setup", include_str!("dict.js"))]) .esm(vec![("internal:setup", include_str!("dict.js"))])
.build(), .build(),
] ]
} }

View file

@ -4,10 +4,8 @@
/// <reference no-default-lib="true" /> /// <reference no-default-lib="true" />
/// <reference lib="esnext" /> /// <reference lib="esnext" />
declare namespace globalThis { declare module "internal:ext/webidl/00_webidl.js" {
declare namespace __bootstrap { interface ConverterOpts {
declare namespace webidl {
declare interface ConverterOpts {
/** /**
* The prefix for error messages created by this converter. * The prefix for error messages created by this converter.
* Examples: * Examples:
@ -16,7 +14,7 @@ declare namespace globalThis {
*/ */
prefix: string; prefix: string;
} }
declare interface ValueConverterOpts extends ConverterOpts { interface ValueConverterOpts extends ConverterOpts {
/** /**
* The context of this value error messages created by this converter. * The context of this value error messages created by this converter.
* Examples: * Examples:
@ -25,12 +23,12 @@ declare namespace globalThis {
*/ */
context: string; context: string;
} }
declare function makeException( function makeException(
ErrorType: any, ErrorType: any,
message: string, message: string,
opts: ValueConverterOpts, opts: ValueConverterOpts,
): any; ): any;
declare interface IntConverterOpts extends ValueConverterOpts { interface IntConverterOpts extends ValueConverterOpts {
/** /**
* Wether to throw if the number is outside of the acceptable values for * Wether to throw if the number is outside of the acceptable values for
* this type. * this type.
@ -41,19 +39,19 @@ declare namespace globalThis {
*/ */
clamp?: boolean; clamp?: boolean;
} }
declare interface StringConverterOpts extends ValueConverterOpts { interface StringConverterOpts extends ValueConverterOpts {
/** /**
* Wether to treat `null` value as an empty string. * Wether to treat `null` value as an empty string.
*/ */
treatNullAsEmptyString?: boolean; treatNullAsEmptyString?: boolean;
} }
declare interface BufferConverterOpts extends ValueConverterOpts { interface BufferConverterOpts extends ValueConverterOpts {
/** /**
* Wether to allow `SharedArrayBuffer` (not just `ArrayBuffer`). * Wether to allow `SharedArrayBuffer` (not just `ArrayBuffer`).
*/ */
allowShared?: boolean; allowShared?: boolean;
} }
declare const converters: { const converters: {
any(v: any): any; any(v: any): any;
/** /**
* Convert a value into a `boolean` (bool). * Convert a value into a `boolean` (bool).
@ -205,13 +203,13 @@ declare namespace globalThis {
/** /**
* Assert that the a function has at least a required amount of arguments. * Assert that the a function has at least a required amount of arguments.
*/ */
declare function requiredArguments( function requiredArguments(
length: number, length: number,
required: number, required: number,
opts: ConverterOpts, opts: ConverterOpts,
): void; ): void;
declare type Dictionary = DictionaryMember[]; type Dictionary = DictionaryMember[];
declare interface DictionaryMember { interface DictionaryMember {
key: string; key: string;
converter: (v: any, opts: ValueConverterOpts) => any; converter: (v: any, opts: ValueConverterOpts) => any;
defaultValue?: any; defaultValue?: any;
@ -221,7 +219,7 @@ declare namespace globalThis {
/** /**
* Create a converter for dictionaries. * Create a converter for dictionaries.
*/ */
declare function createDictionaryConverter<T>( function createDictionaryConverter<T>(
name: string, name: string,
...dictionaries: Dictionary[] ...dictionaries: Dictionary[]
): (v: any, opts: ValueConverterOpts) => T; ): (v: any, opts: ValueConverterOpts) => T;
@ -229,7 +227,7 @@ declare namespace globalThis {
/** /**
* Create a converter for enums. * Create a converter for enums.
*/ */
declare function createEnumConverter( function createEnumConverter(
name: string, name: string,
values: string[], values: string[],
): (v: any, opts: ValueConverterOpts) => string; ): (v: any, opts: ValueConverterOpts) => string;
@ -237,28 +235,28 @@ declare namespace globalThis {
/** /**
* Create a converter that makes the contained type nullable. * Create a converter that makes the contained type nullable.
*/ */
declare function createNullableConverter<T>( function createNullableConverter<T>(
converter: (v: any, opts: ValueConverterOpts) => T, converter: (v: any, opts: ValueConverterOpts) => T,
): (v: any, opts: ValueConverterOpts) => T | null; ): (v: any, opts: ValueConverterOpts) => T | null;
/** /**
* Create a converter that converts a sequence of the inner type. * Create a converter that converts a sequence of the inner type.
*/ */
declare function createSequenceConverter<T>( function createSequenceConverter<T>(
converter: (v: any, opts: ValueConverterOpts) => T, converter: (v: any, opts: ValueConverterOpts) => T,
): (v: any, opts: ValueConverterOpts) => T[]; ): (v: any, opts: ValueConverterOpts) => T[];
/** /**
* Create a converter that converts a Promise of the inner type. * Create a converter that converts a Promise of the inner type.
*/ */
declare function createPromiseConverter<T>( function createPromiseConverter<T>(
converter: (v: any, opts: ValueConverterOpts) => T, converter: (v: any, opts: ValueConverterOpts) => T,
): (v: any, opts: ValueConverterOpts) => Promise<T>; ): (v: any, opts: ValueConverterOpts) => Promise<T>;
/** /**
* Invoke a callback function. * Invoke a callback function.
*/ */
declare function invokeCallbackFunction<T>( function invokeCallbackFunction<T>(
callable: (...args: any) => any, callable: (...args: any) => any,
args: any[], args: any[],
thisArg: any, thisArg: any,
@ -269,32 +267,32 @@ declare namespace globalThis {
/** /**
* Throw an illegal constructor error. * Throw an illegal constructor error.
*/ */
declare function illegalConstructor(): never; function illegalConstructor(): never;
/** /**
* The branding symbol. * The branding symbol.
*/ */
declare const brand: unique symbol; const brand: unique symbol;
/** /**
* Create a branded instance of an interface. * Create a branded instance of an interface.
*/ */
declare function createBranded(self: any): any; function createBranded(self: any): any;
/** /**
* Assert that self is branded. * Assert that self is branded.
*/ */
declare function assertBranded(self: any, type: any): void; function assertBranded(self: any, type: any): void;
/** /**
* Create a converter for interfaces. * Create a converter for interfaces.
*/ */
declare function createInterfaceConverter( function createInterfaceConverter(
name: string, name: string,
prototype: any, prototype: any,
): (v: any, opts: ValueConverterOpts) => any; ): (v: any, opts: ValueConverterOpts) => any;
declare function createRecordConverter< function createRecordConverter<
K extends string | number | symbol, K extends string | number | symbol,
V, V,
>( >(
@ -309,7 +307,7 @@ declare namespace globalThis {
* Mix in the iterable declarations defined in WebIDL. * Mix in the iterable declarations defined in WebIDL.
* https://heycam.github.io/webidl/#es-iterable * https://heycam.github.io/webidl/#es-iterable
*/ */
declare function mixinPairIterable( function mixinPairIterable(
name: string, name: string,
prototype: any, prototype: any,
dataSymbol: symbol, dataSymbol: symbol,
@ -320,12 +318,12 @@ declare namespace globalThis {
/** /**
* Configure prototype properties enumerability / writability / configurability. * Configure prototype properties enumerability / writability / configurability.
*/ */
declare function configurePrototype(prototype: any); function configurePrototype(prototype: any);
/** /**
* Get the WebIDL / ES type of a value. * Get the WebIDL / ES type of a value.
*/ */
declare function type( function type(
v: any, v: any,
): ):
| "Null" | "Null"
@ -337,5 +335,3 @@ declare namespace globalThis {
| "BigInt" | "BigInt"
| "Object"; | "Object";
} }
}
}

View file

@ -6,7 +6,7 @@ use deno_core::Extension;
/// Load and execute the javascript code. /// Load and execute the javascript code.
pub fn init() -> Extension { pub fn init() -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/webidl", prefix "internal:ext/webidl",
"00_webidl.js", "00_webidl.js",
)) ))

View file

@ -1,25 +1,24 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const { URL } = window.__bootstrap.url; import { URL } from "internal:ext/url/00_url.js";
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { HTTP_TOKEN_CODE_POINT_RE } = window.__bootstrap.infra; import { HTTP_TOKEN_CODE_POINT_RE } from "internal:ext/web/00_infra.js";
const { DOMException } = window.__bootstrap.domException; import DOMException from "internal:ext/web/01_dom_exception.js";
const { import {
Event,
ErrorEvent,
CloseEvent,
MessageEvent,
defineEventHandler,
_skipInternalInit, _skipInternalInit,
} = window.__bootstrap.event; CloseEvent,
const { EventTarget } = window.__bootstrap.eventTarget; defineEventHandler,
const { Blob, BlobPrototype } = globalThis.__bootstrap.file; ErrorEvent,
Event,
EventTarget,
MessageEvent,
} from "internal:ext/web/02_event.js";
import { Blob, BlobPrototype } from "internal:ext/web/09_file.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayBufferPrototype, ArrayBufferPrototype,
ArrayBufferIsView, ArrayBufferIsView,
@ -42,7 +41,7 @@
SymbolIterator, SymbolIterator,
PromisePrototypeCatch, PromisePrototypeCatch,
SymbolFor, SymbolFor,
} = window.__bootstrap.primordials; } = primordials;
webidl.converters["sequence<DOMString> or DOMString"] = (V, opts) => { webidl.converters["sequence<DOMString> or DOMString"] = (V, opts) => {
// Union for (sequence<DOMString> or DOMString) // Union for (sequence<DOMString> or DOMString)
@ -225,8 +224,7 @@
if ( if (
ArrayPrototypeSome( ArrayPrototypeSome(
protocols, protocols,
(protocol) => (protocol) => !RegExpPrototypeTest(HTTP_TOKEN_CODE_POINT_RE, protocol),
!RegExpPrototypeTest(HTTP_TOKEN_CODE_POINT_RE, protocol),
) )
) { ) {
throw new DOMException( throw new DOMException(
@ -565,15 +563,14 @@
webidl.configurePrototype(WebSocket); webidl.configurePrototype(WebSocket);
const WebSocketPrototype = WebSocket.prototype; const WebSocketPrototype = WebSocket.prototype;
window.__bootstrap.webSocket = { export {
WebSocket,
_rid,
_readyState,
_eventLoop, _eventLoop,
_protocol,
_server,
_idleTimeoutDuration, _idleTimeoutDuration,
_idleTimeoutTimeout, _idleTimeoutTimeout,
_protocol,
_readyState,
_rid,
_server,
_serverHandleIdleTimeout, _serverHandleIdleTimeout,
WebSocket,
}; };
})(this);

View file

@ -1,18 +1,19 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { writableStreamClose, Deferred } = window.__bootstrap.streams; import { Deferred, writableStreamClose } from "internal:ext/web/06_streams.js";
const { DOMException } = window.__bootstrap.domException; import DOMException from "internal:ext/web/01_dom_exception.js";
const { add, remove } = window.__bootstrap.abortSignal; import { add, remove } from "internal:ext/web/03_abort_signal.js";
const { headersFromHeaderList, headerListFromHeaders, fillHeaders } = import {
window.__bootstrap.headers; fillHeaders,
headerListFromHeaders,
headersFromHeaderList,
} from "internal:ext/fetch/20_headers.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
ArrayPrototypeJoin, ArrayPrototypeJoin,
ArrayPrototypeMap, ArrayPrototypeMap,
@ -27,7 +28,7 @@
SymbolFor, SymbolFor,
TypeError, TypeError,
Uint8ArrayPrototype, Uint8ArrayPrototype,
} = window.__bootstrap.primordials; } = primordials;
webidl.converters.WebSocketStreamOptions = webidl.createDictionaryConverter( webidl.converters.WebSocketStreamOptions = webidl.createDictionaryConverter(
"WebSocketStreamOptions", "WebSocketStreamOptions",
@ -153,9 +154,7 @@
"op_ws_create", "op_ws_create",
"new WebSocketStream()", "new WebSocketStream()",
this[_url], this[_url],
options.protocols options.protocols ? ArrayPrototypeJoin(options.protocols, ", ") : "",
? ArrayPrototypeJoin(options.protocols, ", ")
: "",
cancelRid, cancelRid,
headerListFromHeaders(headers), headerListFromHeaders(headers),
), ),
@ -422,5 +421,4 @@
const WebSocketStreamPrototype = WebSocketStream.prototype; const WebSocketStreamPrototype = WebSocketStream.prototype;
window.__bootstrap.webSocket.WebSocketStream = WebSocketStream; export { WebSocketStream };
})(this);

View file

@ -504,7 +504,7 @@ pub fn init<P: WebSocketPermissions + 'static>(
) -> Extension { ) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_url", "deno_webidl"]) .dependencies(vec!["deno_url", "deno_webidl"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/websocket", prefix "internal:ext/websocket",
"01_websocket.js", "01_websocket.js",
"02_websocketstream.js", "02_websocketstream.js",

View file

@ -2,10 +2,10 @@
/// <reference path="../../core/internal.d.ts" /> /// <reference path="../../core/internal.d.ts" />
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const { const {
SafeArrayIterator, SafeArrayIterator,
Symbol, Symbol,
@ -16,7 +16,7 @@
ReflectGet, ReflectGet,
ReflectHas, ReflectHas,
Proxy, Proxy,
} = window.__bootstrap.primordials; } = primordials;
const _persistent = Symbol("[[persistent]]"); const _persistent = Symbol("[[persistent]]");
@ -171,22 +171,20 @@
return proxy; return proxy;
} }
let localStorage; let localStorageStorage;
let sessionStorage; function localStorage() {
if (!localStorageStorage) {
localStorageStorage = createStorage(true);
}
return localStorageStorage;
}
window.__bootstrap.webStorage = { let sessionStorageStorage;
localStorage() { function sessionStorage() {
if (!localStorage) { if (!sessionStorageStorage) {
localStorage = createStorage(true); sessionStorageStorage = createStorage(false);
} }
return localStorage; return sessionStorageStorage;
},
sessionStorage() {
if (!sessionStorage) {
sessionStorage = createStorage(false);
} }
return sessionStorage;
}, export { localStorage, sessionStorage, Storage };
Storage,
};
})(this);

View file

@ -24,7 +24,7 @@ const MAX_STORAGE_BYTES: u32 = 10 * 1024 * 1024;
pub fn init(origin_storage_dir: Option<PathBuf>) -> Extension { pub fn init(origin_storage_dir: Option<PathBuf>) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME")) Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl"]) .dependencies(vec!["deno_webidl"])
.js(include_js_files!( .esm(include_js_files!(
prefix "internal:ext/webstorage", prefix "internal:ext/webstorage",
"01_webstorage.js", "01_webstorage.js",
)) ))

View file

@ -5,7 +5,6 @@ use std::env;
use std::path::PathBuf; use std::path::PathBuf;
// This is a shim that allows to generate documentation on docs.rs // This is a shim that allows to generate documentation on docs.rs
#[cfg(not(feature = "docsrs"))]
mod not_docs { mod not_docs {
use std::path::Path; use std::path::Path;
@ -121,7 +120,7 @@ mod not_docs {
} }
} }
fn create_runtime_snapshot(snapshot_path: PathBuf, files: Vec<PathBuf>) { fn create_runtime_snapshot(snapshot_path: PathBuf, esm_files: Vec<PathBuf>) {
let extensions_with_js: Vec<Extension> = vec![ let extensions_with_js: Vec<Extension> = vec![
deno_webidl::init(), deno_webidl::init(),
deno_console::init(), deno_console::init(),
@ -158,7 +157,8 @@ mod not_docs {
startup_snapshot: None, startup_snapshot: None,
extensions: vec![], extensions: vec![],
extensions_with_js, extensions_with_js,
additional_files: files, additional_files: vec![],
additional_esm_files: esm_files,
compression_cb: Some(Box::new(|vec, snapshot_slice| { compression_cb: Some(Box::new(|vec, snapshot_slice| {
lzzzz::lz4_hc::compress_to_vec( lzzzz::lz4_hc::compress_to_vec(
snapshot_slice, snapshot_slice,
@ -172,14 +172,19 @@ mod not_docs {
pub fn build_snapshot(runtime_snapshot_path: PathBuf) { pub fn build_snapshot(runtime_snapshot_path: PathBuf) {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js"); let mut esm_files = get_js_files(
env!("CARGO_MANIFEST_DIR"),
"js",
Some(Box::new(|path| !path.ends_with("99_main.js"))),
);
#[cfg(not(feature = "snapshot_from_snapshot"))] #[cfg(not(feature = "snapshot_from_snapshot"))]
{ {
let manifest = env!("CARGO_MANIFEST_DIR"); let manifest = env!("CARGO_MANIFEST_DIR");
let path = PathBuf::from(manifest); let path = PathBuf::from(manifest);
js_files.push(path.join("js").join("99_main.js")); esm_files.push(path.join("js").join("99_main.js"));
} }
create_runtime_snapshot(runtime_snapshot_path, js_files); create_runtime_snapshot(runtime_snapshot_path, esm_files);
} }
} }

View file

@ -1,8 +1,7 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const primordials = globalThis.__bootstrap.primordials;
const { ObjectFreeze, StringPrototypeSplit } = window.__bootstrap.primordials; const { ObjectFreeze, StringPrototypeSplit } = primordials;
const build = { const build = {
target: "unknown", target: "unknown",
@ -26,8 +25,4 @@
ObjectFreeze(build); ObjectFreeze(build);
} }
window.__bootstrap.build = { export { build, setBuildInfo };
build,
setBuildInfo,
};
})(this);

View file

@ -1,10 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const { Error } = window.__bootstrap.primordials;
const { BadResource, Interrupted } = core; const { BadResource, Interrupted } = core;
const primordials = globalThis.__bootstrap.primordials;
const { Error } = primordials;
class NotFound extends Error { class NotFound extends Error {
constructor(msg) { constructor(msg) {
@ -147,7 +146,4 @@
NotSupported, NotSupported,
}; };
window.__bootstrap.errors = { export { errors };
errors,
};
})(this);

View file

@ -1,8 +1,7 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const primordials = globalThis.__bootstrap.primordials;
const { ObjectFreeze } = window.__bootstrap.primordials; const { ObjectFreeze } = primordials;
const version = { const version = {
deno: "", deno: "",
@ -22,8 +21,4 @@
ObjectFreeze(version); ObjectFreeze(version);
} }
window.__bootstrap.version = { export { setVersions, version };
version,
setVersions,
};
})(this);

View file

@ -1,25 +0,0 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const { TypeError, Symbol } = window.__bootstrap.primordials;
const illegalConstructorKey = Symbol("illegalConstructorKey");
function requiredArguments(
name,
length,
required,
) {
if (length < required) {
const errMsg = `${name} requires at least ${required} argument${
required === 1 ? "" : "s"
}, but only ${length} present`;
throw new TypeError(errMsg);
}
}
window.__bootstrap.webUtil = {
illegalConstructorKey,
requiredArguments,
};
})(this);

View file

@ -1,7 +1,7 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const { const {
decodeURIComponent, decodeURIComponent,
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
@ -9,9 +9,9 @@
SafeArrayIterator, SafeArrayIterator,
StringPrototypeReplace, StringPrototypeReplace,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const { build } = window.__bootstrap.build; import { build } from "internal:runtime/js/01_build.js";
const { URLPrototype } = window.__bootstrap.url; import { URLPrototype } from "internal:ext/url/00_url.js";
let logDebug = false; let logDebug = false;
let logSource = "JS"; let logSource = "JS";
@ -96,10 +96,8 @@
return pathOrUrl; return pathOrUrl;
} }
window.__bootstrap.internals = { // TODO(bartlomieju): remove
...window.__bootstrap.internals ?? {}, internals.pathFromURL = pathFromURL;
pathFromURL,
};
function writable(value) { function writable(value) {
return { return {
@ -137,14 +135,13 @@
}; };
} }
window.__bootstrap.util = { export {
log,
setLogDebug,
createResolvable, createResolvable,
pathFromURL,
writable,
nonEnumerable,
readOnly,
getterOnly, getterOnly,
log,
nonEnumerable,
pathFromURL,
readOnly,
setLogDebug,
writable,
}; };
})(this);

View file

@ -1,12 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const { ops } = Deno.core; const ops = core.ops;
const { Event } = window.__bootstrap.event; import { Event, EventTarget } from "internal:ext/web/02_event.js";
const { EventTarget } = window.__bootstrap.eventTarget; import { pathFromURL } from "internal:runtime/js/06_util.js";
const { pathFromURL } = window.__bootstrap.util; const primordials = globalThis.__bootstrap.primordials;
const { illegalConstructorKey } = window.__bootstrap.webUtil;
const { const {
ArrayIsArray, ArrayIsArray,
ArrayPrototypeIncludes, ArrayPrototypeIncludes,
@ -21,9 +19,12 @@
PromiseReject, PromiseReject,
ReflectHas, ReflectHas,
SafeArrayIterator, SafeArrayIterator,
Symbol,
SymbolFor, SymbolFor,
TypeError, TypeError,
} = window.__bootstrap.primordials; } = primordials;
const illegalConstructorKey = Symbol("illegalConstructorKey");
/** /**
* @typedef StatusCacheValue * @typedef StatusCacheValue
@ -278,10 +279,4 @@
return permissions; return permissions;
} }
window.__bootstrap.permissions = { export { Permissions, permissions, PermissionStatus, serializePermissions };
serializePermissions,
permissions,
Permissions,
PermissionStatus,
};
})(this);

View file

@ -1,9 +1,8 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => { const core = globalThis.Deno.core;
const core = window.Deno.core;
const ops = core.ops; const ops = core.ops;
const primordials = globalThis.__bootstrap.primordials;
const { const {
Error, Error,
ObjectPrototypeIsPrototypeOf, ObjectPrototypeIsPrototypeOf,
@ -11,20 +10,23 @@
String, String,
SymbolIterator, SymbolIterator,
SymbolToStringTag, SymbolToStringTag,
} = window.__bootstrap.primordials; } = primordials;
const webidl = window.__bootstrap.webidl; import * as webidl from "internal:ext/webidl/00_webidl.js";
const { URL } = window.__bootstrap.url; import { URL } from "internal:ext/url/00_url.js";
const { getLocationHref } = window.__bootstrap.location; import { getLocationHref } from "internal:ext/web/12_location.js";
const { serializePermissions } = window.__bootstrap.permissions; import { serializePermissions } from "internal:runtime/js/10_permissions.js";
const { log } = window.__bootstrap.util; import { log } from "internal:runtime/js/06_util.js";
const { ErrorEvent, MessageEvent, defineEventHandler } = import {
window.__bootstrap.event; defineEventHandler,
const { EventTarget } = window.__bootstrap.eventTarget; ErrorEvent,
const { EventTarget,
MessageEvent,
} from "internal:ext/web/02_event.js";
import {
deserializeJsMessageData, deserializeJsMessageData,
serializeJsMessageData,
MessagePortPrototype, MessagePortPrototype,
} = window.__bootstrap.messagePort; serializeJsMessageData,
} from "internal:ext/web/13_message_port.js";
function createWorker( function createWorker(
specifier, specifier,
@ -131,7 +133,7 @@
// TODO(nayeemrmn): It's not correct to use `e.fileName` to detect user // TODO(nayeemrmn): It's not correct to use `e.fileName` to detect user
// errors. It won't be there for non-awaited async ops for example. // errors. It won't be there for non-awaited async ops for example.
if (e.fileName && !event.defaultPrevented) { if (e.fileName && !event.defaultPrevented) {
window.dispatchEvent(event); globalThis.dispatchEvent(event);
} }
return event.defaultPrevented; return event.defaultPrevented;
@ -248,7 +250,4 @@
"module", "module",
]); ]);
window.__bootstrap.worker = { export { Worker };
Worker,
};
})(this);

Some files were not shown because too many files have changed in this diff Show more