When editing in VSCode, if a JS file imports ESM exports from another a node_modules library, if that library is in JS, then type declarations are required for type hinting? If the node_modules library is in TS, are type declarations required for type hinting?

Here’s a comprehensive explanation:

When a JS file imports ESM exports from a Node.modules library:

  • If the library is in JS:

    • Type declarations are needed for type hinting in VS Code.
    • Methods to provide type declarations:
      1. Library-provided types:
        • Check if the library includes its own types, often in a @types or dist directory. Install them using npm or yarn.
      2. DefinitelyTyped:
        • Search for community-maintained types on DefinitelyTyped. Install using @types/<library-name>.
      3. Create manual type declarations:
        • If types aren’t available, create a .d.ts file with type definitions for the library’s exports.
  • If the library is in TypeScript:

    • Type declarations are typically not required.
    • VS Code can infer types directly from the library’s TypeScript code.

Key points for optimal type hinting experience:

  • Enable the TypeScript extension in VS Code.
  • Configure VS Code to discover type declarations:
    • Set typeRoots in jsconfig.json or tsconfig.json to include node_modules/@types.
  • Consider using a type checker for enhanced type safety and linting:
    • Explore ESLint with TypeScript plugins or standalone type checkers like TypeScript ESLint or tsc.

Additional tips:

  • Keep type declarations up-to-date:
    • Ensure they match library versions for accuracy.
  • Leverage VS Code’s IntelliSense for guidance:
    • Utilize code completion, hover information, and error checking for efficient coding.
  • Explore advanced features:
    • Type search (Cmd+T or Ctrl+T), go to type definition (F12), type hierarchy exploration, and more.

Why do I need a TypeScript declaration file for a JavaScript library even though type checking works in VSCode in own library?

The following is an AI chat conversation regarding the topic stated in the title.
Depending on the quality of the conversation, modifications may have been made. Modifications may or may not be stated in this page.


Why do I need to generate a declaration file for a javascript library in order to get type hinting in VSCode when I use that library in another project? VSCode can already get types of JS file in the same project. So why does this change when importing from an external library?

Here’s a breakdown of why declaration files are required for type hinting in VSCode when using external JavaScript libraries:

1. JavaScript’s Dynamic Nature:

  • JavaScript is dynamically typed, meaning type information isn’t explicitly included in the code itself. This flexibility makes it harder for editors to infer types accurately, especially for external code.

2. VSCode’s Type Hinting Reliance:

  • VSCode heavily relies on type information for features like:
    • IntelliSense (code completion, suggestions)
    • Hover information
    • Parameter and type checking
    • Refactoring tools

3. Separate Project Scope:

  • When a library is in a separate project, VSCode can’t directly analyze its source code to infer types. Declaration files (.d.ts) bridge this gap.

4. Declaration Files:

  • They describe the types of variables, functions, and classes within a library.
  • They’re written in TypeScript, a superset of JavaScript with explicit typing.
  • VSCode can leverage them for type hinting even in JavaScript projects.

5. Type Acquisition Methods:

  • Automatic: VSCode tries to automatically fetch declaration files for popular libraries.
  • Manual: Install declaration files from DefinitelyTyped (a community repository): npm install --save-dev @types/<library-name>
  • Generating: Compile a library’s TypeScript source code or use tools to create .d.ts files from JSDoc comments.

Key Points:

  • Declaration files are essential for type-aware features in VSCode when using external JavaScript libraries.
  • They make your code more readable, maintainable, and less prone to type-related errors.
  • Consider using TypeScript for new projects to enjoy strong typing and type safety from the start.

The HTMLMediaElement (

The HTMLMediaElement (Mainly <video> and <audio>) contains a “volume” property.
This property is set by the browser and seems to have a default value of max (1.0).
This “volume” property can be modified via JavaScript, by simply set a valid value between 0 and 1.
It seems that it is sometimes altered on videos such as in YouTube adverts.
The reason for this is described in the AI conversation I shared below. To summarize, advert owners seem to have the ability to change the volume.


The following is an AI chat conversation regarding the topic stated in the title.
Depending on the quality of the conversation, modifications may have been made. Modifications may or may not be stated in this page.


There is a “volume” property on HTMLMediaElement elements. It can be modified. When playing a YouTube video, I checked the value, and it was 0.4415704270182424. Is this value the default value? Can this value be changed at a browser or browser extension level? Can this value be changed at an OS level? Why is this valued used, and not a max value of 1?

No, the value you observed (0.4415704270182424) is not the default value for the volume property on HTMLMediaElement elements. The default value is 1.0, which represents the maximum volume.

Here’s a breakdown of your questions:

Can this value be changed at a browser or browser extension level?

  • Yes, the volume property can be changed through both browser settings and browser extensions. Browsers usually have volume controls built-in, and many extensions offer additional functionalities like volume normalization or specific volume adjustments for certain websites.

Can this value be changed at an OS level?

  • Yes, most operating systems have system-wide volume controls that apply to all applications, including web browsers. Adjusting the system volume will also affect the volume of HTML media elements.

Why is this value used, and not a max value of 1?

There are a few reasons why the specific value you encountered might not be 1.0:

  • Initial volume setting: Some websites or video players might have a different initial volume setting than the browser default.
  • User interaction: The user might have previously adjusted the volume using the browser controls, an extension, or the system volume, resulting in the value you observed.
  • Automatic volume adjustments: Certain browser extensions or system settings might automatically adjust the volume based on various factors like ambient noise level or user preferences.

It’s important to note that while the volume property technically allows values between 0 (muted) and 1 (maximum), some browsers or extensions might use a different scale or apply additional logic, potentially leading to non-intuitive values like the one you observed.


The value was that when viewing an advert on YouTube. Was the value that because of being on YouTube, or the advert?

The observed value (0.4415704270182424) for the volume property in your case is likely not directly caused by being on YouTube itself, but rather due to the specific advertisement you were watching or previous user interaction. Here’s why:

  1. YouTube doesn’t automatically adjust volume: While some websites might have their own initial volume settings, YouTube itself doesn’t have a known feature that automatically adjusts the volume for specific content like advertisements.

  2. Advertisers control their content: Advertisements on YouTube are uploaded by individual companies or agencies. These entities have control over the audio levels within their ads, which could explain the specific volume level you observed.

  3. Past user interaction: As mentioned earlier, the volume property could have been previously adjusted through browser controls, extensions, or system settings, impacting the value you saw even during the ad.

Therefore, the specific value you encountered is more likely a combination of:

  • The volume level set within the advertisement itself.
  • Any previous volume adjustments you or your system made.

It’s important to note that while there are no regulations directly mandating specific volume levels for online advertisements, many users find sudden changes in volume disruptive. YouTube itself offers a feature called “Stable volume” that aims to reduce volume fluctuations between videos and ads. However, it’s ultimately left to individual advertisers to be mindful of their ad’s audio levels to create a positive user experience.

Tree shaking ES6 JavaScript code. Does tree-shaken bundle of single named export contain others of that file?

The following is an AI chat conversation regarding the topic stated in the title.
Depending on the quality of the conversation, modifications may have been made. Modifications may or may not be stated in this page.


When tree shaking ES6 JavaScript code, if I import a single named function from a file that exports multiple named functions, will the tree shaken code still contain the other named functions?

No, in most cases, tree shaking will remove the unused named functions from the final code. Here’s how it works:

  1. Static Analysis: Tree shaking tools like Webpack or Rollup analyze the module’s import statements. They create a dependency graph, mapping which exported functions are actually used by other modules.

  2. Unused Code Elimination: If a named function is not imported anywhere, tree shaking removes it from the final bundle. Only the necessary code for used functions is included.

Example:

JavaScript
// math.js
export function add(x, y) { return x + y; }
export function subtract(x, y) { return x - y; }

// main.js
import { add } from './math.js';

console.log(add(2, 3));
  • After tree shaking, subtract will be removed from the final code, as it’s not imported in main.js.

Important Considerations:

  • Tree shaking is most effective with direct named imports: While it generally works with named imports, it might be less effective with default imports or complex module structures.
  • Side Effects: Tree shaking cannot remove functions that have side effects, like modifying global state or accessing external resources, even if they’re not directly used. The bundler assumes they might be necessary for the application to function correctly.

Tips for Effective Tree Shaking:

  • Use named imports whenever possible.
  • Be mindful of side effects in exported functions.
  • Consider using bundler options like sideEffects: false in package.json to provide hints about modules that can be fully tree-shaken.
  • Use tools like Webpack Bundle Analyzer to visualize the generated bundle and identify optimization opportunities.

How to mark an npm project as for Node.js or for browser or for both?

One issue I have often run into when using npm packages is not supporting the browser.
It is common for even a simple utility package to have a dependency on an npm package and so only work in Node.js. It would be nice if this could be detected quickly, especially automatically.
I asked this question to Bard AI, and got a useful response. The response doesn’t solve the issue for all packages as it requires certain optional properties to be set, but if they are set, then it can be decided what environment support exists.

Is there a common or official way to mark an npm project as for usage of Node.js(not browser), vice-versa, and both?

Yes, there are two ways to mark an npm project as for usage of Node.js (not browser), vice-versa, and both.

  • Using the engines field in the package.json file. This is the official way to specify the runtime environment that a package requires. The engines field is a list of objects, each of which specifies a minimum version of a particular runtime environment. For example, to specify that a package requires Node.js 16 or later, you would add the following to the engines field:
"engines": {
  "node": ">=16"
}
  • Using the browserslist field in the package.json file. This field specifies the browsers that a package supports. If you want to specify that a package is only for Node.js, you would set the browserslist field to an empty array. For example:
"browserslist": []

If you want to specify that a package is for both Node.js and the browser, you would set the browserslist field to a list of browsers that the package supports. For example:

"browserslist": ["last 2 versions", "not ie <= 11"]

The browserslist field is used by the npm command to determine which packages to install when you run npm install. For example, if you have a package that is only for Node.js, and you run npm install, the npm command will only install the packages that are listed in the engines field.

I hope this helps! Let me know if you have any other questions.

IFrame src is not updating when frame URL changes. Why does this happen?

Recently, I have been using Bard quite a lot because it has proven to be quite helpful. This time it was so much better than searching Google and DuckDuckGo that I decided to share it in a post for everybody’s reference.

When the URL of an iframe is changed within the iframe, the iframe element’s “src” attribute does not change. What is the reasoning for this?

There are a few reasons why the iframe element’s src attribute does not change when the URL of an iframe is changed within the iframe.

First, it is important to remember that an iframe is a separate document from the parent document. When you change the URL of an iframe within the iframe, you are actually changing the URL of the embedded document, not the iframe element itself.

Second, the src attribute of an iframe element is read-only. This means that once the src attribute is set, it cannot be changed.

Finally, there is a security risk associated with allowing iframes to change their own src attribute. If an iframe were able to change its own src attribute, it could potentially load malicious content from a different domain.

To avoid these problems, if you need to change the URL of an iframe, you must do so from the parent document. You can do this using JavaScript to set the src attribute of the iframe element.

Here is an example of how to change the URL of an iframe using JavaScript:

JavaScript
// Get the iframe element
var iframe = document.getElementById('myIframe');

// Set the src attribute of the iframe element
iframe.src = 'https://new-url.com';

When you set the src attribute of an iframe element using JavaScript, the iframe will be reloaded with the new URL.

It is important to note that you can only change the URL of an iframe if the iframe is from the same domain as the parent document. If the iframe is from a different domain, you will need to use a cross-origin resource sharing (CORS) request to change the URL of the iframe.

Help with WebRTC, Webcams and getUserMedia.

WebRTC and rendering help.
This article provides help on video/audio streaming, webRTC troubleshooting, webcams, setup, and more.

Recommended environment

  • Development environment: Windows 8/10 + Chrome
  • Caution: Make sure to use the latest version of the browser you are using.
  • Supported browsers: Usually, in addition to Chrome, any Chromium based browser (For example: Brave, Edge, and more: https://en.wikipedia.org/wiki/Chromium_(web_browser)#Active) and Firefox is also supported. Firefox is usually very similar to Chrome, but small differences can sometimes lead to bugs and performance issues. ※ Update (2022/05/13): New versions of Edge use Chromium, so has generally the same features as Chrome.
  • IE: Internet Explorer should be avoided.
  • Other browsers: Old versions of Edge have better support than IE, but Chrome and Firefox are preferred. It is important to be especially aware that Edge used to use ORTC not WebRTC.
  • OS: There are usually no problems using another OS, but hardware related bugs may occur in rare circumstances.

Plugins and extensions

Internet Explorer(IE):

Does not support WebRTC, but there is a plugin for supporting WebRTC in IE: Temasys

Screenshare in Chrome:

At the time of writing this document, obtaining screen data in Chrome without an extension was not possible.

However, this is now (2022/05/13) possible using “getDisplayMedia”. Support for this can be checked in this getDisplayMedia Demo

API information can be found here: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia#examples

An extension can be independently developed, or a stream can be obtained by using the extension below.

How to use HTTPS required functions when using HTTP

Functions that might not reveal private data are progressively requiring encryption.
The best counter-measure for this is obviously to switch your website to https.

Details below:

However, if not supporting https, then the following counter-measures are available:

Use an old browser

Due to vulnerabilities and inconvenience, this method is NOT RECOMMENDED. If going to use this method, a limited secure environment(Local, single domain) should be used.
Information can be found below, but compared to previously, this method has become difficult.

It is necessary to find the installation file from before the function limitation was added from the app history page.

Https only support for getUserMedia happened in version 47 for Chrome and version 46 for Chromium.
The portable version is better than the installer version of Chromium to use because there is no auto-update
feature.
Use version 45 from the link below for the appropriate Chromium (Portable).
For the Installer version of Chromium, each is grouped by commit number, which is difficult to determine from the version number. Important versions are 45 and below (Commit number < 31****).

Https support changes for Firefox in the link above were posted in April 2015 so versions 35.0 and before should be fine.
However, at the time of writing(2017/08/09), it seems getUserMedia can still be used on HTTP pages.

Old browsers tend to have webRTC and getUserMedia bugs and specification differences, which may result in code not working.

Install file

Source

Flag permissions

Chromium: –allow-running-insecure-content
The flags below can be used. Refer to the links below for command line information:
–unsafely-treat-insecure-origin-as-secure
–use-fake-device-for-media-stream
–use-fake-ui-for-media-stream

Chromium:
https://peter.sh/experiments/chromium-command-line-switches/
Firefox:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
about:config

Setting exceptions via flags

Currently (2017/08/09), Chrome supports using flags, Firefox has no problems without flags.

Use another browser

Firefox can be used at the current time of writing (2017/08/09).
Functions only available in https for Chrome have been available using HTTP for a while in Firefox.
This is subject to change in the future.

Other

Counter-measure below for 「Secure Connection Failed」 in Firefox issue:
about:config
security.tls.insecure_fallback_hosts = 「www.domain.com」
https://superuser.com/questions/826232/how-to-bypass-the-secure-connection-failed-warning-in-firefox-33

Microphone/Webcam permissions

Due to this feature possibly revealing private information, please refer to “Permission required functions“.
The permissions mechanism allows separate access to device audio and video. Both simultaneously access the audio/video from the same and separate device is possible.
Depending on the environment, an error may occur if the function settings and the allowed device statuses do not match. If a problem occurs, both the settings and permission statuses should be checked.
Depending on the browser (Confirmed in Chrome), default devices may be available. This is not very useful for accessing media, but this may fix specific errors when you want to allow a media type but do not have the correct device.
The available permissions that can be selected may change depending on installed software (Audio management software).

Microphone/webcam problems

  • Fail to acquire audio from device with multiple functions: Depending on the browser(Occurred multiple times in Firefox), audio of a device can not be acquired. For
    example, both video and audio functionality exists for a webcam, but audio can not be acquired. In this case, there is a chance that the application will stop, depending on the source code. This can be solved by using a separate device for each function.
  • Unsupported browser: Check whether your browser can use getUserMedia: http://caniuse.com/#search=getusermedia
    Update to a new browser.
  • No device: There is a chance the device is not inserted. Please check the device is properly inserted.
  • The environment does not support the device: Check whether the device can be used on other websites.
    If the above fails, check whether it can be used in other browsers or elsewhere in the OS.
    If the device does not work on the OS, try reinstalling the drivers and contacting the manufacturer.

Permission required functions

Functions that might reveal private information often require permissions due to standardized specifications.
Permissions are mainly controlled via displaying upon execution, in-app flags or setting files.
The easiest method is “displaying upon execution”. When the function is executed, a pop-up should be displayed.
The selection made should be usable across the session. When on an https URL, it is common for the selection to be remembered.

Web camera environment

When using a webcam, the following is recommended to play clear video:

  • Brighten the room. When there is little light, the image quality becomes rough and loses sharpness. It especially causes issues for image recognition.

Microphone environment

When using a microphone, the following is recommended to play clear audio:

  • Do not output audio too close to the microphone. When audio is outputted too close to a microphone, the audio from the microphone is inputted into the microphone again, causing a howling effect.

WebGL support

Pages with a canvas (Image rendering functionality) often use WebGL. Even more so when rendering in 3D.
In order for the code to work and performance not to drop, WebGL should be enabled.

Chrome: chrome://flags/ Enabled by default, but should check each WebGL flag.
Firefox: about:config Make sure webgl.disabled = false + about:support WebGL rendering details are correct.

WebRTC issue report tools

WebRTC issue reporting

The following information should be provided when reporting WebRTC issues.
It becomes a lot easier to handle issues as more accurate data is provided.

  • OS (Including version number)
  • Browser (Including version number)
  • Web camera (Source of video)
  • Microphone (Source of audio)
  • Network speed
  • Network topology
  • Allowed and blocked ports for TCP and UDP
  • ICE Candidates log(If available)

WebRTC ports

WebRTC uses the following ports.

  • Signalling: 80 or 443
  • STUN/TURN: (default)3478, (Google STUN)19305 or 19307, (TLS)5349, (HTTP)80 or 443
  • P2P: 0~65535 (Often, 50000 and above)

Notes

Please consider trying out the Commew Web App for P2P communication, trying out WebRTC, testing out webcams, and more.