Use ESM in a service worker file (import/export) - javascript

I am trying to use a service worker file which is also an ESM module.
The register method has an extra argument accepting an options object which has a type field whose valid values seem to be classic and module, but when I use:
navigator.serviceWorker.register('worker.js', { type: 'module' });
// `worker.mjs` doesn't work either
// The file exists in both cases!
I get an unspecified DOMException with no message in Chrome.
I figured what the valid values for type were by reading the spec, specifically this:
https://html.spec.whatwg.org/multipage/workers.html#workertype
It seems to me like my code is valid.
As a sanity check, I also tried to explicity set type to classic and the service worker registration then goes through fine. If I set it to an invalid value, I get a TypeError telling me so, so it's not like the browser is not yet aware of type: module. It is treated as a special case, it just throws a DOMException with no message.
Am I using the type field correctly? Is it still too early and it is not supported in browsers?

This is dumb! Chrome will print just DOMException into the console (not even expansible) when logging the error object and Object.keys on that object instance returns [], but when I specifically print e.message the culprit is revealed:
type 'module' in RegistrationOptions is not implemented yet.See https://crbug.com/824647 for details.
Not amused by Chrome.

On browsers, bare names can't be used to identify modules unless you also have a module map (aka import map, this link has much more info) that maps the bare name to a module.
If worker.js is in the same location as the page loading it, then:
navigator.serviceWorker.register('./worker.js', { type: 'module' });
// -------------------------------^^
Or of course, add a module map.

Related

How can I instantiate a new SystemError object in Node.js?

Looking at Node's documentation, SystemError extends the Error class. However, if you attempt to use SystemError directly, Node will throw a ReferenceError saying that SystemError is undefined.
Clearly, according to the docs, it is possible to encounter an instance of SystemError, but it seems impossible to recreate such an error in the usual way (e.g. throw new SystemError(args)).
I would like to test some code which is designed to interact with the specified SystemError API as detailed in the docs, but I have no idea how to recreate a SystemError. Is this even possible?
I think that node.js doesn't put SystemError available in order to avoid anyone (npm packages) to use it. So a SystemError is really a SystemError and not something else.
If you want to test it, generate the error : Try to read a file that doesn't exist for example.
An other soluce would be to recreate a lookalike error because you know every property of it. But it's a workaround actually.
https://nodejs.org/api/errors.html#errors_class_systemerror
In the Github https://github.com/DefinitelyTyped/DefinitelyTyped I couldn't find any interface declaration of SystemError.
Except custom implementations made by node-fetch, voximplant-websdk and alexa-sdk.
https://github.com/DefinitelyTyped/DefinitelyTyped/search?q=systemError&unscoped_q=systemError

Suppress "cannot instantiate non-constructor" warning

Using the Closure Compiler,I get the warning:
cannot instantiate non-constructor
This is just a warning and the code runs fine. Still, I hate having warnings that I know have no affect on the app. Some of the code where this warning occurs is from third party libraries but some of it is from my own.
Is there a way to just suppress this warning?
You can use this option:
--warnings_whitelist_file VAL : A file containing warnings to
suppress. Each line should be of the
form
<file-name>:<line-number>?
<warning-description> (default: )
This might be useful to suppress warnings from the 3rd party code:
--hide_warnings_for VAL : If specified, files whose path
contains this string will have their
warnings hidden. You may specify
multiple.
There is also this:
--warning_level (-W) [QUIET | DEFAULT : Specifies the warning level to use.
| VERBOSE] Options: QUIET, DEFAULT, VERBOSE
(default: DEFAULT)
To see the complete list of available options execute a command like this:
java -jar ../closure-compiler/target/closure-compiler-1.0-SNAPSHOT.jar --help
Note however that you are passing up some of the benefits of Closure Compiler for doing type-checking on your code. If you provide more details about the error and where in the code it happened I might be able to suggest the annotation to use there.
For you own code, either use ES2015 class syntax, or add #constructor annotations to function constructors. This tells the compiler that the function is intended to be called with the new operator.
For 3rd party code, hiding the warning is the best you can do.

Prevent Javascript calling Typescript without error

Suppose, I am writing a library with Typescript. There is a function with following signature-
function check(value: "YES"|"NO"): boolean
So, when this function is called from other typescript files with values other than "YES" or "NO", there will be a compilation error. But if called from a Javascript file, there will be no error, as Javascript do not has the type information. I can check for invalid values inside my function and throw errors. But then the type safety provided by Typescript seems only an illusion to me.
What should I do in this case as a library developer? Go with pure javascript? What did the teams like Angular do?
This is the difference between build-time (compile-time) and run-time error checking. TypeScript only helps you with Build-time checks. Providing a TypeScript Definition File with your library will help you users get meaningful compile-time errors when they use your lib incorrectly.
If your lib is being consumed by JavaScript directly, you'll have no build-step to notify the user, and you'll have to resort to run-time messaging. If file size is not an issue, I'd suggest throwing a meaningful error message:
function (check) {
if (check != "YES" && check != "NO")
throw new Error("Invalid Check Value: " + check);
...
}
If you are concerned about file size, probably best to simply no-op on invalid calls. Or have some sort of sensible default. It will depend on your situation.
You could also consider a "debug" build of your library that provides error messages, but exclude them from the minified release build.

How does assert (req.assert) work in nodejs

I am currently working on MEAN stack using node, express and angularjs. I downloaded boiler plate code from mean.io and also using debugger while I explore the code.
In the controller which gets req and res as parameters, how does req.assert work?
In the file server/controllers/users.js
req.assert('username', 'Username cannot be more than 20 characters').len(1,20);
adds into validation error even when the username is empty or null. How do I check for current username value in the req? Where is the assert function of req defined.
I come from java background and find it tricky to find the function code some times as I wont be sure about where is it defined and how is it prototyped. How does one properly read the objects and browse the functions that are being used in javascript?
It's defined in Express's dependency express-validator. Check here: https://github.com/ctavan/express-validator/blob/master/lib/express_validator.js
which depends on validator:
https://github.com/chriso/validator.js
Accepted answer refers to what is now the Legacy API hence broken links.
Check out the documentation for Sanitization and the available sanitizing tools. You can make custom validators in there.

Anchor element's pathname returns undefined in Rhino with env.js

I have run into an issue that I believe is rooted in the implementation of anchor tags in Rhino. Although I am utilizing env.js, I suspect perhaps I am not configuring something correctly.
In particular, my issue occurs while I am attempting to write unit tests against code written for an angularjs application. When I include angular.js (versions 1.2.1 to present), I get the following error:
TypeError: Cannot call method "charAt" of undefined
I am convinced the error is the result of this call to urlParsingNode.pathname since a console.log call reveals that the pathname object is undefined.
I traced the instantiation of the urlParsingNode to this line where we see that it is the result of a call to document.createElement("a"); Further down, we see that they set the href attribute in this line in hopes that the created anchor tag will utilize the browser to correctly parse the URL.
I have to believe I'm not the first to attempt JS unit testing for angular via Rhino, but thus far I've not successfully Googled myself to a solution. Any tips will be greatly appreciated.
Found it and fixed it. The pathname getter/setter simply was undefined for HTMLAnchorElement in env.js.
I submitted a pull request, but unfortunately the project looks all but abandoned. I also couldn't figure out how to build it out to a single file. It appears perhaps someone has taken it upon themselves to break it apart into require.js modules. Not a battle worth fighting for my use case.
So for anyone else who hits this issue, I have the code you need below. It belongs in the HTMLAnchorElement.prototype. In my copy of env.js 1.2, this prototype begins on line 8075. I added the following at line 8118.
get pathname() {
var uri = Envjs.urlsplit(this.href);
return uri.path;
},
set pathname(val) {
var uri = Envjs.urlsplit(this.href);
uri.path = val
this.href(uri.urlunsplit(uri));
},
FYI, my particular issue is resolved with this pull request.

Categories