Skip to content

Commit

Permalink
fix import's source
Browse files Browse the repository at this point in the history
  • Loading branch information
ofzo committed Feb 19, 2024
1 parent 5d2698a commit 2e06f7c
Show file tree
Hide file tree
Showing 11 changed files with 1,068 additions and 762 deletions.
Binary file removed .DS_Store
Binary file not shown.
1,634 changes: 959 additions & 675 deletions Cargo.lock

Large diffs are not rendered by default.

48 changes: 24 additions & 24 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,30 @@ version = "0.1.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
chrono = "0.4.23"
colored = "2.0.0"
console-subscriber = "0.1.8"
env_logger = "0.10"
futures = "0.3.6"
log = "0.4.17"
queues = "1.0.2"
quote = "1.0"
regex = "1"
relative-path = "1.8.0"
reqwest = { version = "0.11.14", features = ["blocking"] }
serde_json = "1.0.99"
serde_v8 = "0.126.0"
swc = "0.266.20"
swc_common = { version = "0.32.1", features = ["tty-emitter"] }
swc_ecma_ast = "0.109.1"
swc_ecma_parser = "0.140.0"
swc_ecma_visit = "0.95.1"
swc_ecma_transforms_module = "0.176.14"
url = "2.3.1"
v8 = "0.78.0"
anyhow = "1.0.71"
tracing = "0.1.37"
chrono = "0.4.31"
colored = "2.1.0"
console-subscriber = "0.2.0"
env_logger = "0.10.1"
futures = "0.3.30"
log = "0.4.20"
queues = "1.1.0"
quote = "1.0.35"
regex = "1.10.2"
relative-path = "1.9.2"
reqwest = { version = "0.11.23", features = ["blocking"] }
serde_json = "1.0.111"
serde_v8 = "0.154.0"
swc = "0.270.20"
swc_common = { version = "0.33.12", features = ["tty-emitter"] }
swc_ecma_ast = "0.110.17"
swc_ecma_parser = "0.141.37"
swc_ecma_visit = "0.96.17"
swc_ecma_transforms_module = "0.178.16"
url = "2.5.0"
v8 = "0.82.0"
anyhow = "1.0.79"
tracing = "0.1.40"

[dependencies.tokio]
features = ["full"]
version = "1.19.2"
version = "1.35.1"
37 changes: 18 additions & 19 deletions bootstrap/main.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
declare var globalThis;

interface RuntimeData {
asyncHandle: Record<number, (() => void)>,
count: number
asyncHandle: Record<number, () => void>
count: number
}

var runtimeData: RuntimeData = {
asyncHandle: [],
count: 0
asyncHandle: [],
count: 0,
}

export default async function bootstrap(entry: string) {
globalThis.setTimeout = (fn: Function, delay: number, ...arg: any[]) => {
runtimeData.asyncHandle[runtimeData.count] = () => {
fn(...arg);
}
this.timer.send(runtimeData.count, delay)
runtimeData.count++
//@ts-ignore
globalThis.setTimeout = (fn: Function, delay: number, ...arg: any[]) => {
runtimeData.asyncHandle[runtimeData.count] = () => {
fn(...arg)
}
globalThis.exec = (id: number) => {
if (runtimeData.asyncHandle[id]) {
let fn = runtimeData.asyncHandle[id]
delete runtimeData.asyncHandle[id]
fn();
}
this.timer.send(runtimeData.count, delay)
runtimeData.count++
}
globalThis.exec = (id: number) => {
if (runtimeData.asyncHandle[id]) {
let fn = runtimeData.asyncHandle[id]
delete runtimeData.asyncHandle[id]
fn()
}
}

await import(entry)
await import(entry)
}
7 changes: 1 addition & 6 deletions src/graph.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
use crate::compile::{compile, ModuleDependency};
use anyhow::anyhow;
use chrono::Local;
use colored::Colorize;
use queues::*;
use regex::Regex;
use relative_path::RelativePath;
use reqwest::{self};
use std::{
collections::HashMap,
fs,
io::{Error, ErrorKind},
};
use std::{collections::HashMap, fs};
use url::Url;

pub fn resolve(filename: &str, base: &String) -> String {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ use runtime::Runtime;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
let args: Vec<String> = env::args().collect();
let args = env::args().collect::<Vec<_>>();
if args.len() <= 1 {
panic!("no args");
}

let current_dir = env::current_dir()?.to_string_lossy().to_string();
let entry = &args[1];

println!("");
// println!("");
Runtime::from(DependencyGraph::from(entry, &current_dir).await?)
.run(&resolve(entry, &current_dir))
.await
Expand Down
28 changes: 17 additions & 11 deletions src/runner/console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ pub fn console_format(
name
};
let tag = if v.is_async_function() {
"AsyncFunction"
"async function"
} else if v.is_generator_function() {
"GeneratorFunction"
"function*"
} else {
"Function"
"function"
};
return format!("{}", format!("[ {tag} <{name}> ]").yellow());
return format!("{}", format!(" {tag} {name}() ").italic().yellow());
}
if v.is_promise() {
let promise = v8::Local::<v8::Promise>::try_from(*v).unwrap();
Expand Down Expand Up @@ -96,12 +96,15 @@ pub fn console_format(
)
})
.collect::<Vec<_>>();
fmt.push(format!(
"{}{}: {{}}",
" ".repeat(level + 1).to_string(),
"[[prototype]]".color("gray"),
// console_format(scope, &prototype, level + 1)
));
// fmt.push(format!(
// "{}{}: {{}}",
// " ".repeat(level + 1).to_string(),
// "[[prototype]]".color("gray"),
// // console_format(scope, &prototype, level + 1)
// ));
if fmt.len() == 0 {
return format!("{{}}");
}
return format!(
"{{\n{}\n{}}}",
fmt.join(",\n"),
Expand All @@ -125,5 +128,8 @@ pub fn console_log(
.collect::<Vec<_>>()
.join(" ");

println!("{result}");
println!(
"{} {result}",
format!("{}", Utc::now().format("%Y-%m-%d %H:%M:%S%.3f")).color("gray")
);
}
3 changes: 3 additions & 0 deletions src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ pub struct RuntimeState {
pub sender: Sender<usize>,
pub receiver: Receiver<usize>,
}
/**
# Ts Runtime
*/
pub struct Runtime {
pub isolate: v8::OwnedIsolate,
pub sender: Sender<usize>,
Expand Down
29 changes: 18 additions & 11 deletions src/runtime/static_fn.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
use std::{task::Poll, time::Duration};

use super::{asynchronous::AsynchronousKind, Runtime};
use crate::{graph::resolve, runner::console::console_format};
use std::{task::Poll, time::Duration};
use url::Url;

impl Runtime {
pub fn resolve<'s>(
context: v8::Local<'s, v8::Context>,
specifier: v8::Local<'s, v8::String>,
source: v8::Local<'s, v8::String>,
_import_assertions: v8::Local<'s, v8::FixedArray>,
referrer: v8::Local<'s, v8::Module>,
) -> Option<v8::Local<'s, v8::Module>> {
Expand All @@ -16,18 +15,26 @@ impl Runtime {
let graph_rc = Self::graph(scope);

let state = graph_rc.borrow();
let module_id = referrer.get_identity_hash();

let hash = state.hash.borrow();
let url = hash.get(&module_id).unwrap();
let source = source.to_rust_string_lossy(scope);

let url = if source.starts_with("http") {
let url = Url::parse(&source).expect(format!("parse url failed: {}", source).as_str());
let url = url.join(&source).unwrap();
let url = url.as_str().to_string();
url
} else {
let module_id = referrer.get_identity_hash();

let specifier = specifier.to_rust_string_lossy(scope);
let url = Url::parse(url).unwrap();
let url = url.join(&specifier).unwrap();
let url = url.as_str().to_string();
let hash = state.hash.borrow();
let url = hash.get(&module_id).unwrap();
url.clone()
};

let module = state.module.borrow();
let info = module.get(&url).unwrap();
let info = module
.get(&url)
.expect(format!("get module failure: {}", url).as_str());
let module = v8::Local::new(scope, &info.module);

return Some(module);
Expand Down
13 changes: 9 additions & 4 deletions test/test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import "https://deno.land/[email protected]/examples/welcome.ts";
import "https://deno.land/[email protected]/examples/welcome.ts";

const res = await import("./test1.ts");
console.log("res", res);
console.log("res", res);
const text = res.json()
console.log("🚀 text", text);
test.copy()
try {
const text = await res.json();
console.log("🚀 text", text);
test.copy();
} catch (err) {
console.error("err => ", err);
}
27 changes: 17 additions & 10 deletions test/test1.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
setTimeout(
(...arg: number[]) => {
console.log("Hello Timeout", ...arg);
},
1000,
1,
2,
3,
);
console.log("Welcome Timeout!");
setTimeout((...arg: number[]) => {
console.log("Hello Timeout", ...arg)
}, 1000, 1, 2, 3);
console.log("Welcome Timeout!")
setTimeout((...arg: number[]) => {
console.log("Timeout 2", ...arg)
console.log("Timeout 2", ...arg, /^bin$/g);
}, 100);


export default {
copy() {
console.log("1121")
}
}
copy() {
console.log("1121");
},
};

export function* x() {}

0 comments on commit 2e06f7c

Please sign in to comment.