1. Definitions
A specifier map is an ordered map from strings to lists of URLs .
A import map is a struct with two items :
-
imports , a specifier map , and
-
scopes , an ordered map of URLs to specifier maps .
An empty import map is an import map with its imports and scopes both being empty maps.
2. Acquiring import maps
2.1. New members of environment settings objects
Each
environment
settings
object
will
get
an
import
map
algorithm,
which
returns
an
import
map
created
by
parsing
and
merging
all
the
first
<script
type="importmap">
elements
element
that
are
is
encountered
(before
the
cutoff).
A
Document
has
an
import
map
import
map
.
It
is
initially
a
new
empty
import
map
.
In
set
up
a
window
environment
settings
object
,
settings
object
’s
import
map
returns
the
import
map
of
window
’s
associated
Document
.
A
WorkerGlobalScope
has
an
import
map
import
map
.
It
is
initially
a
new
empty
import
map
.
Specify
a
way
to
set
WorkerGlobalScope
's
import
map
.
We
might
want
to
inherit
parent
context’s
import
maps,
or
provide
APIs
on
WorkerGlobalScope
,
but
we
are
not
sure.
Currently
it
is
always
an
empty
import
map
.
See
#2
.
In set up a worker environment settings object , settings object ’s import map returns worker global scope ’s import map .
This infrastructure is very similar to the existing specification for module maps.
A
Document
has
a
list
of
pending
import
map
scripts
script
,
which
is
a
list
of
HTMLScriptElement
s,
or
null,
initially
empty.
null.
HTMLScriptElement
s
are
added
to
this
list
This
is
modified
by
§ 2.3
Prepare
a
script
.
Each
Document
has
an
acquiring
import
maps
boolean.
It
is
initially
true.
-
Import maps areAn import map is accepted if and only ifthey areit is added (i.e.,theirits correspondingscriptelements areelement is added) before the first module load is started, even if the loading of the import mapfiles don’tfile doesn’t finish before the first module load is started. -
Module
loading
waits
for
any
import
mapsmap thathavehas already startedloading, if any.loading.
2.2. Script type
To process import maps in the prepare a script algorithm consistently with existing script types (i.e. classic or module), we make the following changes:
-
Introduce import map parse result , which is a struct with three items :
-
a settings object , an environment settings object ;
-
an import map , an import map ; and
-
an error to rethrow , a JavaScript value representing a parse error when non-null.
-
-
the script’s type should be either "
classic", "module", or "importmap". -
Rename the script’s script to the script’s result , which can be either a script or an import map parse result .
The following algorithms are updated accordingly:
-
execute a script block Step 4: add the following case.
-
"
importmap" -
-
Assert: Never reached.
Import maps are processed by register an import map instead of execute a script block .
-
-
"
Because we don’t make import map parse result the new subclass of script , other script execution-related specs are left unaffected.
2.3. Prepare a script
Inside the prepare a script algorithm, we make the following changes:
-
Insert the following step to prepare a script step 7, under "Determine the script’s type as follows:":
-
If the script block’s type string is an ASCII case-insensitive match for the string "
importmap", the script’s type is "importmap".
-
-
Insert the following step before prepare a script step 24:
-
If the script’s type is "
importmap"", and either the element’s node document’s's acquiring import maps isfalse,false or the element’s node document 's pending import map script is non-null, then queue a task to fire an event namederrorat the element, and return.Alternative considered: We can proceed to import map loading unlessIn thescript is ready for all HTMLScriptElement in listfuture we could losen the constrain of erroring when the pending import mapscripts , even when acquiring import mapsscript isfalse, because at that time subsequent module loading is blocked and new import map loads could be still added. This wouldnon-null, to allowa few more opportinities for adding import maps, but this would highly depend on the timing of network loading. For example, if the preceding import map load finishes earlier than expected, then subsequentmultiple importmaps depending on this behavior might fail. To avoid this kind of nondeterminism, we didn’t choose this option, at least for now.maps.
-
-
Insert the following case to prepare a script step 24.6:
-
"
importmap" - Fetch an import map given url , settings object , and options .
-
"
-
Insert the following case to prepare a script step 25.2:
-
"
importmap" -
-
Let import map parse result be the result of create an import map parse result , given source text , base URL and settings object .
-
Set the script’s result to import map parse result .
-
-
"
-
Insert the following case to prepare a script step 26:
-
If
the
script’s
type
is
"
importmap" -
Append the element toSet the element’s node document’s list of's pending import mapscripts .script to the element. When the script is ready , run the following steps:-
Repeat while the list of pending import map scripts is not empty and the first entry’s the script is ready :Register an import map given thefirst element of list ofpending import mapscriptsscript . -
RemoveSet thefirst element of list ofpending import mapscripts .script to null.If this makes the list of pending import map scripts empty, itThis will (asynchronously) unblock any wait for import maps algorithm instances.
-
-
If
the
script’s
type
is
"
This
is
specified
similar
to
the
list
of
scripts
that
will
execute
in
order
as
soon
as
possible
,
to
register
import
maps
and
fire
error
events
in
order
(
list
of
scripts
that
will
execute
in
order
as
soon
as
possible
is
rarely
used
in
the
wild
though).
There
can
be
other
alternatives,
e.g.
executing
a
similar
loop
inside
wait
for
import
maps
.
This algorithm is specified consistently with fetch a single module script steps 5, 7, 8, 9, 10, and 12.1. Particularly, we enforce CORS to avoid leaking the import map contents that shouldn’t be accessed.
-
Let request be a new request whose url is url , destination is "
script", mode is "cors", referrer is "client", and client is settings object .Here we use "
script" as the destination , which means thescript-src-elemCSP directive applies. -
Set up the module script request given request and options .
-
Fetch request . Return from this algorithm, and run the remaining steps as part of the fetch’s process response for the response response .
response is always CORS-same-origin .
-
If any of the following conditions are met, asynchronously complete this algorithm with null, and abort these steps:
-
response ’s type is "
error" -
The result of extracting a MIME type from response ’s header list is not
"application/importmap+json"
-
-
Let source text be the result of UTF-8 decoding response’s body .
-
Asynchronously complete this algorithm with the result of create an import map parse result , given source text , response ’s url , and settings object .
2.4. Wait for import maps
-
If settings object ’s global object is a
Windowobject:-
Let document be settings object ’s global object 's associated
Document. -
Set document ’s acquiring import maps to false.
-
Spin the event loop until document ’s
list ofpending import mapscriptsscript isempty.null.
-
-
Asynchronously complete this algorithm.
No
actions
are
specified
for
WorkerGlobalScope
because
for
now
there
are
no
mechanisms
for
adding
import
maps
to
WorkerGlobalScope
.
Insert a call to wait for import maps at the beginning of the following HTML spec concepts.
-
fetch a module worker script graph (using module map settings object )
import:
URLs,
we
would
instead
use
fetch
client
settings
object
.
This
only
affects
fetch
a
module
worker
script
graph
,
where
these
two
settings
objects
are
different.
And,
given
that
the
import
maps
for
WorkerGlobalScope
s
are
currently
always
empty,
the
only
fetch
that
could
be
impacted
is
that
of
the
initial
module.
But
even
that
would
not
be
impacted,
because
that
fetch
is
done
using
URLs,
not
specifiers.
So
this
is
not
a
future
compatibility
hazard,
just
something
to
keep
in
mind
as
we
develop
import
maps
in
module
workers.
import(unresolvableSpecifier)
might
behave
differently
between
a
HTML-spec-
and
Fetch-spec-based
import
maps.
In
particular,
in
the
current
draft,
acquiring
import
maps
is
set
to
false
after
an
import()
-initiated
failure
to
resolve
a
module
specifier
,
thus
causing
any
later-encountered
import
maps
to
cause
an
error
event
instead
of
being
processed.
Whereas,
if
wait
for
import
maps
was
called
as
part
of
the
Fetch
spec,
it’s
possible
it
would
be
natural
to
specify
things
such
that
acquiring
import
maps
remains
true
(as
it
does
for
cases
like
<script
type="module"
src="http://:invalidurl">
).
This should not be much of a compatibility hazard, as it only makes esoteric error cases into successes. And we can always preserve the behavior as specced here if necessary, with some potential additional complexity.
2.5. Registering an import map
HTMLScriptElement
element
:
-
If element ’s the script’s result is null, then fire an event named
errorat element , and return. -
Let import map parse result be element ’s the script’s result .
-
Assert: element ’s the script’s type is "
importmap". -
Assert: import map parse result is an import map parse result .
-
Let settings object be import map parse result ’s settings object .
-
If element ’s node document ’s relevant settings object is not equal to settings object , then return.
This is spec’ed consistently with whatwg/html#2673 .
Currently we don’t fire
errorevents in this case. If we change the decision at whatwg/html#2673 to fireerrorevents, then we should change this step accordingly. -
If import map parse result ’s error to rethrow is not null, then:
-
Report the exception given import map parse result ’s error to rethrow .
There are no relevant script , because import map parse result isn’t a script . This needs to wait for whatwg/html#958 before it is fixable.
-
Return.
-
-
UpdateSet element ’s node document 's import mapwithto import map parse result ’s import map . -
If element is from an external file , then fire an event named
loadat element .
The
timing
of
register
an
import
map
is
observable
by
possible
error
and
load
events,
or
by
the
fact
that
after
register
an
import
map
an
import
map
script
can
be
moved
to
another
Document
.
On
the
other
hand,
the
updated
import
map
is
not
observable
until
wait
for
import
maps
completes.
3. Parsing import maps
-
Let parsed be the result of parsing JSON into Infra values given input .
-
If parsed is not a map , then throw a
TypeErrorindicating that the top-level value must be a JSON object. -
Let sortedAndNormalizedImports be an empty map .
-
If parsed ["
imports"] exists , then:-
If parsed ["
imports"] is not a map , then throw aTypeErrorindicating that the "imports" top-level key must be a JSON object. -
Set sortedAndNormalizedImports to the result of sorting and normalizing a specifier map given parsed ["
imports"] and baseURL .
-
-
Let sortedAndNormalizedScopes be an empty map .
-
If parsed ["
scopes"] exists , then:-
If parsed ["
scopes"] is not a map , then throw aTypeErrorindicating that the "scopes" top-level key must be a JSON object. -
Set sortedAndNormalizedScopes to the result of sorting and normalizing scopes given parsed ["
scopes"] and baseURL .
-
-
If parsed ’s keys contains any items besides "
imports" or "scopes", report a warning to the console that an invalid top-level key was present in the import map.This can help detect typos. It is not an error, because that would prevent any future extensions from being added backward-compatibly.
-
Return the import map whose imports are sortedAndNormalizedImports and whose scopes scopes are sortedAndNormalizedScopes .
-
Let import map be the result of parse an import map string given input and baseURL . If this throws an exception, let error to rethrow be the exception. Otherwise, let error to rethrow be null.
-
Return an import map parse result with settings object is settings object , import map is import map , and error to rethrow is error to rethrow .
<https://example.com/base/page.html>
,
the
input
{ "imports" : { "/app/helper" : "node_modules/helper/index.mjs" , "lodash" : "/node_modules/lodash-es/lodash.js" } }
will generate an import map with imports of
«["https://example.com/app/helper" → « <https://example.com/base/node_modules/helper/index.mjs> », "std:kv-storage" → « <std:kv-storage>, <https://example.com/base/node_modules/kv-storage-polyfill/index.mjs> »"https://example.com/app/helper" → <https://example.com/base/node_modules/helper/index.mjs> "lodash" → <https://example.com/node_modules/lodash-es/lodash.js> ]»
and (despite nothing being present in the input) an empty map for its scopes .
-
Let normalized be an empty map .
-
First, normalize all entries so that their values are lists .For each specifierKey → value of originalMap ,-
Let normalizedSpecifierKey be the result of normalizing a specifier key given specifierKey and baseURL .
-
If normalizedSpecifierKey is null, then continue .
-
If value is
a string , then set normalized [ normalizedSpecifierKey ] to « value ». Otherwise, if value is null, then set normalized [ normalizedSpecifierKey ] to a new empty list. Otherwise, if value is a list , then set normalized [ normalizedSpecifierKey ] to value . Otherwise, report a warning to the console that addresses must be strings, arrays, or null. Next, normalize and validate each potential address in the value lists . For each specifierKey → potentialAddresses of normalized , Assert: potentialAddresses is a list , because of the previous normalization pass. Let validNormalizedAddresses be an empty list . For each potentialAddress of potentialAddresses , If potentialAddress isnot a string , then:-
Report a warning to the console that
the contents of address arraysaddresses must be strings. -
Continue .
-
-
Let addressURL be the result of parsing a URL-like import specifier given
potentialAddressvalue and baseURL . -
If addressURL is null, then:
-
Report a warning to the console that the address was invalid.
-
Continue .
-
-
If specifierKey ends with U+002F (/), and the serialization of addressURL does not end with U+002F (/), then:
-
Report a warning to the console that an invalid address was given for the specifier key specifierKey ; since specifierKey ended in a slash, so must the address.
-
Continue .
-
-
Append addressURL to validNormalizedAddresses .Set normalized [ specifierKey ] tovalidNormalizedAddressesaddressURL .
-
-
Return the result of sorting normalized , with an entry a being less than an entry b if a ’s key is longer or code unit less than b ’s key .
-
Let normalized be an empty map .
-
For each scopePrefix → potentialSpecifierMap of originalMap ,
-
If potentialSpecifierMap is not a map , then throw a
TypeErrorindicating that the value of the scope with prefix scopePrefix must be a JSON object. -
Let scopePrefixURL be the result of parsing scopePrefix with baseURL as the base URL.
-
If scopePrefixURL is failure, then:
-
Report a warning to the console that the scope prefix URL was not parseable.
-
Continue .
-
-
If scopePrefixURL ’s scheme is not a fetch scheme , then:
-
Report a warning to the console that scope prefix URLs must have a fetch scheme.
-
Continue .
-
-
Let normalizedScopePrefix be the serialization of scopePrefixURL .
-
Set normalized [ normalizedScopePrefix ] to the result of sorting and normalizing a specifier map given potentialSpecifierMap and baseURL .
-
-
Return the result of sorting normalized , with an entry a being less than an entry b if a ’s key is longer or code unit less than b ’s key .
-
If specifierKey is the empty string, then:
-
Report a warning to the console that specifier keys cannot be the empty string.
-
Return null.
-
-
Let url be the result of parsing a URL-like import specifier , given specifierKey and baseURL .
-
If url is not null, then return the serialization of url .
-
Return specifierKey .
-
If specifier starts with "
/", "./", or "../", then:-
Let url be the result of parsing specifier with baseURL as the base URL.
-
If url is failure, then return null.
One way this could happen is if specifier is "
../foo" and baseURL is adata:URL. -
Return url .
-
-
Let url be the result of parsing specifier (with no base URL).
-
If url is failure, then return null.
-
If url ’s scheme is
eithera fetch schemeor " std ",, then return url . -
Return null.
4. Resolving module specifiers
4.1. New "resolve a module specifier"
-
Let settingsObject be the current settings object .
-
Let baseURL be settingsObject ’s API base URL .
-
If referringScript is not null, then:
-
Set settingsObject to referringScript ’s settings object .
-
Set baseURL to referringScript ’s base URL .
-
-
Let importMap be settingsObject ’s import map .
-
Let
moduleMap be settingsObject ’s module map . LetbaseURLString be baseURL , serialized . -
Let asURL be the result of parsing a URL-like import specifier given specifier and baseURL .
-
Let normalizedSpecifier be the serialization of asURL , if asURL is non-null; otherwise, specifier .
-
For each scopePrefix → scopeImports of importMap ’s scopes ,
-
If scopePrefix is baseURLString , or if scopePrefix ends with U+002F (/) and baseURLString starts with scopePrefix , then:
-
Let scopeImportsMatch be the result of resolving an imports match given normalizedSpecifier
, scopeImports ,andmoduleMapscopeImports . -
If scopeImportsMatch is not null,
then: Validate the module script URL given scopeImportsMatch , settingsObject , and baseURL . Returnthen return scopeImportsMatch .
-
-
-
Let topLevelImportsMatch be the
reusltresult of resolving an imports match given normalizedSpecifier,and importMap ’s imports, and moduleMap .. -
If topLevelImportsMatch is not null,
then: Validate the module script URL given topLevelImportsMatch , settingsObject , and baseURL . Returnthen return topLevelImportsMatch . -
At this point, the specifier was able to be turned in to a URL, but it wasn’t remapped to anything by importMap .
If asURL is not null,then: Validate the module script URL given asURL , settingsObject , and baseURL . Returnthen return asURL . -
Throw a
TypeErrorindicating that specifier was a bare specifier, but was not remapped to anything by importMap .
-
For each specifierKey →
addressesaddress of specifierMap ,-
If specifierKey is normalizedSpecifier ,
then: If addresses ’s size is 0, then throw a TypeError indicating that normalizedSpecifier was mapped to no addresses. If addresses ’s size is 1, then: Let singleAddress be addresses [0]. If singleAddress ’s scheme is " std ", and moduleMap [ singleAddress ] does not exist ,thenthrow a TypeError indicating that the requested built-in module is not implemented. Return singleAddress . If addresses ’s size is 2, and addresses [0]'s scheme is " std ", and addresses [1]'s scheme is not " std ", then: Return addresses [0], if moduleMap [ addresses [0]] exists ; otherwise,returnaddresses [1]. Otherwise, we have no specification for more complicated fallbacks yet; throw a TypeError indicating this is not yet supported .address . -
If specifierKey ends with U+002F (/) and normalizedSpecifier starts with specifierKey , then:
-
If addresses ’s size is 0, then throw a TypeError indicating that normalizedSpecifier was mapped to no addresses. If addresses ’s size is 1, then:Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix. -
Assert: afterPrefix ends with "
/", as enforced during parsing . -
Let url be the result of parsing
the concatenation of the serialization of addresses [0] with afterPrefix . We parse the concatenation, instead of parsingafterPrefix relative toaddresses [0], due to cases such as an afterPrefix of " switch " and an addresses [0] of " std:elements/ ". Assert: url is not failure, since addresses [0] was a URL, and appending afterthetrailing " / " will not make it unparseable. Returnbase URLurladdress . -
If
addresses ’s size is 2, and addresses [0]'s scheme is " std ", and addressesurl[1]'s schemeisnot " std ", then: Let afterPrefix be the portion of normalizedSpecifier after the initial specifierKey prefix. Assert: afterPrefix ends with " / ", as enforced during parsing . Let url0 be the result of parsing the concatenation of the serialization of addresses [0] with afterPrefix ; similarly, let url1 be the result of parsing the concatenation of the serialization of addresses [1] with afterPrefix . As above, we parse the concatenation to deal with built-in module cases. Assert: neither url0 nor url1 arefailure,since addresses [0] and addresses [1] were URLs, and appending after their trailing " / " will not make them unparseable.then return null. -
Return
url0 , if moduleMap [ url0 ] exists ; otherwise, return url1url .
Otherwise, we have no specification for more complicated fallbacks yet; throw a TypeError indicating this is not yet supported . -
-
-
Return null.
4.2. Updates to other algorithms
All call sites of HTML’s existing resolve a module specifier will need to be updated to pass the appropriate script , not just its base URL . Some particular interesting cases:
-
HostResolveImportedModule and HostImportModuleDynamically no longer need to compute the base URL themselves, as resolve a module specifier now handles that.
-
Fetch an import() module script graph will also need to take a script instead of a base URL.
Call
sites
will
also
need
to
be
updated
to
account
for
resolve
a
module
specifier
now
throwing
exceptions,
instead
of
returning
failure.
(Previously
most
call
sites
just
turned
failures
into
TypeError
s
manually,
so
this
is
straightforward.)