2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2021-12-17 20:18:17 -05:00
|
|
|
|
|
|
|
use crate::colors;
|
|
|
|
use crate::lsp::ReplLanguageServer;
|
2022-12-13 07:53:32 -05:00
|
|
|
use crate::npm::NpmPackageReference;
|
|
|
|
use crate::ProcState;
|
|
|
|
use deno_ast::swc::ast as swc_ast;
|
|
|
|
use deno_ast::swc::visit::noop_visit_type;
|
|
|
|
use deno_ast::swc::visit::Visit;
|
|
|
|
use deno_ast::swc::visit::VisitWith;
|
2022-01-13 11:58:00 -05:00
|
|
|
use deno_ast::DiagnosticsError;
|
|
|
|
use deno_ast::ImportsNotUsedAsValues;
|
2022-12-13 07:53:32 -05:00
|
|
|
use deno_ast::ModuleSpecifier;
|
2021-12-17 20:18:17 -05:00
|
|
|
use deno_core::error::AnyError;
|
2022-12-16 14:12:06 -05:00
|
|
|
use deno_core::futures::channel::mpsc::UnboundedReceiver;
|
2021-12-17 20:18:17 -05:00
|
|
|
use deno_core::futures::FutureExt;
|
2022-12-16 14:12:06 -05:00
|
|
|
use deno_core::futures::StreamExt;
|
2022-02-07 11:05:49 -05:00
|
|
|
use deno_core::serde_json;
|
2021-12-17 20:18:17 -05:00
|
|
|
use deno_core::serde_json::Value;
|
|
|
|
use deno_core::LocalInspectorSession;
|
2022-12-13 07:53:32 -05:00
|
|
|
use deno_graph::source::Resolver;
|
2021-12-17 20:18:17 -05:00
|
|
|
use deno_runtime::worker::MainWorker;
|
|
|
|
|
2022-11-25 18:38:08 -05:00
|
|
|
use super::cdp;
|
|
|
|
|
2021-12-17 20:18:17 -05:00
|
|
|
static PRELUDE: &str = r#"
|
|
|
|
Object.defineProperty(globalThis, "_", {
|
|
|
|
configurable: true,
|
|
|
|
get: () => Deno[Deno.internal].lastEvalResult,
|
|
|
|
set: (value) => {
|
|
|
|
Object.defineProperty(globalThis, "_", {
|
|
|
|
value: value,
|
|
|
|
writable: true,
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
});
|
|
|
|
console.log("Last evaluation result is no longer saved to _.");
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
Object.defineProperty(globalThis, "_error", {
|
|
|
|
configurable: true,
|
|
|
|
get: () => Deno[Deno.internal].lastThrownError,
|
|
|
|
set: (value) => {
|
|
|
|
Object.defineProperty(globalThis, "_error", {
|
|
|
|
value: value,
|
|
|
|
writable: true,
|
|
|
|
enumerable: true,
|
|
|
|
configurable: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
console.log("Last thrown error is no longer saved to _error.");
|
|
|
|
},
|
|
|
|
});
|
2022-04-20 15:48:15 -04:00
|
|
|
|
|
|
|
globalThis.clear = console.clear.bind(console);
|
2021-12-17 20:18:17 -05:00
|
|
|
"#;
|
|
|
|
|
|
|
|
pub enum EvaluationOutput {
|
|
|
|
Value(String),
|
|
|
|
Error(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl std::fmt::Display for EvaluationOutput {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
EvaluationOutput::Value(value) => f.write_str(value),
|
|
|
|
EvaluationOutput::Error(value) => f.write_str(value),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-16 11:11:10 -05:00
|
|
|
pub fn result_to_evaluation_output(
|
|
|
|
r: Result<EvaluationOutput, AnyError>,
|
|
|
|
) -> EvaluationOutput {
|
|
|
|
match r {
|
|
|
|
Ok(value) => value,
|
|
|
|
Err(err) => {
|
|
|
|
EvaluationOutput::Error(format!("{} {}", colors::red("error:"), err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-17 20:18:17 -05:00
|
|
|
struct TsEvaluateResponse {
|
|
|
|
ts_code: String,
|
2022-02-07 11:05:49 -05:00
|
|
|
value: cdp::EvaluateResponse,
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ReplSession {
|
2022-12-13 07:53:32 -05:00
|
|
|
proc_state: ProcState,
|
2021-12-17 20:18:17 -05:00
|
|
|
pub worker: MainWorker,
|
|
|
|
session: LocalInspectorSession,
|
|
|
|
pub context_id: u64,
|
|
|
|
pub language_server: ReplLanguageServer,
|
2022-12-13 07:53:32 -05:00
|
|
|
has_initialized_node_runtime: bool,
|
|
|
|
referrer: ModuleSpecifier,
|
2022-12-16 14:12:06 -05:00
|
|
|
// FIXME(bartlomieju): this field should be used to listen
|
|
|
|
// for "exceptionThrown" notifications
|
|
|
|
#[allow(dead_code)]
|
|
|
|
notification_rx: UnboundedReceiver<Value>,
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ReplSession {
|
2022-12-13 07:53:32 -05:00
|
|
|
pub async fn initialize(
|
|
|
|
proc_state: ProcState,
|
|
|
|
mut worker: MainWorker,
|
|
|
|
) -> Result<Self, AnyError> {
|
2021-12-17 20:18:17 -05:00
|
|
|
let language_server = ReplLanguageServer::new_initialized().await?;
|
|
|
|
let mut session = worker.create_inspector_session().await;
|
|
|
|
|
|
|
|
worker
|
|
|
|
.with_event_loop(
|
2022-02-07 11:05:49 -05:00
|
|
|
session
|
|
|
|
.post_message::<()>("Runtime.enable", None)
|
|
|
|
.boxed_local(),
|
2021-12-17 20:18:17 -05:00
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
// Enabling the runtime domain will always send trigger one executionContextCreated for each
|
|
|
|
// context the inspector knows about so we grab the execution context from that since
|
|
|
|
// our inspector does not support a default context (0 is an invalid context id).
|
2022-12-16 14:12:06 -05:00
|
|
|
let context_id: u64;
|
|
|
|
let mut notification_rx = session.take_notification_rx();
|
|
|
|
|
|
|
|
loop {
|
|
|
|
let notification = notification_rx.next().await.unwrap();
|
2021-12-17 20:18:17 -05:00
|
|
|
let method = notification.get("method").unwrap().as_str().unwrap();
|
|
|
|
let params = notification.get("params").unwrap();
|
|
|
|
if method == "Runtime.executionContextCreated" {
|
2022-11-26 17:09:48 -05:00
|
|
|
let context = params.get("context").unwrap();
|
|
|
|
assert!(context
|
|
|
|
.get("auxData")
|
2021-12-17 20:18:17 -05:00
|
|
|
.unwrap()
|
2022-11-26 17:09:48 -05:00
|
|
|
.get("isDefault")
|
2021-12-17 20:18:17 -05:00
|
|
|
.unwrap()
|
2022-11-26 17:09:48 -05:00
|
|
|
.as_bool()
|
|
|
|
.unwrap());
|
|
|
|
context_id = context.get("id").unwrap().as_u64().unwrap();
|
2022-12-16 14:12:06 -05:00
|
|
|
break;
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
}
|
2022-11-26 17:09:48 -05:00
|
|
|
assert_ne!(context_id, 0);
|
2021-12-17 20:18:17 -05:00
|
|
|
|
2022-12-13 07:53:32 -05:00
|
|
|
let referrer = deno_core::resolve_url_or_path("./$deno$repl.ts").unwrap();
|
|
|
|
|
2021-12-17 20:18:17 -05:00
|
|
|
let mut repl_session = ReplSession {
|
2022-12-13 07:53:32 -05:00
|
|
|
proc_state,
|
2021-12-17 20:18:17 -05:00
|
|
|
worker,
|
|
|
|
session,
|
|
|
|
context_id,
|
|
|
|
language_server,
|
2022-12-13 07:53:32 -05:00
|
|
|
has_initialized_node_runtime: false,
|
|
|
|
referrer,
|
2022-12-16 14:12:06 -05:00
|
|
|
notification_rx,
|
2021-12-17 20:18:17 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
// inject prelude
|
|
|
|
repl_session.evaluate_expression(PRELUDE).await?;
|
|
|
|
|
|
|
|
Ok(repl_session)
|
|
|
|
}
|
|
|
|
|
2022-05-12 19:12:55 -04:00
|
|
|
pub async fn closing(&mut self) -> Result<bool, AnyError> {
|
2021-12-17 20:18:17 -05:00
|
|
|
let closed = self
|
|
|
|
.evaluate_expression("(this.closed)")
|
|
|
|
.await?
|
2022-02-07 11:05:49 -05:00
|
|
|
.result
|
|
|
|
.value
|
2021-12-17 20:18:17 -05:00
|
|
|
.unwrap()
|
|
|
|
.as_bool()
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
Ok(closed)
|
|
|
|
}
|
|
|
|
|
2022-02-07 11:05:49 -05:00
|
|
|
pub async fn post_message_with_event_loop<T: serde::Serialize>(
|
2021-12-17 20:18:17 -05:00
|
|
|
&mut self,
|
|
|
|
method: &str,
|
2022-02-07 11:05:49 -05:00
|
|
|
params: Option<T>,
|
2021-12-17 20:18:17 -05:00
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
self
|
|
|
|
.worker
|
|
|
|
.with_event_loop(self.session.post_message(method, params).boxed_local())
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn run_event_loop(&mut self) -> Result<(), AnyError> {
|
|
|
|
self.worker.run_event_loop(true).await
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn evaluate_line_and_get_output(
|
|
|
|
&mut self,
|
|
|
|
line: &str,
|
2022-12-16 11:11:10 -05:00
|
|
|
) -> EvaluationOutput {
|
2021-12-17 20:18:17 -05:00
|
|
|
fn format_diagnostic(diagnostic: &deno_ast::Diagnostic) -> String {
|
2023-01-04 18:54:54 -05:00
|
|
|
let display_position = diagnostic.display_position();
|
2021-12-17 20:18:17 -05:00
|
|
|
format!(
|
|
|
|
"{}: {} at {}:{}",
|
|
|
|
colors::red("parse error"),
|
|
|
|
diagnostic.message(),
|
2023-01-04 18:54:54 -05:00
|
|
|
display_position.line_number,
|
|
|
|
display_position.column_number,
|
2021-12-17 20:18:17 -05:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-12-16 11:11:10 -05:00
|
|
|
async fn inner(
|
|
|
|
session: &mut ReplSession,
|
|
|
|
line: &str,
|
|
|
|
) -> Result<EvaluationOutput, AnyError> {
|
|
|
|
match session.evaluate_line_with_object_wrapping(line).await {
|
|
|
|
Ok(evaluate_response) => {
|
|
|
|
let cdp::EvaluateResponse {
|
|
|
|
result,
|
|
|
|
exception_details,
|
|
|
|
} = evaluate_response.value;
|
|
|
|
|
|
|
|
Ok(if let Some(exception_details) = exception_details {
|
|
|
|
session.set_last_thrown_error(&result).await?;
|
|
|
|
let description = match exception_details.exception {
|
|
|
|
Some(exception) => exception
|
|
|
|
.description
|
|
|
|
.unwrap_or_else(|| "Unknown exception".to_string()),
|
|
|
|
None => "Unknown exception".to_string(),
|
|
|
|
};
|
|
|
|
EvaluationOutput::Error(format!(
|
|
|
|
"{} {}",
|
|
|
|
exception_details.text, description
|
|
|
|
))
|
|
|
|
} else {
|
|
|
|
session
|
|
|
|
.language_server
|
|
|
|
.commit_text(&evaluate_response.ts_code)
|
|
|
|
.await;
|
|
|
|
|
|
|
|
session.set_last_eval_result(&result).await?;
|
|
|
|
let value = session.get_eval_value(&result).await?;
|
|
|
|
EvaluationOutput::Value(value)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
// handle a parsing diagnostic
|
|
|
|
match err.downcast_ref::<deno_ast::Diagnostic>() {
|
|
|
|
Some(diagnostic) => {
|
|
|
|
Ok(EvaluationOutput::Error(format_diagnostic(diagnostic)))
|
|
|
|
}
|
|
|
|
None => match err.downcast_ref::<DiagnosticsError>() {
|
|
|
|
Some(diagnostics) => Ok(EvaluationOutput::Error(
|
|
|
|
diagnostics
|
|
|
|
.0
|
|
|
|
.iter()
|
|
|
|
.map(format_diagnostic)
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.join("\n\n"),
|
|
|
|
)),
|
|
|
|
None => Err(err),
|
|
|
|
},
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-12-16 11:11:10 -05:00
|
|
|
|
|
|
|
let result = inner(self, line).await;
|
|
|
|
result_to_evaluation_output(result)
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn evaluate_line_with_object_wrapping(
|
|
|
|
&mut self,
|
|
|
|
line: &str,
|
|
|
|
) -> Result<TsEvaluateResponse, AnyError> {
|
|
|
|
// Expressions like { "foo": "bar" } are interpreted as block expressions at the
|
|
|
|
// statement level rather than an object literal so we interpret it as an expression statement
|
|
|
|
// to match the behavior found in a typical prompt including browser developer tools.
|
|
|
|
let wrapped_line = if line.trim_start().starts_with('{')
|
|
|
|
&& !line.trim_end().ends_with(';')
|
|
|
|
{
|
|
|
|
format!("({})", &line)
|
|
|
|
} else {
|
|
|
|
line.to_string()
|
|
|
|
};
|
|
|
|
|
|
|
|
let evaluate_response = self.evaluate_ts_expression(&wrapped_line).await;
|
|
|
|
|
|
|
|
// If that fails, we retry it without wrapping in parens letting the error bubble up to the
|
|
|
|
// user if it is still an error.
|
|
|
|
if wrapped_line != line
|
|
|
|
&& (evaluate_response.is_err()
|
|
|
|
|| evaluate_response
|
|
|
|
.as_ref()
|
|
|
|
.unwrap()
|
|
|
|
.value
|
2022-02-07 11:05:49 -05:00
|
|
|
.exception_details
|
2021-12-17 20:18:17 -05:00
|
|
|
.is_some())
|
|
|
|
{
|
|
|
|
self.evaluate_ts_expression(line).await
|
|
|
|
} else {
|
|
|
|
evaluate_response
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn set_last_thrown_error(
|
|
|
|
&mut self,
|
2022-02-07 11:05:49 -05:00
|
|
|
error: &cdp::RemoteObject,
|
2021-12-17 20:18:17 -05:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
self.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
2022-02-07 11:05:49 -05:00
|
|
|
Some(cdp::CallFunctionOnArgs {
|
|
|
|
function_declaration: "function (object) { Deno[Deno.internal].lastThrownError = object; }".to_string(),
|
|
|
|
object_id: None,
|
|
|
|
arguments: Some(vec![error.into()]),
|
|
|
|
silent: None,
|
|
|
|
return_by_value: None,
|
|
|
|
generate_preview: None,
|
|
|
|
user_gesture: None,
|
|
|
|
await_promise: None,
|
|
|
|
execution_context_id: Some(self.context_id),
|
|
|
|
object_group: None,
|
|
|
|
throw_on_side_effect: None
|
|
|
|
}),
|
2021-12-17 20:18:17 -05:00
|
|
|
).await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn set_last_eval_result(
|
|
|
|
&mut self,
|
2022-02-07 11:05:49 -05:00
|
|
|
evaluate_result: &cdp::RemoteObject,
|
2021-12-17 20:18:17 -05:00
|
|
|
) -> Result<(), AnyError> {
|
2022-02-07 11:05:49 -05:00
|
|
|
self
|
|
|
|
.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
|
|
|
Some(cdp::CallFunctionOnArgs {
|
|
|
|
function_declaration:
|
|
|
|
"function (object) { Deno[Deno.internal].lastEvalResult = object; }"
|
|
|
|
.to_string(),
|
|
|
|
object_id: None,
|
|
|
|
arguments: Some(vec![evaluate_result.into()]),
|
|
|
|
silent: None,
|
|
|
|
return_by_value: None,
|
|
|
|
generate_preview: None,
|
|
|
|
user_gesture: None,
|
|
|
|
await_promise: None,
|
|
|
|
execution_context_id: Some(self.context_id),
|
|
|
|
object_group: None,
|
|
|
|
throw_on_side_effect: None,
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
.await?;
|
2021-12-17 20:18:17 -05:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn get_eval_value(
|
|
|
|
&mut self,
|
2022-02-07 11:05:49 -05:00
|
|
|
evaluate_result: &cdp::RemoteObject,
|
2021-12-17 20:18:17 -05:00
|
|
|
) -> Result<String, AnyError> {
|
|
|
|
// TODO(caspervonb) we should investigate using previews here but to keep things
|
|
|
|
// consistent with the previous implementation we just get the preview result from
|
|
|
|
// Deno.inspectArgs.
|
|
|
|
let inspect_response = self.post_message_with_event_loop(
|
|
|
|
"Runtime.callFunctionOn",
|
2022-02-07 11:05:49 -05:00
|
|
|
Some(cdp::CallFunctionOnArgs {
|
|
|
|
function_declaration: r#"function (object) {
|
2021-12-17 20:18:17 -05:00
|
|
|
try {
|
|
|
|
return Deno[Deno.internal].inspectArgs(["%o", object], { colors: !Deno.noColor });
|
|
|
|
} catch (err) {
|
|
|
|
return Deno[Deno.internal].inspectArgs(["%o", err]);
|
|
|
|
}
|
2022-02-07 11:05:49 -05:00
|
|
|
}"#.to_string(),
|
|
|
|
object_id: None,
|
|
|
|
arguments: Some(vec![evaluate_result.into()]),
|
|
|
|
silent: None,
|
|
|
|
return_by_value: None,
|
|
|
|
generate_preview: None,
|
|
|
|
user_gesture: None,
|
|
|
|
await_promise: None,
|
|
|
|
execution_context_id: Some(self.context_id),
|
|
|
|
object_group: None,
|
|
|
|
throw_on_side_effect: None
|
|
|
|
}),
|
2021-12-17 20:18:17 -05:00
|
|
|
).await?;
|
|
|
|
|
2022-02-07 11:05:49 -05:00
|
|
|
let response: cdp::CallFunctionOnResponse =
|
|
|
|
serde_json::from_value(inspect_response)?;
|
|
|
|
let value = response.result.value.unwrap();
|
|
|
|
let s = value.as_str().unwrap();
|
2021-12-17 20:18:17 -05:00
|
|
|
|
2022-02-07 11:05:49 -05:00
|
|
|
Ok(s.to_string())
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
async fn evaluate_ts_expression(
|
|
|
|
&mut self,
|
|
|
|
expression: &str,
|
|
|
|
) -> Result<TsEvaluateResponse, AnyError> {
|
|
|
|
let parsed_module = deno_ast::parse_module(deno_ast::ParseParams {
|
|
|
|
specifier: "repl.ts".to_string(),
|
2022-05-20 16:40:55 -04:00
|
|
|
text_info: deno_ast::SourceTextInfo::from_string(expression.to_string()),
|
2021-12-17 20:18:17 -05:00
|
|
|
media_type: deno_ast::MediaType::TypeScript,
|
|
|
|
capture_tokens: false,
|
|
|
|
maybe_syntax: None,
|
|
|
|
scope_analysis: false,
|
|
|
|
})?;
|
|
|
|
|
2023-02-01 16:37:05 -05:00
|
|
|
self
|
|
|
|
.check_for_npm_or_node_imports(&parsed_module.program())
|
|
|
|
.await?;
|
2022-12-13 07:53:32 -05:00
|
|
|
|
2022-01-13 11:58:00 -05:00
|
|
|
let transpiled_src = parsed_module
|
|
|
|
.transpile(&deno_ast::EmitOptions {
|
2021-12-17 20:18:17 -05:00
|
|
|
emit_metadata: false,
|
|
|
|
source_map: false,
|
|
|
|
inline_source_map: false,
|
|
|
|
inline_sources: false,
|
|
|
|
imports_not_used_as_values: ImportsNotUsedAsValues::Preserve,
|
|
|
|
// JSX is not supported in the REPL
|
|
|
|
transform_jsx: false,
|
|
|
|
jsx_automatic: false,
|
|
|
|
jsx_development: false,
|
|
|
|
jsx_factory: "React.createElement".into(),
|
|
|
|
jsx_fragment_factory: "React.Fragment".into(),
|
|
|
|
jsx_import_source: None,
|
2022-01-13 11:58:00 -05:00
|
|
|
var_decl_imports: true,
|
|
|
|
})?
|
|
|
|
.text;
|
2021-12-17 20:18:17 -05:00
|
|
|
|
|
|
|
let value = self
|
2023-01-27 10:43:16 -05:00
|
|
|
.evaluate_expression(&format!("'use strict'; void 0;\n{transpiled_src}"))
|
2021-12-17 20:18:17 -05:00
|
|
|
.await?;
|
|
|
|
|
|
|
|
Ok(TsEvaluateResponse {
|
|
|
|
ts_code: expression.to_string(),
|
|
|
|
value,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-02-01 16:37:05 -05:00
|
|
|
async fn check_for_npm_or_node_imports(
|
2022-12-13 07:53:32 -05:00
|
|
|
&mut self,
|
|
|
|
program: &swc_ast::Program,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let mut collector = ImportCollector::new();
|
|
|
|
program.visit_with(&mut collector);
|
|
|
|
|
2023-02-01 16:37:05 -05:00
|
|
|
let resolved_imports = collector
|
2022-12-13 07:53:32 -05:00
|
|
|
.imports
|
|
|
|
.iter()
|
|
|
|
.flat_map(|i| {
|
|
|
|
self
|
|
|
|
.proc_state
|
|
|
|
.maybe_resolver
|
|
|
|
.as_ref()
|
2023-01-24 08:23:19 -05:00
|
|
|
.and_then(|resolver| resolver.resolve(i, &self.referrer).ok())
|
2022-12-13 07:53:32 -05:00
|
|
|
.or_else(|| ModuleSpecifier::parse(i).ok())
|
|
|
|
})
|
2023-02-01 16:37:05 -05:00
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
let npm_imports = resolved_imports
|
|
|
|
.iter()
|
|
|
|
.flat_map(|url| NpmPackageReference::from_specifier(url).ok())
|
2022-12-13 07:53:32 -05:00
|
|
|
.map(|r| r.req)
|
|
|
|
.collect::<Vec<_>>();
|
2023-02-01 16:37:05 -05:00
|
|
|
let has_node_specifier =
|
|
|
|
resolved_imports.iter().any(|url| url.scheme() == "node");
|
|
|
|
if !npm_imports.is_empty() || has_node_specifier {
|
2022-12-13 07:53:32 -05:00
|
|
|
if !self.has_initialized_node_runtime {
|
|
|
|
self.proc_state.prepare_node_std_graph().await?;
|
2022-12-16 17:41:51 -05:00
|
|
|
crate::node::initialize_runtime(
|
|
|
|
&mut self.worker.js_runtime,
|
|
|
|
self.proc_state.options.node_modules_dir(),
|
|
|
|
)
|
|
|
|
.await?;
|
2022-12-13 07:53:32 -05:00
|
|
|
self.has_initialized_node_runtime = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
self
|
|
|
|
.proc_state
|
|
|
|
.npm_resolver
|
|
|
|
.add_package_reqs(npm_imports)
|
|
|
|
.await?;
|
2023-02-01 16:37:05 -05:00
|
|
|
|
|
|
|
// prevent messages in the repl about @types/node not being cached
|
|
|
|
if has_node_specifier {
|
|
|
|
self
|
|
|
|
.proc_state
|
|
|
|
.npm_resolver
|
|
|
|
.inject_synthetic_types_node_package()
|
|
|
|
.await?;
|
|
|
|
}
|
2022-12-13 07:53:32 -05:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-12-17 20:18:17 -05:00
|
|
|
async fn evaluate_expression(
|
|
|
|
&mut self,
|
|
|
|
expression: &str,
|
2022-02-07 11:05:49 -05:00
|
|
|
) -> Result<cdp::EvaluateResponse, AnyError> {
|
2021-12-17 20:18:17 -05:00
|
|
|
self
|
|
|
|
.post_message_with_event_loop(
|
|
|
|
"Runtime.evaluate",
|
2022-02-07 11:05:49 -05:00
|
|
|
Some(cdp::EvaluateArgs {
|
|
|
|
expression: expression.to_string(),
|
|
|
|
object_group: None,
|
|
|
|
include_command_line_api: None,
|
|
|
|
silent: None,
|
|
|
|
context_id: Some(self.context_id),
|
|
|
|
return_by_value: None,
|
|
|
|
generate_preview: None,
|
|
|
|
user_gesture: None,
|
|
|
|
await_promise: None,
|
|
|
|
throw_on_side_effect: None,
|
|
|
|
timeout: None,
|
|
|
|
disable_breaks: None,
|
|
|
|
repl_mode: Some(true),
|
|
|
|
allow_unsafe_eval_blocked_by_csp: None,
|
|
|
|
unique_context_id: None,
|
|
|
|
}),
|
2021-12-17 20:18:17 -05:00
|
|
|
)
|
|
|
|
.await
|
2022-02-07 11:05:49 -05:00
|
|
|
.and_then(|res| serde_json::from_value(res).map_err(|e| e.into()))
|
2021-12-17 20:18:17 -05:00
|
|
|
}
|
|
|
|
}
|
2022-12-13 07:53:32 -05:00
|
|
|
|
|
|
|
/// Walk an AST and get all import specifiers for analysis if any of them is
|
|
|
|
/// an npm specifier.
|
|
|
|
struct ImportCollector {
|
|
|
|
pub imports: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ImportCollector {
|
|
|
|
pub fn new() -> Self {
|
|
|
|
Self { imports: vec![] }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Visit for ImportCollector {
|
|
|
|
noop_visit_type!();
|
|
|
|
|
|
|
|
fn visit_call_expr(&mut self, call_expr: &swc_ast::CallExpr) {
|
|
|
|
if !matches!(call_expr.callee, swc_ast::Callee::Import(_)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if !call_expr.args.is_empty() {
|
|
|
|
let arg = &call_expr.args[0];
|
|
|
|
if let swc_ast::Expr::Lit(swc_ast::Lit::Str(str_lit)) = &*arg.expr {
|
|
|
|
self.imports.push(str_lit.value.to_string());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_module_decl(&mut self, module_decl: &swc_ast::ModuleDecl) {
|
|
|
|
use deno_ast::swc::ast::*;
|
|
|
|
|
|
|
|
match module_decl {
|
|
|
|
ModuleDecl::Import(import_decl) => {
|
|
|
|
if import_decl.type_only {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.imports.push(import_decl.src.value.to_string());
|
|
|
|
}
|
|
|
|
ModuleDecl::ExportAll(export_all) => {
|
|
|
|
self.imports.push(export_all.src.value.to_string());
|
|
|
|
}
|
|
|
|
ModuleDecl::ExportNamed(export_named) => {
|
|
|
|
if let Some(src) = &export_named.src {
|
|
|
|
self.imports.push(src.value.to_string());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|