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 {
JsRuntime::new(RuntimeOptions {
extensions_with_js: setup(),
module_loader: Some(std::rc::Rc::new(
deno_core::InternalModuleLoader::new(None),
)),
..Default::default()
})
}

View file

@ -275,6 +275,7 @@ mod ts {
.build()],
extensions_with_js: vec![],
additional_files: files,
additional_esm_files: vec![],
compression_cb: Some(Box::new(|vec, snapshot_slice| {
vec.extend_from_slice(
&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![
deno_webidl::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()),
extensions,
extensions_with_js: vec![],
additional_files: files,
additional_files: vec![],
additional_esm_files: esm_files,
compression_cb: Some(Box::new(|vec, snapshot_slice| {
lzzzz::lz4_hc::compress_to_vec(
snapshot_slice,
@ -448,13 +450,13 @@ fn main() {
let o = PathBuf::from(env::var_os("OUT_DIR").unwrap());
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);
let cli_snapshot_path = o.join("CLI_SNAPSHOT.bin");
let mut js_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js");
js_files.push(deno_runtime::js::get_99_main());
create_cli_snapshot(cli_snapshot_path, js_files);
let mut esm_files = get_js_files(env!("CARGO_MANIFEST_DIR"), "js", None);
esm_files.push(deno_runtime::js::get_99_main());
create_cli_snapshot(cli_snapshot_path, esm_files);
#[cfg(target_os = "windows")]
{

View file

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

View file

@ -3844,3 +3844,15 @@ itest!(node_prefix_missing {
envs: env_vars_for_npm_tests_no_sync_download(),
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
queueMicrotask
error: Uncaught 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 });
const internals = {};
ObjectAssign(globalThis.__bootstrap, { internals });
ObjectAssign(globalThis.Deno, { core });
// Direct bindings on `globalThis`

View file

@ -267,9 +267,11 @@ pub fn host_import_module_dynamically_callback<'s>(
.unwrap()
.to_rust_string_lossy(scope);
let is_internal_module = specifier_str.starts_with("internal:");
let resolver = v8::PromiseResolver::new(scope).unwrap();
let promise = resolver.get_promise(scope);
if !is_internal_module {
let assertions = parse_import_assertions(
scope,
import_assertions,
@ -305,7 +307,7 @@ pub fn host_import_module_dynamically_callback<'s>(
);
state_rc.borrow_mut().notify_new_dynamic_import();
}
}
// 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
// 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();
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)
}

View file

@ -38,6 +38,7 @@ impl OpDecl {
#[derive(Default)]
pub struct Extension {
js_files: Option<Vec<SourcePair>>,
esm_files: Option<Vec<SourcePair>>,
ops: Option<Vec<OpDecl>>,
opstate_fn: Option<Box<OpStateFn>>,
middleware_fn: Option<Box<OpMiddlewareFn>>,
@ -81,13 +82,20 @@ impl Extension {
/// 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.
pub fn init_js(&self) -> &[SourcePair] {
pub fn get_js_sources(&self) -> &[SourcePair] {
match &self.js_files {
Some(files) => files,
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.
pub fn init_ops(&mut self) -> Option<Vec<OpDecl>> {
// TODO(@AaronO): maybe make op registration idempotent
@ -145,6 +153,7 @@ impl Extension {
#[derive(Default)]
pub struct ExtensionBuilder {
js: Vec<SourcePair>,
esm: Vec<SourcePair>,
ops: Vec<OpDecl>,
state: Option<Box<OpStateFn>>,
middleware: Option<Box<OpMiddlewareFn>>,
@ -164,6 +173,11 @@ impl ExtensionBuilder {
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 {
self.ops.extend(ops);
self
@ -195,10 +209,12 @@ impl ExtensionBuilder {
pub fn build(&mut self) -> Extension {
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 deps = Some(std::mem::take(&mut self.deps));
Extension {
js_files,
esm_files,
ops,
opstate_fn: self.state.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::DUMMY_SPECIFIER;
pub use crate::modules::FsModuleLoader;
pub use crate::modules::InternalModuleLoader;
pub use crate::modules::ModuleId;
pub use crate::modules::ModuleLoader;
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.
///
/// Note that this loader will **block** event loop
@ -2508,4 +2571,33 @@ if (import.meta.url != 'file:///main_with_code.js') throw Error();
)
.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::ModuleLoader;
use crate::modules::ModuleMap;
use crate::modules::NoopModuleLoader;
use crate::op_void_async;
use crate::op_void_sync;
use crate::ops::*;
use crate::source_map::SourceMapCache;
use crate::source_map::SourceMapGetter;
use crate::Extension;
use crate::NoopModuleLoader;
use crate::OpMiddlewareFn;
use crate::OpResult;
use crate::OpState;
use crate::PromiseId;
use anyhow::Context as AnyhowContext;
use anyhow::Error;
use futures::channel::oneshot;
use futures::future::poll_fn;
@ -605,9 +606,16 @@ impl JsRuntime {
None
};
let loader = options
let loader = if snapshot_options != SnapshotOptions::Load {
Rc::new(crate::modules::InternalModuleLoader::new(
options.module_loader,
))
} else {
options
.module_loader
.unwrap_or_else(|| Rc::new(NoopModuleLoader));
.unwrap_or_else(|| Rc::new(NoopModuleLoader))
};
{
let mut state = state_rc.borrow_mut();
state.global_realm = Some(JsRealm(global_context.clone()));
@ -805,12 +813,32 @@ impl JsRuntime {
// Take extensions to avoid double-borrow
let extensions = std::mem::take(&mut self.extensions_with_js);
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 {
// TODO(@AaronO): use JsRuntime::execute_static() here to move src off heap
realm.execute_script(self.v8_isolate(), filename, source)?;
}
}
}
// Restore extensions
self.extensions_with_js = extensions;

View file

@ -1,10 +1,12 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
use anyhow::Context;
use std::path::Path;
use std::path::PathBuf;
use crate::Extension;
use crate::JsRuntime;
use crate::ModuleSpecifier;
use crate::RuntimeOptions;
use crate::Snapshot;
@ -17,6 +19,7 @@ pub struct CreateSnapshotOptions {
pub extensions: Vec<Extension>,
pub extensions_with_js: Vec<Extension>,
pub additional_files: Vec<PathBuf>,
pub additional_esm_files: Vec<PathBuf>,
pub compression_cb: Option<Box<CompressionCb>>,
}
@ -44,6 +47,27 @@ pub fn create_snapshot(create_snapshot_options: CreateSnapshotOptions) {
)
.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_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(
cargo_manifest_dir: &'static str,
directory: &str,
filter: Option<FilterFn>,
) -> Vec<PathBuf> {
let manifest_dir = Path::new(cargo_manifest_dir);
let mut js_files = std::fs::read_dir(directory)
@ -92,7 +119,7 @@ pub fn get_js_files(
})
.filter(|path| {
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>>();
js_files.sort();

View file

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

View file

@ -112,7 +112,7 @@ pub fn init<BC: BroadcastChannel + 'static>(
) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web"])
.js(include_js_files!(
.esm(include_js_files!(
prefix "internal:ext/broadcast_channel",
"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.
"use strict";
((window) => {
const core = window.__bootstrap.core;
const webidl = window.__bootstrap.webidl;
const core = globalThis.Deno.core;
import * as webidl from "internal:ext/webidl/00_webidl.js";
const primordials = globalThis.__bootstrap.primordials;
const {
Symbol,
TypeError,
ObjectPrototypeIsPrototypeOf,
} = window.__bootstrap.primordials;
const {
} = primordials;
import {
Request,
toInnerResponse,
RequestPrototype,
toInnerRequest,
} = window.__bootstrap.fetch;
const { URLPrototype } = window.__bootstrap.url;
const RequestPrototype = Request.prototype;
const { getHeader } = window.__bootstrap.headers;
const { readableStreamForRid } = window.__bootstrap.streams;
} from "internal:ext/fetch/23_request.js";
import { toInnerResponse } from "internal:ext/fetch/23_response.js";
import { URLPrototype } from "internal:ext/url/00_url.js";
import { getHeader } from "internal:ext/fetch/20_headers.js";
import { readableStreamForRid } from "internal:ext/web/06_streams.js";
class CacheStorage {
constructor() {
@ -282,15 +281,12 @@
const CacheStoragePrototype = CacheStorage.prototype;
const CachePrototype = Cache.prototype;
let cacheStorage;
window.__bootstrap.caches = {
CacheStorage,
Cache,
cacheStorage() {
if (!cacheStorage) {
cacheStorage = webidl.createBranded(CacheStorage);
let cacheStorageStorage;
function cacheStorage() {
if (!cacheStorageStorage) {
cacheStorageStorage = webidl.createBranded(CacheStorage);
}
return cacheStorage;
},
};
})(this);
return cacheStorageStorage;
}
export { Cache, CacheStorage, cacheStorage };

2
ext/cache/lib.rs vendored
View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -75,7 +75,7 @@ use crate::shared::RawKeyData;
pub fn init(maybe_seed: Option<u64>) -> Extension {
Extension::builder(env!("CARGO_PKG_NAME"))
.dependencies(vec!["deno_webidl", "deno_web"])
.js(include_js_files!(
.esm(include_js_files!(
prefix "internal:ext/crypto",
"00_crypto.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="./lib.deno_fetch.d.ts" />
/// <reference lib="esnext" />
"use strict";
((window) => {
const webidl = window.__bootstrap.webidl;
const {
import * as webidl from "internal:ext/webidl/00_webidl.js";
import {
byteLowerCase,
collectHttpQuotedString,
collectSequenceOfCodepoints,
HTTP_TAB_OR_SPACE_PREFIX_RE,
HTTP_TAB_OR_SPACE_SUFFIX_RE,
HTTP_TOKEN_CODE_POINT_RE,
byteLowerCase,
collectSequenceOfCodepoints,
collectHttpQuotedString,
httpTrim,
} = window.__bootstrap.infra;
} from "internal:ext/web/00_infra.js";
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayIsArray,
ArrayPrototypeMap,
@ -38,7 +37,7 @@
SymbolIterator,
StringPrototypeReplaceAll,
TypeError,
} = window.__bootstrap.primordials;
} = primordials;
const _headerList = Symbol("header list");
const _iterableHeaders = Symbol("iterable headers");
@ -452,7 +451,7 @@
}
/**
* @param {Headers}
* @param {Headers} headers
* @returns {HeaderList}
*/
function headerListFromHeaders(headers) {
@ -460,20 +459,19 @@
}
/**
* @param {Headers}
* @param {Headers} headers
* @returns {"immutable" | "request" | "request-no-cors" | "response" | "none"}
*/
function guardFromHeaders(headers) {
return headers[_guard];
}
window.__bootstrap.headers = {
headersFromHeaderList,
headerListFromHeaders,
getDecodeSplitHeader,
guardFromHeaders,
export {
fillHeaders,
getDecodeSplitHeader,
getHeader,
guardFromHeaders,
headerListFromHeaders,
Headers,
headersFromHeaderList,
};
})(this);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,10 +1,9 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
const ops = core.ops;
const __bootstrap = window.__bootstrap;
const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayPrototypeMap,
ArrayPrototypeJoin,
@ -26,7 +25,7 @@
MathCeil,
SafeMap,
SafeArrayIterator,
} = window.__bootstrap.primordials;
} = primordials;
const U32_BUFFER = new Uint32Array(2);
const U64_BUFFER = new BigUint64Array(U32_BUFFER.buffer);
@ -495,16 +494,16 @@
}
function dlopen(path, symbols) {
// TODO(@crowlKats): remove me
// 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);
}
window.__bootstrap.ffi = {
export {
dlopen,
UnsafeCallback,
UnsafeFnPointer,
UnsafePointer,
UnsafePointerView,
UnsafeFnPointer,
};
})(this);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,15 +1,14 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
const { BadResourcePrototype, InterruptedPrototype, ops } = core;
const {
import {
readableStreamForRidUnrefable,
readableStreamForRidUnrefableRef,
readableStreamForRidUnrefableUnref,
writableStreamForRid,
} = window.__bootstrap.streams;
} from "internal:ext/web/06_streams.js";
const primordials = globalThis.__bootstrap.primordials;
const {
Error,
ObjectPrototypeIsPrototypeOf,
@ -19,7 +18,7 @@
TypedArrayPrototypeSubarray,
TypeError,
Uint8Array,
} = window.__bootstrap.primordials;
} = primordials;
const promiseIdSymbol = SymbolFor("Deno.core.internalPromiseId");
@ -408,16 +407,15 @@
}
}
window.__bootstrap.net = {
connect,
export {
Conn,
connect,
createListenDatagram,
Datagram,
listen,
Listener,
resolveDns,
shutdown,
TcpConn,
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.
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
const ops = core.ops;
const { Listener, Conn } = window.__bootstrap.net;
const { TypeError } = window.__bootstrap.primordials;
import { Conn, Listener } from "internal:ext/net/01_net.js";
const primordials = globalThis.__bootstrap.primordials;
const { TypeError } = primordials;
function opStartTls(args) {
return core.opAsync("op_tls_start", args);
@ -96,11 +95,4 @@
return new TlsConn(rid, remoteAddr, localAddr);
}
window.__bootstrap.tls = {
startTls,
listenTls,
connectTls,
TlsConn,
TlsListener,
};
})(this);
export { connectTls, listenTls, startTls, TlsConn, TlsListener };

View file

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

View file

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

View file

@ -2,9 +2,10 @@
// deno-lint-ignore-file
"use strict";
((window) => {
const core = globalThis.Deno.core;
const ops = core.ops;
const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayIsArray,
ArrayPrototypeIncludes,
@ -37,10 +38,8 @@
RegExpPrototypeTest,
Error,
TypeError,
} = window.__bootstrap.primordials;
const core = window.Deno.core;
const ops = core.ops;
const { node } = window.__bootstrap.internals;
} = primordials;
const node = internals.node;
// Map used to store CJS parsing data.
const cjsParseCache = new SafeWeakMap();
@ -113,7 +112,7 @@
requestPath,
"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) {
return tryExtensions(
pathResolve(requestPath, "index"),
@ -316,7 +315,7 @@
return;
}
return core.ops.op_require_resolve_exports(
return ops.op_require_resolve_exports(
usesLocalNodeModulesDir,
modulesPath,
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,
);
const isRelative = ops.op_require_is_request_relative(
@ -417,16 +416,16 @@
Module._resolveLookupPaths = function (request, parent) {
const paths = [];
if (core.ops.op_require_is_request_relative(request) && parent?.filename) {
if (ops.op_require_is_request_relative(request) && parent?.filename) {
ArrayPrototypePush(
paths,
core.ops.op_require_path_dirname(parent.filename),
ops.op_require_path_dirname(parent.filename),
);
return paths;
}
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,
parent.filename,
);
@ -592,7 +591,7 @@
if (parent?.filename) {
if (request[0] === "#") {
const maybeResolved = core.ops.op_require_package_imports_resolve(
const maybeResolved = ops.op_require_package_imports_resolve(
parent.filename,
request,
);
@ -741,7 +740,7 @@
if (hasInspectBrk && !hasBrokenOnInspectBrk) {
hasBrokenOnInspectBrk = true;
core.ops.op_require_break_on_next_statement();
ops.op_require_break_on_next_statement();
}
const result = compiledWrapper.call(
@ -763,7 +762,7 @@
const content = ops.op_require_read_file(filename);
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") {
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}`,
);
}
const filename = core.ops.op_require_as_file_path(fileUrlStr);
const filename = ops.op_require_as_file_path(fileUrlStr);
return createRequireFromPath(filename);
}
@ -925,9 +924,7 @@
return ArrayPrototypeJoin(parts, "/");
}
window.__bootstrap.internals = {
...window.__bootstrap.internals ?? {},
require: {
internals.require = {
setUsesLocalNodeModulesDir() {
usesLocalNodeModulesDir = true;
},
@ -939,6 +936,4 @@
toRealPath,
cjsParseCache,
readPackageScope,
},
};
})(globalThis);

View file

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

View file

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

View file

@ -7,12 +7,10 @@
/// <reference path="./internal.d.ts" />
/// <reference path="./lib.deno_url.d.ts" />
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
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 {
ArrayPrototypeMap,
ObjectKeys,
@ -23,7 +21,7 @@
Symbol,
SymbolFor,
TypeError,
} = window.__bootstrap.primordials;
} = primordials;
const _components = Symbol("components");
@ -268,7 +266,4 @@
return webidl.converters.USVString(V, opts);
};
window.__bootstrap.urlPattern = {
URLPattern,
};
})(globalThis);
export { URLPattern };

View file

@ -12,9 +12,11 @@ fn setup() -> Vec<Extension> {
deno_webidl::init(),
deno_url::init(),
Extension::builder("bench_setup")
.js(vec![(
"setup",
"const { URL } = globalThis.__bootstrap.url;",
.esm(vec![(
"internal:setup",
r#"import { URL } from "internal:ext/url/00_url.js";
globalThis.URL = URL;
"#,
)])
.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.
// deno-lint-ignore-file no-var
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
declare namespace globalThis {
declare namespace __bootstrap {
declare var url: {
URL: typeof URL;
URLSearchParams: typeof URLSearchParams;
parseUrlEncoded(bytes: Uint8Array): [string, string][];
};
declare module "internal:ext/url/00_url.js" {
const URL: typeof URL;
const URLSearchParams: typeof URLSearchParams;
function parseUrlEncoded(bytes: Uint8Array): [string, string][];
}
declare var urlPattern: {
URLPattern: typeof URLPattern;
};
}
declare module "internal:ext/url/01_urlpattern.js" {
const URLPattern: typeof URLPattern;
}

View file

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

View file

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

View file

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

View file

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

View file

@ -4,14 +4,13 @@
// 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
// and impossible logic branches based on what Deno currently supports.
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
const ops = core.ops;
const webidl = window.__bootstrap.webidl;
const { DOMException } = window.__bootstrap.domException;
const consoleInternal = window.__bootstrap.console;
import * as webidl from "internal:ext/webidl/00_webidl.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
import { createFilteredInspectProxy } from "internal:ext/console/02_console.js";
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayPrototypeFilter,
ArrayPrototypeIncludes,
@ -40,7 +39,15 @@
SymbolFor,
SymbolToStringTag,
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
@ -198,7 +205,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(Event.prototype, this),
keys: EVENT_PROPS,
@ -947,7 +954,7 @@
callback,
options,
) {
const self = this ?? globalThis;
const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype);
const prefix = "Failed to execute 'addEventListener' on 'EventTarget'";
@ -1005,7 +1012,7 @@
callback,
options,
) {
const self = this ?? globalThis;
const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype);
webidl.requiredArguments(arguments.length, 2, {
prefix: "Failed to execute 'removeEventListener' on 'EventTarget'",
@ -1043,7 +1050,7 @@
// `globalThis` directly here, because it could be deleted by user.
// Instead use saved reference to global scope when the script was
// executed.
const self = this ?? window;
const self = this ?? globalThis_;
webidl.assertBranded(self, EventTargetPrototype);
webidl.requiredArguments(arguments.length, 1, {
prefix: "Failed to execute 'dispatchEvent' on 'EventTarget'",
@ -1130,7 +1137,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(ErrorEvent.prototype, this),
keys: [
@ -1191,7 +1198,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(CloseEvent.prototype, this),
keys: [
@ -1224,7 +1231,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(MessageEvent.prototype, this),
keys: [
@ -1257,7 +1264,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(CustomEvent.prototype, this),
keys: [
@ -1287,7 +1294,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(ProgressEvent.prototype, this),
keys: [
@ -1335,7 +1342,7 @@
}
[SymbolFor("Deno.privateCustomInspect")](inspect) {
return inspect(consoleInternal.createFilteredInspectProxy({
return inspect(createFilteredInspectProxy({
object: this,
evaluate: ObjectPrototypeIsPrototypeOf(
PromiseRejectionEvent.prototype,
@ -1480,14 +1487,14 @@
error,
});
// 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);
}
reportExceptionStackedCalls--;
}
function checkThis(thisArg) {
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis) {
if (thisArg !== null && thisArg !== undefined && thisArg !== globalThis_) {
throw new TypeError("Illegal invocation");
}
}
@ -1500,24 +1507,22 @@
reportException(error);
}
window.__bootstrap.eventTarget = {
EventTarget,
setEventTargetData,
listenerCount,
};
window.__bootstrap.event = {
reportException,
setIsTrusted,
setTarget,
defineEventHandler,
export {
_skipInternalInit,
Event,
ErrorEvent,
CloseEvent,
MessageEvent,
CustomEvent,
defineEventHandler,
ErrorEvent,
Event,
EventTarget,
listenerCount,
MessageEvent,
ProgressEvent,
PromiseRejectionEvent,
reportError,
reportException,
saveGlobalThisReference,
setEventTargetData,
setIsTrusted,
setTarget,
};
})(this);

View file

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

View file

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

View file

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

View file

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

View file

@ -6,17 +6,15 @@
/// <reference path="../web/internal.d.ts" />
/// <reference lib="esnext" />
"use strict";
((window) => {
const core = Deno.core;
const core = globalThis.Deno.core;
const ops = core.ops;
const webidl = window.__bootstrap.webidl;
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 primordials = globalThis.__bootstrap.primordials;
const {
ObjectPrototypeIsPrototypeOf,
TypeErrorPrototype,
} = window.__bootstrap.primordials;
} = primordials;
/**
* @param {string} data
@ -66,8 +64,4 @@
}
}
window.__bootstrap.base64 = {
atob,
btoa,
};
})(globalThis);
export { atob, btoa };

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,11 +1,10 @@
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
"use strict";
/// <reference path="../../core/internal.d.ts" />
((window) => {
const { URL } = window.__bootstrap.url;
const { DOMException } = window.__bootstrap.domException;
import { URL } from "internal:ext/url/00_url.js";
import DOMException from "internal:ext/web/01_dom_exception.js";
const primordials = globalThis.__bootstrap.primordials;
const {
Error,
ObjectDefineProperties,
@ -16,7 +15,7 @@
WeakMap,
WeakMapPrototypeGet,
WeakMapPrototypeSet,
} = window.__bootstrap.primordials;
} = primordials;
const locationConstructorKey = Symbol("locationConstuctorKey");
@ -363,18 +362,23 @@
workerLocation = new WorkerLocation(href, locationConstructorKey);
}
window.__bootstrap.location = {
locationConstructorDescriptor: {
function getLocationHref() {
return location?.href;
}
const locationConstructorDescriptor = {
value: Location,
configurable: true,
writable: true,
},
workerLocationConstructorDescriptor: {
};
const workerLocationConstructorDescriptor = {
value: WorkerLocation,
configurable: true,
writable: true,
},
locationDescriptor: {
};
const locationDescriptor = {
get() {
return location;
},
@ -382,8 +386,8 @@
throw new DOMException(`Cannot set "location".`, "NotSupportedError");
},
enumerable: true,
},
workerLocationDescriptor: {
};
const workerLocationDescriptor = {
get() {
if (workerLocation == null) {
throw new Error(
@ -394,10 +398,13 @@
},
configurable: 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="./lib.deno_web.d.ts" />
"use strict";
((window) => {
const core = window.Deno.core;
const core = globalThis.Deno.core;
const { InterruptedPrototype, ops } = core;
const webidl = window.__bootstrap.webidl;
const { EventTarget, setEventTargetData } = window.__bootstrap.eventTarget;
const { MessageEvent, defineEventHandler } = window.__bootstrap.event;
const { DOMException } = window.__bootstrap.domException;
import * as webidl from "internal:ext/webidl/00_webidl.js";
import {
defineEventHandler,
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 {
ArrayBufferPrototype,
ArrayPrototypeFilter,
@ -26,7 +28,7 @@
SymbolFor,
SymbolIterator,
TypeError,
} = window.__bootstrap.primordials;
} = primordials;
class MessageChannel {
/** @type {MessagePort} */
@ -194,7 +196,7 @@
}
/**
* @param {globalThis.__bootstrap.messagePort.MessageData} messageData
* @param {messagePort.MessageData} messageData
* @returns {[any, object[]]}
*/
function deserializeJsMessageData(messageData) {
@ -240,14 +242,14 @@
/**
* @param {any} data
* @param {object[]} transferables
* @returns {globalThis.__bootstrap.messagePort.MessageData}
* @returns {messagePort.MessageData}
*/
function serializeJsMessageData(data, transferables) {
const transferredArrayBuffers = [];
for (let i = 0, j = 0; i < transferables.length; i++) {
const ab = transferables[i];
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(
`ArrayBuffer at index ${j} is already detached`,
"DataCloneError",
@ -268,7 +270,7 @@
throw new DOMException(err, "DataCloneError");
});
/** @type {globalThis.__bootstrap.messagePort.Transferable[]} */
/** @type {messagePort.Transferable[]} */
const serializedTransferables = [];
let arrayBufferI = 0;
@ -332,12 +334,11 @@
return deserializeJsMessageData(messageData)[0];
}
window.__bootstrap.messagePort = {
export {
deserializeJsMessageData,
MessageChannel,
MessagePort,
MessagePortPrototype,
deserializeJsMessageData,
serializeJsMessageData,
structuredClone,
};
})(globalThis);

View file

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

View file

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

View file

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

View file

@ -28,9 +28,10 @@ fn setup() -> Vec<Extension> {
deno_console::init(),
deno_web::init::<Permissions>(BlobStore::default(), None),
Extension::builder("bench_setup")
.js(vec![
("setup", r#"
const { setTimeout, handleTimerMacrotask } = globalThis.__bootstrap.timers;
.esm(vec![
("internal:setup", r#"
import { setTimeout, handleTimerMacrotask } from "internal:ext/web/02_timers.js";
globalThis.setTimeout = setTimeout;
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.
// deno-lint-ignore-file no-var
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
declare namespace globalThis {
declare namespace __bootstrap {
declare var infra: {
collectSequenceOfCodepoints(
declare module "internal:ext/web/00_infra.js" {
function collectSequenceOfCodepoints(
input: string,
position: number,
condition: (char: string) => boolean,
@ -16,26 +12,26 @@ declare namespace globalThis {
result: string;
position: number;
};
ASCII_DIGIT: string[];
ASCII_UPPER_ALPHA: string[];
ASCII_LOWER_ALPHA: string[];
ASCII_ALPHA: string[];
ASCII_ALPHANUMERIC: string[];
HTTP_TAB_OR_SPACE: string[];
HTTP_WHITESPACE: string[];
HTTP_TOKEN_CODE_POINT: string[];
HTTP_TOKEN_CODE_POINT_RE: RegExp;
HTTP_QUOTED_STRING_TOKEN_POINT: string[];
HTTP_QUOTED_STRING_TOKEN_POINT_RE: RegExp;
HTTP_TAB_OR_SPACE_PREFIX_RE: RegExp;
HTTP_TAB_OR_SPACE_SUFFIX_RE: RegExp;
HTTP_WHITESPACE_PREFIX_RE: RegExp;
HTTP_WHITESPACE_SUFFIX_RE: RegExp;
httpTrim(s: string): string;
regexMatcher(chars: string[]): string;
byteUpperCase(s: string): string;
byteLowerCase(s: string): string;
collectHttpQuotedString(
const ASCII_DIGIT: string[];
const ASCII_UPPER_ALPHA: string[];
const ASCII_LOWER_ALPHA: string[];
const ASCII_ALPHA: string[];
const ASCII_ALPHANUMERIC: string[];
const HTTP_TAB_OR_SPACE: string[];
const HTTP_WHITESPACE: string[];
const HTTP_TOKEN_CODE_POINT: string[];
const HTTP_TOKEN_CODE_POINT_RE: RegExp;
const HTTP_QUOTED_STRING_TOKEN_POINT: string[];
const HTTP_QUOTED_STRING_TOKEN_POINT_RE: RegExp;
const HTTP_TAB_OR_SPACE_PREFIX_RE: RegExp;
const HTTP_TAB_OR_SPACE_SUFFIX_RE: RegExp;
const HTTP_WHITESPACE_PREFIX_RE: RegExp;
const HTTP_WHITESPACE_SUFFIX_RE: RegExp;
function httpTrim(s: string): string;
function regexMatcher(chars: string[]): string;
function byteUpperCase(s: string): string;
function byteLowerCase(s: string): string;
function collectHttpQuotedString(
input: string,
position: number,
extractValue: boolean,
@ -43,78 +39,73 @@ declare namespace globalThis {
result: string;
position: number;
};
forgivingBase64Encode(data: Uint8Array): string;
forgivingBase64Decode(data: string): Uint8Array;
serializeJSValueToJSONString(value: unknown): string;
};
function forgivingBase64Encode(data: Uint8Array): string;
function forgivingBase64Decode(data: string): Uint8Array;
function serializeJSValueToJSONString(value: unknown): string;
}
declare var domException: {
DOMException: typeof DOMException;
};
declare module "internal:ext/web/01_dom_exception.js" {
export = DOMException;
}
declare namespace mimesniff {
declare interface MimeType {
declare module "internal:ext/web/01_mimesniff.js" {
interface MimeType {
type: string;
subtype: string;
parameters: Map<string, string>;
}
declare function parseMimeType(input: string): MimeType | null;
declare function essence(mimeType: MimeType): string;
declare function serializeMimeType(mimeType: MimeType): string;
declare function extractMimeType(
function parseMimeType(input: string): MimeType | null;
function essence(mimeType: MimeType): string;
function serializeMimeType(mimeType: MimeType): string;
function extractMimeType(
headerValues: string[] | null,
): MimeType | null;
}
declare var eventTarget: {
EventTarget: typeof EventTarget;
};
declare module "internal:ext/web/02_event.js" {
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: {
Event: typeof event;
ErrorEvent: typeof ErrorEvent;
CloseEvent: typeof CloseEvent;
MessageEvent: typeof MessageEvent;
CustomEvent: typeof CustomEvent;
ProgressEvent: typeof ProgressEvent;
PromiseRejectionEvent: typeof PromiseRejectionEvent;
reportError: typeof reportError;
};
declare module "internal:ext/web/12_location.js" {
function getLocationHref(): string | undefined;
}
declare var location: {
getLocationHref(): string | undefined;
};
declare module "internal:ext/web/05_base64.js" {
function atob(data: string): string;
function btoa(data: string): string;
}
declare var base64: {
atob(data: string): string;
btoa(data: string): string;
};
declare module "internal:ext/web/09_file.js" {
function blobFromObjectUrl(url: string): Blob | null;
function getParts(blob: Blob): string[];
const Blob: typeof Blob;
const File: typeof File;
}
declare var file: {
blobFromObjectUrl(url: string): Blob | null;
getParts(blob: Blob): string[];
Blob: typeof Blob;
File: typeof File;
};
declare module "internal:ext/web/06_streams.js" {
const ReadableStream: typeof ReadableStream;
function isReadableStreamDisturbed(stream: ReadableStream): boolean;
function createProxy<T>(stream: ReadableStream<T>): ReadableStream<T>;
}
declare var streams: {
ReadableStream: typeof ReadableStream;
isReadableStreamDisturbed(stream: ReadableStream): boolean;
createProxy<T>(stream: ReadableStream<T>): ReadableStream<T>;
};
declare namespace messagePort {
declare type Transferable = {
declare module "internal:ext/web/13_message_port.js" {
type Transferable = {
kind: "messagePort";
data: number;
} | {
kind: "arrayBuffer";
data: number;
};
declare interface MessageData {
interface MessageData {
data: Uint8Array;
transferables: Transferable[];
}
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,7 +5,6 @@ use std::env;
use std::path::PathBuf;
// This is a shim that allows to generate documentation on docs.rs
#[cfg(not(feature = "docsrs"))]
mod not_docs {
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![
deno_webidl::init(),
deno_console::init(),
@ -158,7 +157,8 @@ mod not_docs {
startup_snapshot: None,
extensions: vec![],
extensions_with_js,
additional_files: files,
additional_files: vec![],
additional_esm_files: esm_files,
compression_cb: Some(Box::new(|vec, snapshot_slice| {
lzzzz::lz4_hc::compress_to_vec(
snapshot_slice,
@ -172,14 +172,19 @@ mod not_docs {
pub fn build_snapshot(runtime_snapshot_path: PathBuf) {
#[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"))]
{
let manifest = env!("CARGO_MANIFEST_DIR");
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.
"use strict";
((window) => {
const { ObjectFreeze, StringPrototypeSplit } = window.__bootstrap.primordials;
const primordials = globalThis.__bootstrap.primordials;
const { ObjectFreeze, StringPrototypeSplit } = primordials;
const build = {
target: "unknown",
@ -26,8 +25,4 @@
ObjectFreeze(build);
}
window.__bootstrap.build = {
build,
setBuildInfo,
};
})(this);
export { build, setBuildInfo };

View file

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

View file

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

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.
"use strict";
((window) => {
const internals = globalThis.__bootstrap.internals;
const primordials = globalThis.__bootstrap.primordials;
const {
decodeURIComponent,
ObjectPrototypeIsPrototypeOf,
@ -9,9 +9,9 @@
SafeArrayIterator,
StringPrototypeReplace,
TypeError,
} = window.__bootstrap.primordials;
const { build } = window.__bootstrap.build;
const { URLPrototype } = window.__bootstrap.url;
} = primordials;
import { build } from "internal:runtime/js/01_build.js";
import { URLPrototype } from "internal:ext/url/00_url.js";
let logDebug = false;
let logSource = "JS";
@ -96,10 +96,8 @@
return pathOrUrl;
}
window.__bootstrap.internals = {
...window.__bootstrap.internals ?? {},
pathFromURL,
};
// TODO(bartlomieju): remove
internals.pathFromURL = pathFromURL;
function writable(value) {
return {
@ -137,14 +135,13 @@
};
}
window.__bootstrap.util = {
log,
setLogDebug,
export {
createResolvable,
pathFromURL,
writable,
nonEnumerable,
readOnly,
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.
"use strict";
((window) => {
const { ops } = Deno.core;
const { Event } = window.__bootstrap.event;
const { EventTarget } = window.__bootstrap.eventTarget;
const { pathFromURL } = window.__bootstrap.util;
const { illegalConstructorKey } = window.__bootstrap.webUtil;
const core = globalThis.Deno.core;
const ops = core.ops;
import { Event, EventTarget } from "internal:ext/web/02_event.js";
import { pathFromURL } from "internal:runtime/js/06_util.js";
const primordials = globalThis.__bootstrap.primordials;
const {
ArrayIsArray,
ArrayPrototypeIncludes,
@ -21,9 +19,12 @@
PromiseReject,
ReflectHas,
SafeArrayIterator,
Symbol,
SymbolFor,
TypeError,
} = window.__bootstrap.primordials;
} = primordials;
const illegalConstructorKey = Symbol("illegalConstructorKey");
/**
* @typedef StatusCacheValue
@ -278,10 +279,4 @@
return permissions;
}
window.__bootstrap.permissions = {
serializePermissions,
permissions,
Permissions,
PermissionStatus,
};
})(this);
export { Permissions, permissions, PermissionStatus, serializePermissions };

View file

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

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