Skip to content

Commit

Permalink
Merge pull request #506 from ledsun/require_remote_base_url
Browse files Browse the repository at this point in the history
Add a base_url property to JS::RequreRemote to specify the base URL for resolving relative paths.
  • Loading branch information
kateinoigakukun authored Aug 19, 2024
2 parents 22a8f54 + 0d72102 commit f4dafaa
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/gems/js/lib/js/require_remote.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,27 @@ class RequireRemote
include Singleton

def initialize
# By default, the base_url is the URL of the HTML file that invoked ruby.wasm vm.
base_url = JS.global[:URL].new(JS.global[:location][:href])
@resolver = URLResolver.new(base_url)
@evaluator = Evaluator.new
end

# If you want to resolve relative paths to a starting point other than the HTML file that executes ruby.wasm,
# you can set the base_url property.
# For example, if you want to use the `lib` directory as the starting point, specify base_url as follows
#
# == Example
# require 'js/require_remote'
# JS::RequireRemote.instance.base_url = "lib"
# JS::RequireRemote.instance.load("foo") # => 'lib/foo.rb' will be loaded.
#
def base_url=(base_url)
base_url = base_url.end_with?("/") ? base_url : "#{base_url}/"
url = JS.global[:URL].new(base_url, JS.global[:location][:href])
@resolver = URLResolver.new(url)
end

# Load the given feature from remote.
def load(relative_feature)
location = @resolver.get_location(relative_feature)
Expand Down
4 changes: 4 additions & 0 deletions packages/gems/js/lib/js/require_remote/url_resolver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ def pop()
@url_stack.pop
end

def inspect
"#{self.class}(#{@url_stack})"
end

private

def filename_from(relative_feature)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,25 @@ if (!process.env.RUBY_NPM_PACKAGE_ROOT) {

expect(await resolve()).toBe("Hello from RecursiveRequire::B");
});

test("JS::RequireRemote#load loads the file with a path relative to the base_url specified by the base_url property.", async ({
page,
}) => {
const resolve = await resolveBinding(page, "checkResolved");
await page.goto(
"https://cdn.jsdelivr.net/npm/@ruby/head-wasm-wasi@latest/dist/",
);
await page.setContent(`
<script src="browser.script.iife.js"></script>
<script type="text/ruby" data-eval="async">
require 'js/require_remote'
JS::RequireRemote.instance.base_url = 'fixtures/recursive_require'
JS::RequireRemote.instance.load 'b'
JS.global.checkResolved RecursiveRequire::B.new.message
</script>
`);

expect(await resolve()).toBe("Hello from RecursiveRequire::B");
});
});
}

0 comments on commit f4dafaa

Please sign in to comment.