@@ -6,12 +6,17 @@ const {
6
6
} = primordials ;
7
7
8
8
const {
9
- ERR_IMPORT_ASSERTION_DISALLOWED ,
10
- ERR_IMPORT_ASSERTION_INVALID ,
11
- ERR_IMPORT_ASSERTION_MISSING ,
12
- ERR_UNKNOWN_MODULE_FORMAT ,
9
+ ERR_IMPORT_ASSERTION_TYPE_FAILED ,
10
+ ERR_IMPORT_ASSERTION_TYPE_MISSING ,
11
+ ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED ,
13
12
} = require ( 'internal/errors' ) . codes ;
14
13
14
+ /**
15
+ * Define a map of module formats to import assertion types (the value of `type` in `assert { type: 'json' }`).
16
+ * A value of `false` means that the presence of an import assertion type for this format should throw an error.
17
+ * This matches browser behavior, where `import('data:text/javascript,export{}', { assert: { type: 'javascript' } })` throws.
18
+ * @type {Map<string, string | false }
19
+ */
15
20
const formatTypeMap = new SafeMap ( [
16
21
[ 'builtin' , false ] ,
17
22
[ 'commonjs' , false ] ,
@@ -22,26 +27,24 @@ const formatTypeMap = new SafeMap([
22
27
23
28
24
29
function validateAssertions ( format , importAssertions ) {
25
- let validType ;
26
- try {
27
- validType = formatTypeMap . get ( format ) ;
28
- } catch {
29
- throw new ERR_UNKNOWN_MODULE_FORMAT ( format ) ;
30
- }
30
+ const validType = formatTypeMap . get ( format ) ;
31
31
32
- if ( validType === false ) {
32
+ if ( validType === undefined ) {
33
+ // Ignore assertions for module types we don’t recognize, to allow new formats in the future
34
+ return true ;
35
+ } else if ( validType === false ) {
33
36
if ( ! importAssertions ||
34
37
! ObjectPrototypeHasOwnProperty ( importAssertions , 'type' ) ) {
35
38
return true ;
36
39
}
37
- throw new ERR_IMPORT_ASSERTION_DISALLOWED ( format ) ;
40
+ throw new ERR_IMPORT_ASSERTION_TYPE_UNSUPPORTED ( format , validType ) ;
38
41
} else {
39
42
if ( validType === importAssertions ?. type ) {
40
43
return true ;
41
44
} else if ( ! ObjectPrototypeHasOwnProperty ( importAssertions , 'type' ) ) {
42
- throw new ERR_IMPORT_ASSERTION_MISSING ( format , 'type' , validType ) ;
45
+ throw new ERR_IMPORT_ASSERTION_TYPE_MISSING ( format , validType ) ;
43
46
} else {
44
- throw new ERR_IMPORT_ASSERTION_INVALID ( format , 'type' , validType ) ;
47
+ throw new ERR_IMPORT_ASSERTION_TYPE_FAILED ( format , validType ) ;
45
48
}
46
49
}
47
50
}
0 commit comments