ronantakizawa/codereview-bench huggingface dataset:
Repository: denoland/deno
File: ext/fs/ops.rs (Rust)

Code before:
  #[string] path: String,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsOpsError>
where
  P: FsPermissions + 'static,
{
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<P>().check_write(&path, "Deno.chown()")?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };
  fs.chown_async(path.clone(), uid, gid)
    .await
    .context_path("chown", &path)?;
  Ok(())
}

#[op2(stack_trace)]
pub fn op_fs_fchown_sync(
  state: &mut OpState,
  #[smi] rid: ResourceId,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsOpsError> {
  let file =
    FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?;
  file.chown_sync(uid, gid)?;
  Ok(())
}

#[op2(async, stack_trace)]
pub async fn op_fs_fchown_async(
  state: Rc<RefCell<OpState>>,
  #[smi] rid: ResourceId,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsOpsError> {
  let file = FileResource::get_file(&state.borrow(), rid)
    .map_err(FsOpsErrorKind::Resource)?;
  file.chown_async(uid, gid).await?;
  Ok(())
}

#[op2(fast, stack_trace)]
pub fn op_fs_remove_sync<P>(
  state: &mut OpState,
  #[string] path: &str,
  recursive: bool,
) -> Result<(), FsOpsError>
where

Review comment (suggestion):
This is not really correct - `ResourceId` is not a real file descriptor that the Node API expects. That said, it appears that we already have several APIs that do that already, so I think it's fine for now...

Code after:
  #[string] path: String,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsOpsError>
where
  P: FsPermissions + 'static,
{
  let (fs, path) = {
    let mut state = state.borrow_mut();
    let path = state.borrow_mut::<P>().check_write(&path, "Deno.chown()")?;
    (state.borrow::<FileSystemRc>().clone(), path)
  };
  fs.chown_async(path.clone(), uid, gid)
    .await
    .context_path("chown", &path)?;
  Ok(())
}

#[op2(fast, stack_trace)]
pub fn op_fs_fchmod_sync(
  state: &mut OpState,
  #[smi] rid: ResourceId,
  mode: u32,
) -> Result<(), FsOpsError> {
  let file =
    FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?;
  file.chmod_sync(mode)?;
  Ok(())
}

#[op2(async, stack_trace)]
pub async fn op_fs_fchmod_async(
  state: Rc<RefCell<OpState>>,
  #[smi] rid: ResourceId,
  mode: u32,
) -> Result<(), FsOpsError> {
  let file = FileResource::get_file(&state.borrow(), rid)
    .map_err(FsOpsErrorKind::Resource)?;
  file.chmod_async(mode).await?;
  Ok(())
}

#[op2(stack_trace)]
pub fn op_fs_fchown_sync(
  state: &mut OpState,
  #[smi] rid: ResourceId,
  uid: Option<u32>,
  gid: Option<u32>,
) -> Result<(), FsOpsError> {
  let file =
    FileResource::get_file(state, rid).map_err(FsOpsErrorKind::Resource)?;
Repository: denoland/deno
File: cli/tools/fmt.rs (Rust)

Code before:
  file_path: &Path,
  file_contents: String,
) -> Result<(), AnyError> {
  Ok(fs::write(file_path, file_contents)?)
}

pub async fn run_parallelized<F>(
  file_paths: Vec<PathBuf>,
  f: F,
) -> Result<(), AnyError>
where
  F: FnOnce(PathBuf) -> Result<(), AnyError> + Send + 'static + Clone,
{
  let handles = file_paths.iter().map(|file_path| {
    let f = f.clone();
    let file_path = file_path.clone();
    spawn_blocking(move || f(file_path))
  });
  let join_results = futures::future::join_all(handles).await;

  // find the tasks that panicked and let the user know which files
  let panic_file_paths = join_results
    .iter()
    .enumerate()
    .filter_map(|(i, join_result)| {
      join_result
        .as_ref()
        .err()
        .map(|_| file_paths[i].to_string_lossy())
    })
    .collect::<Vec<_>>();
  if !panic_file_paths.is_empty() {
    panic!("Panic formatting: {}", panic_file_paths.join(", "))
  }

  // check for any errors and if so return the first one
  let mut errors = join_results.into_iter().filter_map(|join_result| {
    join_result
      .ok()
      .and_then(|handle_result| handle_result.err())
  });

  if let Some(e) = errors.next() {
    Err(e)
  } else {
    Ok(())
  }
}

/// This function is similar to is_supported_ext but adds additional extensions
/// supported by `deno fmt`.

Review comment (suggestion):
I think this currently strips the bom internally: https://github.com/denoland/deno_media_type/blob/1aa277b0f182f23680f8077ee85266f0a95ddf8a/src/encoding.rs#L50

Code after:
    flow_sequence_prefer_single_line: None,
    flow_map_prefer_single_line: None,
    trim_trailing_whitespaces: true,
    trim_trailing_zero: false,
    ignore_comment_directive: "deno-fmt-ignore".into(),
  };

  FormatOptions {
    layout: layout_options,
    language: language_options,
  }
}

pub struct FileContents<'a> {
  pub text: Cow<'a, str>,
  pub had_bom: bool,
}

fn read_file_contents(file_path: &Path) -> Result<FileContents, AnyError> {
  let file_bytes = fs::read(file_path)
    .with_context(|| format!("Error reading {}", file_path.display()))?;
  let had_bom = file_bytes.starts_with(&[0xEF, 0xBB, 0xBF]);

  let charset =
    deno_media_type::encoding::detect_charset_local_file(&file_bytes);
  let text = deno_media_type::encoding::decode_owned_source(
    charset,
    file_bytes.to_vec(),
  )
  .with_context(|| {
    anyhow!("{} is not a valid UTF-8 file", file_path.display())
  })?;

  Ok(FileContents {
    text: Cow::Owned(text),
    had_bom,
  })
}

fn write_file_contents(
  file_path: &Path,
  file_contents: &str,
) -> Result<(), AnyError> {
  Ok(fs::write(file_path, file_contents)?)
}

pub async fn run_parallelized<F>(
  file_paths: Vec<PathBuf>,
  f: F,
) -> Result<(), AnyError>
where
Repository: denoland/deno
File: cli/lib/args.rs (Rust)

Code before:
    }

    maybe_set(
      &mut self.bare_node_builtins,
      UNSTABLE_ENV_VAR_NAMES.bare_node_builtins,
    );
    maybe_set(
      &mut self.lazy_dynamic_imports,
      UNSTABLE_ENV_VAR_NAMES.lazy_dynamic_imports,
    );
    maybe_set(
      &mut self.npm_lazy_caching,
      UNSTABLE_ENV_VAR_NAMES.npm_lazy_caching,
    );
    maybe_set(&mut self.raw_imports, UNSTABLE_ENV_VAR_NAMES.raw_imports);
    maybe_set(
      &mut self.sloppy_imports,
      UNSTABLE_ENV_VAR_NAMES.sloppy_imports,
    );
  }

  pub fn enable_node_compat(&mut self) {
    self.bare_node_builtins = true;
    self.sloppy_imports = true;
    self.detect_cjs = true;
    if !self.features.contains(&"node-globals".to_string()) {
      self.features.push("node-globals".to_string());
    }
  }
}


Review comment (suggestion):
Removes an allocation:

```suggestion
    if !self.features.iter().any(|f| f == "node-globals") {
```

Code after:
    }

    maybe_set(
      &mut self.bare_node_builtins,
      UNSTABLE_ENV_VAR_NAMES.bare_node_builtins,
    );
    maybe_set(
      &mut self.lazy_dynamic_imports,
      UNSTABLE_ENV_VAR_NAMES.lazy_dynamic_imports,
    );
    maybe_set(
      &mut self.npm_lazy_caching,
      UNSTABLE_ENV_VAR_NAMES.npm_lazy_caching,
    );
    maybe_set(&mut self.raw_imports, UNSTABLE_ENV_VAR_NAMES.raw_imports);
    maybe_set(
      &mut self.sloppy_imports,
      UNSTABLE_ENV_VAR_NAMES.sloppy_imports,
    );
  }

  pub fn enable_node_compat(&mut self) {
    self.bare_node_builtins = true;
    self.sloppy_imports = true;
    self.detect_cjs = true;
    if !self.features.iter().any(|f| f == "node-globals") {
      self.features.push("node-globals".to_string());
    }
  }
}
Repository: denoland/deno
File: ext/node/ops/fs.rs (Rust)

Code before:
  };

  fs.cp_async(path.into_owned(), new_path.into_owned())
    .await?;
  Ok(())
}

fn open_options_to_access_kind(open_options: &OpenOptions) -> OpenAccessKind {
  let read = open_options.read;
  let write = open_options.write || open_options.append;
  match (read, write) {
    (true, true) => OpenAccessKind::ReadWrite,
    (false, true) => OpenAccessKind::Write,
    (true, false) | (false, false) => OpenAccessKind::Read,
  }
}

#[op2(stack_trace)]
#[smi]
pub fn op_node_open_sync<P>(
  state: &mut OpState,
  #[string] path: &str,
  #[serde] options: OpenOptions,
) -> Result<ResourceId, FsError>
where
  P: NodePermissions + 'static,
{
  let path = Path::new(path);

  let fs = state.borrow::<FileSystemRc>().clone();
  let path = state.borrow_mut::<P>().check_open(
    Cow::Borrowed(path),
    open_options_to_access_kind(&options),
    Some("node:fs.openSync"),
  )?;
  let file = fs.open_sync(&path, options)?;
  let rid = state
    .resource_table
    .add(FileResource::new(file, "fsFile".to_string()));
  Ok(rid)
}

#[op2(async, stack_trace)]
#[smi]
pub async fn op_node_open<P>(
  state: Rc<RefCell<OpState>>,
  #[string] path: String,
  #[serde] options: OpenOptions,
) -> Result<ResourceId, FsError>
where
  P: NodePermissions + 'static,

Review comment (security):
Here's the current logic from Deno 2.4.3: 
https://github.com/denoland/deno/blob/5612d2edc7262d7bfb3bcfb0f18649b01ec94b53/ext/node/polyfills/_fs/_fs_common.ts#L222-L226

I intentionally omitted the read permission as the Rust stdlib only requires write permission when chained with `create_new`:
https://doc.rust-lang.org/src/std/sys/fs/unix.rs.html#1118-1152

Code after:
  };

  fs.cp_async(path.into_owned(), new_path.into_owned())
    .await?;
  Ok(())
}

fn get_open_options(mut flags: i32, mode: u32) -> OpenOptions {
  let mut options = OpenOptions {
    mode: Some(mode),
    ..Default::default()
  };

  if (flags & libc::O_APPEND) == libc::O_APPEND {
    options.append = true;
    flags &= !libc::O_APPEND;
  }
  if (flags & libc::O_CREAT) == libc::O_CREAT {
    options.create = true;
    flags &= !libc::O_CREAT;
  }
  if (flags & libc::O_EXCL) == libc::O_EXCL {
    options.create_new = true;
    options.write = true;
    flags &= !libc::O_EXCL;
  }
  if (flags & libc::O_RDWR) == libc::O_RDWR {
    options.read = true;
    options.write = true;
    flags &= !libc::O_RDWR;
  }
  if (flags & libc::O_TRUNC) == libc::O_TRUNC {
    options.truncate = true;
    flags &= !libc::O_TRUNC;
  }
  if (flags & libc::O_WRONLY) == libc::O_WRONLY {
    options.write = true;
    flags &= !libc::O_WRONLY;
  }

  if flags != 0 {
    options.custom_flags = Some(flags);
  }

  if !options.append
    && !options.create
    && !options.create_new
    && !options.read
    && !options.truncate
    && !options.write
  {
Repository: denoland/deno
File: ext/node/polyfills/internal/crypto/_randomInt.ts (TypeScript)

Code before:
  cb: (err: Error | null, n?: number) => void,
): void;
export default function randomInt(
  min: number,
  max: number,
  cb: (err: Error | null, n?: number) => void,
): void;

export default function randomInt(
  max: number,
  min?: ((err: Error | null, n?: number) => void) | number,
  cb?: (err: Error | null, n?: number) => void,
): number | void {
  if (typeof max === "number" && typeof min === "number") {
    const temp = max;
    max = min;
    min = temp;
  }
  if (min === undefined) min = 0;
  else if (typeof min === "function") {
    cb = min;
    min = 0;
  }

  if (!NumberIsSafeInteger(min) || !NumberIsSafeInteger(max)) {
    throw new TypeError("max or min is not a Safe Number");
  }

  if (max - min > MathPow(2, 48)) {
    throw new RangeError("max - min should be less than 2^48!");
  }

  if (min >= max) {
    throw new Error("Min is bigger than Max!");
  }

  min = MathCeil(min);
  max = MathFloor(max);
  const result = op_node_random_int(min, max);

  if (cb) {
    cb(null, result);
    return;
  }

  return result;
}


Review comment (suggestion):
How about we follow Node.js's implementation, so that we can have the same error message:
https://github.com/nodejs/node/blob/9d2368f64329bf194c4e82b349e76fdad879d32a/lib/internal/crypto/random.js#L225-L230

You can import the error from here:
```ts
import { ERR_INVALID_ARG_TYPE } from "ext:deno_node/internal/errors.ts";
```

Code after:
  cb: (err: Error | null, n?: number) => void,
): void;
export default function randomInt(
  min: number,
  max: number,
  cb: (err: Error | null, n?: number) => void,
): void;

export default function randomInt(
  max: number,
  min?: ((err: Error | null, n?: number) => void) | number,
  cb?: (err: Error | null, n?: number) => void,
): number | void {
  if (typeof max === "number" && typeof min === "number") {
    const temp = max;
    max = min;
    min = temp;
  }
  if (min === undefined) min = 0;
  else if (typeof min === "function") {
    cb = min;
    min = 0;
  }

  if (!NumberIsSafeInteger(min)) {
    throw new ERR_INVALID_ARG_TYPE("min", "a safe integer", min);
  }

  if (!NumberIsSafeInteger(max)) {
    throw new ERR_INVALID_ARG_TYPE("max", "a safe integer", max);
  }

  if (max - min > MathPow(2, 48)) {
    throw new RangeError("max - min should be less than 2^48!");
  }

  if (min >= max) {
    throw new Error("Min is bigger than Max!");
  }

  min = MathCeil(min);
  max = MathFloor(max);
  const result = op_node_random_int(min, max);

  if (cb) {
    cb(null, result);
    return;
  }

  return result;
}
Repository: denoland/deno
File: libs/node_resolver/errors.rs (Rust)

Code before:
    self.0.maybe_referrer.as_ref().map(|r| format!(" imported from '{}'", r)).unwrap_or_default(),
  )]
#[class(generic)]
#[property("code" = self.code())]
pub struct TypesNotFoundError(pub Box<TypesNotFoundErrorData>);

#[derive(Debug)]
pub struct TypesNotFoundErrorData {
  pub code_specifier: UrlOrPath,
  pub maybe_referrer: Option<UrlOrPath>,
}

impl NodeJsErrorCoded for TypesNotFoundError {
  fn code(&self) -> NodeJsErrorCode {
    NodeJsErrorCode::ERR_TYPES_NOT_FOUND
  }
}

#[derive(Debug, Error, JsError)]
pub enum PackageJsonLoadError {
  #[class(inherit)]
  #[error("[{}] Invalid package config. {}", self.code(), .0)]
  PackageJson(#[from] deno_package_json::PackageJsonLoadError),
  #[class(generic)]
  #[error("[{}] JSR specifiers are not supported in package.json: {req}", self.code())]
  JsrReqUnsupported { req: String },
}

impl NodeJsErrorCoded for PackageJsonLoadError {
  fn code(&self) -> NodeJsErrorCode {
    NodeJsErrorCode::ERR_INVALID_PACKAGE_CONFIG
  }
}

impl NodeJsErrorCoded for ClosestPkgJsonError {
  fn code(&self) -> NodeJsErrorCode {
    match self.as_kind() {
      ClosestPkgJsonErrorKind::Load(e) => e.code(),
    }
  }
}

#[derive(Debug, Boxed, JsError)]
pub struct ClosestPkgJsonError(pub Box<ClosestPkgJsonErrorKind>);

#[derive(Debug, Error, JsError)]
pub enum ClosestPkgJsonErrorKind {
  #[class(inherit)]
  #[error(transparent)]
  Load(#[from] PackageJsonLoadError),
}

Review comment (suggestion):
This is specific to resolving a specifier and not loading a package.json, so removed from here and moved to the resolution error instead.

Code after:
    self.0.maybe_referrer.as_ref().map(|r| format!(" imported from '{}'", r)).unwrap_or_default(),
  )]
#[class(generic)]
#[property("code" = self.code())]
pub struct TypesNotFoundError(pub Box<TypesNotFoundErrorData>);

#[derive(Debug)]
pub struct TypesNotFoundErrorData {
  pub code_specifier: UrlOrPath,
  pub maybe_referrer: Option<UrlOrPath>,
}

impl NodeJsErrorCoded for TypesNotFoundError {
  fn code(&self) -> NodeJsErrorCode {
    NodeJsErrorCode::ERR_TYPES_NOT_FOUND
  }
}

#[derive(Debug, Error, JsError)]
#[class(inherit)]
#[error("[{}] Invalid package config. {}", self.code(), .0)]
pub struct PackageJsonLoadError(pub deno_package_json::PackageJsonLoadError);

impl NodeJsErrorCoded for PackageJsonLoadError {
  fn code(&self) -> NodeJsErrorCode {
    NodeJsErrorCode::ERR_INVALID_PACKAGE_CONFIG
  }
}

#[derive(Debug, Error, JsError)]
#[class(type)]
#[error(
  "[{}] Package import specifier \"{}\" is not defined{}{}",
  self.code(),
  name,
  package_json_path.as_ref().map(|p| format!(" in package {}", p.display())).unwrap_or_default(),
  maybe_referrer.as_ref().map(|r| format!(" imported from '{}'", r)).unwrap_or_default(),
)]
#[property("code" = self.code())]
pub struct PackageImportNotDefinedError {
  pub name: String,
  pub package_json_path: Option<PathBuf>,
  pub maybe_referrer: Option<UrlOrPath>,
}

impl NodeJsErrorCoded for PackageImportNotDefinedError {
  fn code(&self) -> NodeJsErrorCode {
    NodeJsErrorCode::ERR_PACKAGE_IMPORT_NOT_DEFINED
  }
}
Repository: denoland/deno
File: tests/node_compat/run_all_test_unmodified.ts (TypeScript)

Code before:
/** The group is the directory name of the test file.
 * e.g. parallel, internet, pummel, sequential, pseudo-tty, etc */
function getGroupRelUrl(str: string) {
  return str.split("/")[0];
}

function truncateTestOutput(output: string): string {
  output = stripAnsiCode(output);
  if (output.length > 2000) {
    return output.slice(0, 2000) + " ...";
  }
  return output;
}

enum NodeTestFileResult {
  PASS = "pass",
  FAIL = "fail",
  SKIP = "skip", // skipped because of filtering (for debugging locally)
  IGNORED = "ignored", // ignored because the test case does not need to pass in Deno
}

interface NonIgnoredTestFileReport {
  result: Exclude<
    NodeTestFileResult,
    NodeTestFileResult.IGNORED
  >;
  error?: ErrorExit | ErrorTimeout | ErrorUnexpected;
}

interface IgnoredTestFileReport {
  result: NodeTestFileResult.IGNORED;
  reason: string | undefined;
  error?: undefined;
}

type NodeTestFileReport = (NonIgnoredTestFileReport | IgnoredTestFileReport) & {
  usesNodeTest: boolean; // whether the test uses `node:test` module
};

type TestReports = Record<string, NodeTestFileReport>;

type BaseSingleResultInfo = {
  usesNodeTest?: 1; // Uses this form to minimize the size of the report.json
};

type IgnoredSingleResultInfo = BaseSingleResultInfo & {
  ignoreReason: string | undefined;
};

type NonIgnoredSingleResult = [
  pass: boolean,

Review comment (bug):
Argh :D feels like an overkill - wouldn't `NodetestFileResult.OK | NodeTestFileResult.FAILED` be simpler here?

Code after:
/** The group is the directory name of the test file.
 * e.g. parallel, internet, pummel, sequential, pseudo-tty, etc */
function getGroupRelUrl(str: string) {
  return str.split("/")[0];
}

function truncateTestOutput(output: string): string {
  output = stripAnsiCode(output);
  if (output.length > 2000) {
    return output.slice(0, 2000) + " ...";
  }
  return output;
}

enum NodeTestFileResult {
  PASS = "pass",
  FAIL = "fail",
  SKIP = "skip", // skipped because of filtering (for debugging locally)
  IGNORED = "ignored", // ignored because the test case does not need to pass in Deno
}

interface NonIgnoredTestFileReport {
  result:
    | NodeTestFileResult.PASS
    | NodeTestFileResult.FAIL
    | NodeTestFileResult.SKIP; // Currently skipped tests will not be written to the report
  error?: ErrorExit | ErrorTimeout | ErrorUnexpected;
}

interface IgnoredTestFileReport {
  result: NodeTestFileResult.IGNORED;
  reason: string | undefined;
  error?: undefined;
}

type NodeTestFileReport = (NonIgnoredTestFileReport | IgnoredTestFileReport) & {
  usesNodeTest: boolean; // whether the test uses `node:test` module
};

type TestReports = Record<string, NodeTestFileReport>;

type BaseSingleResultInfo = {
  usesNodeTest?: 1; // Uses this form to minimize the size of the report.json
};

type IgnoredSingleResultInfo = BaseSingleResultInfo & {
  ignoreReason: string | undefined;
};

type NonIgnoredSingleResult = [
  pass: boolean,
Repository: denoland/deno
File: cli/rt/file_system.rs (Rust)

Code before:
  async fn chmod_async(&self, path: CheckedPathBuf, mode: i32) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.chmod_async(path, mode).await
  }

  fn chown_sync(
    &self,
    path: &CheckedPath,
    uid: Option<u32>,
    gid: Option<u32>,
  ) -> FsResult<()> {
    self.error_if_in_vfs(path)?;
    RealFs.chown_sync(path, uid, gid)
  }
  async fn chown_async(
    &self,
    path: CheckedPathBuf,
    uid: Option<u32>,
    gid: Option<u32>,
  ) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.chown_async(path, uid, gid).await
  }

  fn exists_sync(&self, path: &CheckedPath) -> bool {
    if self.error_if_in_vfs(path).is_err() {
      return false;
    }
    RealFs.exists_sync(path)
  }
  async fn exists_async(&self, path: CheckedPathBuf) -> FsResult<bool> {
    self.error_if_in_vfs(&path)?;
    RealFs.exists_async(path).await
  }

  fn lchmod_sync(&self, path: &CheckedPath, mode: u32) -> FsResult<()> {
    self.error_if_in_vfs(path)?;
    RealFs.lchmod_sync(path, mode)
  }

  async fn lchmod_async(
    &self,
    path: CheckedPathBuf,
    mode: u32,
  ) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.lchmod_async(path, mode).await
  }

  fn lchown_sync(
    &self,

Review comment (bug):
This is wrong. It should only call this function for write operations. Look at `stat_sync` for an example.

Code after:
  async fn chmod_async(&self, path: CheckedPathBuf, mode: i32) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.chmod_async(path, mode).await
  }

  fn chown_sync(
    &self,
    path: &CheckedPath,
    uid: Option<u32>,
    gid: Option<u32>,
  ) -> FsResult<()> {
    self.error_if_in_vfs(path)?;
    RealFs.chown_sync(path, uid, gid)
  }
  async fn chown_async(
    &self,
    path: CheckedPathBuf,
    uid: Option<u32>,
    gid: Option<u32>,
  ) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.chown_async(path, uid, gid).await
  }

  fn exists_sync(&self, path: &CheckedPath) -> bool {
    if self.0.is_path_within(path) {
      self.0.exists(path)
    } else {
      RealFs.exists_sync(path)
    }
  }
  async fn exists_async(&self, path: CheckedPathBuf) -> FsResult<bool> {
    if self.0.is_path_within(&path) {
      Ok(self.0.exists(&path))
    } else {
      RealFs.exists_async(path).await
    }
  }

  fn lchmod_sync(&self, path: &CheckedPath, mode: u32) -> FsResult<()> {
    self.error_if_in_vfs(path)?;
    RealFs.lchmod_sync(path, mode)
  }

  async fn lchmod_async(
    &self,
    path: CheckedPathBuf,
    mode: u32,
  ) -> FsResult<()> {
    self.error_if_in_vfs(&path)?;
    RealFs.lchmod_async(path, mode).await
Repository: denoland/deno
File: tests/unit_node/sqlite_test.ts (TypeScript)

Code before:
// Copyright 2018-2025 the Deno authors. MIT license.
import sqlite, { DatabaseSync } from "node:sqlite";
import { assert, assertEquals, assertThrows } from "@std/assert";

const tempDir = Deno.makeTempDirSync();

Deno.test("[node/sqlite] sqlite-type symbol", () => {
  const db = new DatabaseSync(":memory:");
  const sqliteTypeSymbol = Symbol.for("sqlite-type");

  assertEquals(db[sqliteTypeSymbol], "node:sqlite");

  db.close();
});

Deno.test("[node/sqlite] in-memory databases", () => {
  const db1 = new DatabaseSync(":memory:");
  const db2 = new DatabaseSync(":memory:");
  assertEquals(
    db1.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);"),
    undefined,
  );
  db1.exec("INSERT INTO data (key) VALUES (1);");

  db2.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);");
  db2.exec("INSERT INTO data (key) VALUES (1);");

  assertEquals(db1.prepare("SELECT * FROM data").all(), [{
    key: 1,
    __proto__: null,
  }]);
  assertEquals(db2.prepare("SELECT * FROM data").all(), [{
    key: 1,
    __proto__: null,
  }]);
});


Review comment (suggestion):
```suggestion
  // @ts-ignore `sqliteTypeSymbol` is not available in `@types:node` for version 24.3
  assertEquals(db[sqliteTypeSymbol], "node:sqlite");
```

Code after:
// Copyright 2018-2025 the Deno authors. MIT license.
import sqlite, { DatabaseSync } from "node:sqlite";
import { assert, assertEquals, assertThrows } from "@std/assert";

const tempDir = Deno.makeTempDirSync();

Deno.test("[node/sqlite] sqlite-type symbol", () => {
  const db = new DatabaseSync(":memory:");
  const sqliteTypeSymbol = Symbol.for("sqlite-type");

  // @ts-ignore `sqliteTypeSymbol` is not available in `@types:node` for version 24.3
  assertEquals(db[sqliteTypeSymbol], "node:sqlite");

  db.close();
});

Deno.test("[node/sqlite] in-memory databases", () => {
  const db1 = new DatabaseSync(":memory:");
  const db2 = new DatabaseSync(":memory:");
  assertEquals(
    db1.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);"),
    undefined,
  );
  db1.exec("INSERT INTO data (key) VALUES (1);");

  db2.exec("CREATE TABLE data(key INTEGER PRIMARY KEY);");
  db2.exec("INSERT INTO data (key) VALUES (1);");

  assertEquals(db1.prepare("SELECT * FROM data").all(), [{
    key: 1,
    __proto__: null,
  }]);
  assertEquals(db2.prepare("SELECT * FROM data").all(), [{
    key: 1,
    __proto__: null,
  }]);
});