Skip to content

feat: add JsModuleInvokers and Page.executeModuleJs - #27492

Merged
mcollovati merged 17 commits into
mainfrom
feature/js-module-invokers
Nov 30, 2026
Merged

mcollovati merged 17 commits into
mainfrom
feature/js-module-invokers

Conversation

@totally-not-ai

@totally-not-ai totally-not-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Part of #27425

new feature · flow-server · apps and components that call what a JavaScript module exports, such as component connectors

Background — JavaScript definitions. A @JsDefinition interface declares JavaScript that the build bundles, so the server sends only a function id and nothing is compiled in the browser. @JsDefinitionImport gives that JavaScript names from a module.

Adds a third kind of definition that calls the exports of one module, with the module as this. A method without @JsExpression calls the export of the same name. This PR loads the modules on the first call, like other imports. The stacked PR on top loads them with the view, so calls run in order.

@JsDefinition
@JsDefinitionImport(from = "./grid-connector.js")
public interface GridConnectorJs extends JsModuleInvokers {
    void initLazy(Element grid); // return this.initLazy($0)
}
page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement());

Risks:

  • ⚠️ Public API: new JsModuleInvokers, Page.executeModuleJs, and a new constant MODULE_CALLS in the public JsDefinitionProxy.Kind enum, which can break an exhaustive switch over it in user code.

  • ⚠️ Behaviour change: the error for an interface that extends no marker, or more than one, has new wording, since there are now three markers.

  • ✅ No serialization, threading, security or migration concerns.

  • Added JsModuleInvokers, a marker that does not extend JsInvokers, so Element.executeJs refuses it at compile time.

  • Added Page.executeModuleJs(Class) and JsDefinitionProxy.createModuleInvokers.

  • checkDefinition refuses an interface that extends more than one marker, and a module definition whose declaring interfaces import zero or several modules without names. It also refuses a module definition annotated with @JsStringFallback, before the import checks, since a string call has no module as this.

  • The import without names is part of the hashed imports, so the same JavaScript run on an element stays a different function.

  • The generated function runs the JavaScript with that module as this.

  • Updated the Javadoc of @JsDefinition, @JsDefinitionImport (its example no longer shows connector code), @JsExpression, and the @throws that list the markers. JsModuleInvokers says that this is the module namespace object (named exports only, a default export is this.default, and it can not be changed), and @JsStringFallback says it can not mark a module definition. The Javadoc of Page.executeModuleJs says when to use it instead of Page.executeJs(Class) and lists what the interface needs, and the docs say that imports are not inherited, so each interface that declares methods of a module definition names its own module, and one that declares no methods must have no import. They also say that a detached Element argument arrives as null, and that a method that has to guard against it declares its JavaScript with @JsExpression. JsInvokers and JsSnippets now name JsModuleInvokers as the third marker. The @throws of the definition methods name the allowed return types.

  • When the build can not find the file of a module that a module definition imports, the methods its interface declares are left out of the bundle and each call throws an IllegalStateException that names the module, as for other imports. For the module that is this, that is every method the interface declares. The Javadoc of Page.executeModuleJs and JsModuleInvokers says so, and the build error for @JsDefinitionImport on a class now names JsModuleInvokers too.

  • Updated the wire-protocol and browser-integration guidelines to list Page.executeModuleJs(Class) and JsModuleInvokers.

  • Existing tests that checked the old wording of the marker errors now check the new wording.

  • Added a strict-CSP production IT that calls an export directly and through an expression.

Working on behalf of @mcollovati

A JavaScript definition that extends JsModuleInvokers calls what one
module exports, with that module as `this`. The module is named by the
one @JsDefinitionImport of the interface that imports no names; other
imports with names work as on a JsInvokers definition. A method without
@JsExpression calls the export of the same name.

The marker does not extend JsInvokers, so Element.executeJs refuses a
module definition at compile time. checkDefinition refuses an interface
that extends more than one marker, and a module definition whose
declaring interfaces import zero or several modules without names.

The import of `this` is part of the hashed imports, so the same
JavaScript run on an element stays another function.

Existing tests that asserted the wording of the "neither" and "both"
marker errors now assert the wording that also covers the third marker.

Part of #27425
Also asserts the message of creating invokers from a module definition
rather than only the marker it names.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Type of change

  • Feature

How to test

  1. Open flow-tests/test-csp-strict/src/main/java/com/vaadin/flow/test/cspstrict/js/DeclaredJsImportView.java (route declared-js-import) in a production build.
  2. Click Run module, then Run module expression.
  3. The status shows initialized by export and then initialized by expression from add-on, with no CSP violation.
API changes
// com.vaadin.flow.js.JsModuleInvokers — Added
public interface JsModuleInvokers extends Serializable

// com.vaadin.flow.component.page.Page — Added
public <T extends JsModuleInvokers> T executeModuleJs(Class<T> definitionType)

// com.vaadin.flow.js.JsDefinitionProxy — Added (internal use)
public static <T extends JsModuleInvokers> T createModuleInvokers(Class<T> definitionType, SerializableFunction<JsCall, PendingJavaScriptResult> runner)
MODULE_CALLS // new constant of the public enum Kind

// com.vaadin.flow.js.internal.JsDefinitionImports — Added (internal)
public static final String THIS

@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Added parentheses around the concatenated first branch of the ternary in the marker check message, so the precedence is explicit. The message itself is unchanged.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Test Results

 1 711 files  ± 0   1 801 suites  ±0   2h 10m 2s ⏱️ + 2m 55s
14 009 tests +14  13 937 ✅ +14  72 💤 ±0  0 ❌ ±0 
14 687 runs  +14  14 615 ✅ +14  72 💤 ±0  0 ❌ ±0 

Results for commit 6333b7d. ± Comparison against base commit 07b92e0.

♻️ This comment has been updated with latest results.

@mcollovati

Copy link
Copy Markdown
Contributor

Two small points from a review of 858e845. Neither blocks the PR.

1. @JsStringFallback on a module definition: the errors send the developer back and forth

@JsDefinition
@JsStringFallback
@JsDefinitionImport(from = "./grid-connector.js")
public interface GridConnectorJs extends JsModuleInvokers { ... }

checkModuleImport accepts this, and then checkImports refuses it with "... is annotated with @JsDefinitionImport, which does not apply to an interface annotated with @JsStringFallback ...". If the developer removes the import as the message says, the next error is "... imports no module with @JsDefinitionImport without names ...". The import is not the problem: a module definition can never be a string fallback, since its this always comes from an import. It would be clearer to refuse the combination itself, before the import checks, with a message like "a JsModuleInvokers interface can not be annotated with @JsStringFallback".

2. The Javadoc of JsModuleInvokers does not say what this is

this is the module namespace object (as in import * as m). This has two effects that a developer does not expect:

  • It has only the named exports. A module that does export default { initLazy(grid) { ... } } fails in the browser with "this.initLazy is not a function". It works with @JsExpression("this.default.initLazy($0)"), but nothing tells the developer that.
  • It can not be changed. JavaScript that sets a property on this (for example this.state = ...) throws a TypeError, since module code is strict.

One or two sentences in the Javadoc, for example: "this is the namespace object of the module: it has the named exports, a default export is this.default, and it can not be changed."

The combination failed on the import checks instead: first on the
import that binds this, then, once it was removed, on the missing one.
Refuse the annotation itself before those checks. Also document in
JsModuleInvokers that this is the module namespace object.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati Both done.

  1. checkDefinition now refuses a JsModuleInvokers interface annotated with @JsStringFallback before any import check, with a message that names the combination and says to move string stand-ins into a JsInvokers interface. The @JsStringFallback Javadoc and the @throws of checkDefinition say so too. A new test checks that the error names the combination and not @JsDefinitionImport.
  2. The JsModuleInvokers Javadoc now says that this is the module namespace object: it has the named exports, a default export is this.default (with a @JsExpression("this.default.initLazy($0)") example), and it can not be changed, so setting a property on it throws a TypeError.

@mcollovati

mcollovati commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

The Javadoc of Page.executeModuleJs is hard to read for people whose first language is not English. Some examples:

  • The first sentence is about 40 words long, with clauses inside clauses.
  • "answers with" is used for "returns".
  • "a method that can not be answered" in @throws is not clear without reading the code.
  • "imports no names" does not say what the developer has to write. It also reads as if the interface can have only one @JsDefinitionImport, but other modules can be imported with names.
  • It does not say when to use this method instead of Page.executeJs(Class). "Apart from what this is, a call runs … the way one through executeJs(Class) does" hides the other differences: methods without @JsExpression, and the import without names.

Here is a proposal for the whole Javadoc. The order is: what the method does, when to use it and how it differs from executeJs(Class), how it works, and what the interface needs.

/**
 * Returns an instance of the given interface that queues calls to the
 * functions of a JavaScript module. In the JavaScript of a call, the module
 * is <code>this</code>.
 * <p>
 * Use this method when the JavaScript you call is in a module, for example
 * the connector of a component. Use {@link #executeJs(Class)} when the
 * JavaScript works on global objects, such as <code>document</code> or
 * <code>navigator</code>. The differences between the two methods are:
 * <ul>
 * <li>Here, <code>this</code> is the module. With {@link #executeJs(Class)},
 * <code>this</code> is not a particular object.</li>
 * <li>Here, a method without {@link JsExpression} calls the function of the
 * module with the same name. {@link #executeJs(Class)} refuses such a
 * method.</li>
 * <li>The interface extends {@link JsModuleInvokers} here, and
 * {@link JsInvokers} for {@link #executeJs(Class)}. One interface can not be
 * used with both methods.</li>
 * </ul>
 * Everything else works the same way: the arguments, the return types, how
 * the build collects the JavaScript, and that no JavaScript is compiled in
 * the browser.
 * <p>
 * Calling a method of the instance adds a call to the queue. The queued calls
 * are sent to the browser with the response to the current request, and run
 * there. In the JavaScript, <code>this</code> is the module, and the
 * arguments of the method are <code>$0</code>, <code>$1</code> and so on. A
 * method without {@link JsExpression} calls the function of the module that
 * has the same name, as <code>this.name(...)</code>. A method with
 * {@link JsExpression} runs that JavaScript instead, for example to call a
 * function with other arguments, or more than one function.
 *
 * <pre>
 * &#64;JsDefinition
 * // The module: this in the JavaScript of each method
 * &#64;JsDefinitionImport(from = "./grid-connector.js")
 * // Another module: formatRow can be used by name
 * &#64;JsDefinitionImport(from = "./grid-format.js", exports = "formatRow")
 * public interface GridConnectorJs extends JsModuleInvokers {
 *
 *     // runs this.initLazy($0)
 *     void initLazy(Element grid);
 *
 *     &#64;JsExpression("this.setRowFormatter($0, formatRow)")
 *     void useRowFormatter(Element grid);
 * }
 *
 * page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement());
 * </pre>
 *
 * The interface must:
 * <ul>
 * <li>be annotated with {@link JsDefinition},</li>
 * <li>extend {@link JsModuleInvokers}, and no other marker interface,</li>
 * <li>name its module with {@link JsDefinitionImport}<code>(from = ...)</code>,
 * without <code>defaultExport</code>, <code>namespace</code> or
 * <code>exports</code>. This import is required, and only one import of the
 * interface can be written this way.</li>
 * </ul>
 * The interface can import other modules too. Each of these imports must set
 * <code>defaultExport</code>, <code>namespace</code> or <code>exports</code>,
 * and the JavaScript of a method uses what it imports by those names. See
 * {@link JsModuleInvokers} for when the modules are loaded.
 *
 * @param <T>
 *            the type of the interface
 * @param definitionType
 *            the interface that describes the module, not <code>null</code>
 * @return an instance of the interface, not <code>null</code>
 * @throws IllegalArgumentException
 *             if the interface does not follow the rules above, or if a
 *             method returns something other than <code>void</code>,
 *             <code>JavaScriptResult</code> or
 *             <code>PendingJavaScriptResult</code>
 */

Other changes:

  • Page.executeJs(Class) could point back with one sentence, for example: "To call the functions of a JavaScript module, use executeModuleJs(Class)."
  • "can not be answered" is also used in the @throws of Element.executeJs(Class), Page.executeJs(Class) and two methods of JsDefinitionProxy. It would be good to change it in all of them, so that the text is the same everywhere.

Say when to use it instead of executeJs(Class) and how the two differ,
list what the interface needs, and say in the @throws of the definition
methods which return types are allowed instead of 'can not be
answered'.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati Done, thanks for the proposal.

  • The Javadoc of Page.executeModuleJs is now your text, with one addition: the list of what the interface must do also says it can not be annotated with @JsStringFallback, since checkDefinition refuses that now.
  • Page.executeJs(Class) ends with "To call the functions of a JavaScript module, use executeModuleJs(Class)."
  • "can not be answered" is gone from the @throws of Element.executeJs(Class), Page.executeJs(Class), JsDefinitionProxy.create and JsDefinitionProxy.createModuleInvokers. They now say "has a method that returns something other than void, JavaScriptResult or PendingJavaScriptResult". The error message for such a method now says "returning a type that a call can not return", followed by the list of allowed types as before.

The latest merge from main only changed guidelines/architecture.md (signal effects), so nothing in this PR needed adapting.

@mcollovati
mcollovati marked this pull request as ready for review November 30, 2026 11:30

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 1 comment.

Finding
📝 A module definition cannot inherit methods unless the extended interface repeats the module import, which no doc mentions and no test pins

* <ul>
* <li>be annotated with {@link JsDefinition},</li>
* <li>extend {@link JsModuleInvokers}, and no other marker interface,</li>
* <li>name its module with

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 A module definition cannot inherit methods unless the extended interface repeats the module import, which no doc mentions and no test pins

checkModuleImport runs for every interface that declares methods of the definition, so the documented inheritance pattern

public interface ConnectorBaseJs extends JsModuleInvokers {
    void initLazy(Element e);
}

@JsDefinition
@JsDefinitionImport(from = "./grid-connector.js")
public interface GridConnectorJs extends ConnectorBaseJs { ... }

is refused with "extends ConnectorBaseJs, which imports no module". The base interface has to carry the same no-name import.

The new docs state the import as a property of "the interface", and the Inheritance section of JsDefinition, which this PR extended to cover executeModuleJs, still promises that inherited methods work as if the definition declared them. Refusing is the right call (the inherited method would otherwise be generated with no module and run with this null), but the rule is worth stating, and the only module-import tests use definitions that declare their methods themselves.

Page.java:662 · documentation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the refusal stays and the rule is now documented and tested.

  • Page.executeModuleJs, JsModuleInvokers and the Inheritance section of @JsDefinition now say that imports are not inherited. The import without names goes on each interface that declares methods, the definition itself or one it extends, and its methods run with that module as this. An interface that declares no methods, such as a definition that only inherits them, has no such import.
  • Tests: an extended interface without the import is refused with "extends …, which imports no module". A parent and child that each have their own import pass. A runtime test checks that an inherited method runs on the parent's module and the child's own method on the child's module.

Imports are not inherited, so an interface that declares methods of a
JsModuleInvokers definition is refused unless it names the module too.
State this in the Javadoc and test both the refused and the accepted
case.
… call

The import goes on every interface that declares methods, and need not
be the definition's module. Test that an inherited method runs on the
module of the interface that declares it.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — collected 1 finding below that could not be attached to the diff.

Finding
📝 The wire-protocol chapter still lists only Element.executeJs(Class) and Page.executeJs(Class) as the declared-JavaScript entry points

📝 The wire-protocol chapter still lists only Element.executeJs(Class) and Page.executeJs(Class) as the declared-JavaScript entry points
## executeJs over the wire enumerates the ways to run JavaScript and names JsInvokers as the marker for declared JavaScript. Page.executeModuleJs(Class) with JsModuleInvokers is a third entry point with the same wire shape, and the later note "null as the element for Page.executeJs(Class)" now covers it too.

guidelines/browser-integration.md:58 points at the same JsInvokers-only wording.
wire-protocol.md:284 · documentation

It is a third entry point for declared JavaScript, with the same wire
shape as Page.executeJs(Class).
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

Updated the guidelines. In guidelines/wire-protocol.md, the declared-JavaScript entry point now also lists Page.executeModuleJs(Class) with a JsModuleInvokers interface: its methods run with the module that the declaring interface imports without names as this, and a method without @JsExpression calls the export of the same name. The wire-shape note says the element parameter is null for both page methods, and that for module calls the generated function, not the wire, supplies this. guidelines/browser-integration.md now mentions JsModuleInvokers next to JsInvokers.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Nothing to flag — the changes look good.

@mcollovati

Copy link
Copy Markdown
Contributor

A note for when #27491 is merged.

#27491 leaves out of the bundle the methods whose ./ module the build can not find. Each call of such a method then throws an IllegalStateException on the server. This already works for executeModuleJs, because the check is in the call handler that both methods use. But the Javadoc says it only for Element.executeJs(Class) and @JsDefinitionImport.

For a module definition this matters more: when the file of the import without names is missing, every method that the interface declares throws, since all of them run with that module as this.

Proposal, as the last paragraph before the tags of Page.executeModuleJs (in the version proposed above):

 * <p>
 * When the build can not find the file of a module that the interface
 * imports, it leaves the methods of the interface out of the bundle and logs
 * an error. Each call of such a method then throws an
 * {@link IllegalStateException} that names the module. When the missing file
 * is the module that is <code>this</code>, this applies to every method of the
 * interface. See {@link JsDefinitionImport} for which files the build checks.

JsModuleInvokers could get the same paragraph, or a shorter one that links to Page#executeModuleJs(Class).

…okers

# Conflicts:
#	flow-server/src/main/java/com/vaadin/flow/component/page/Page.java
The hotswap test from main still expected 'extends neither', which this
branch replaced with 'extends none of JsInvokers, JsModuleInvokers and
JsSnippets'.
Also name JsModuleInvokers in the build error for @JsDefinitionImport
on a class, next to JsInvokers.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati #27491 is merged now, so I merged main into this branch and added the paragraph.

  • Page.executeModuleJs ends with your paragraph. JsModuleInvokers gets the short version: when the file of the module that is this can not be found, every method the interface declares is left out and each call throws an IllegalStateException, with a link to Page#executeModuleJs(Class).
  • Page.executeJs(Class) keeps both paragraphs: the one about left-out methods from feat: report JavaScript definition imports that can not be resolved #27491, and the pointer to executeModuleJs.
  • New tests: the build leaves out the function of a JsModuleInvokers method whose import without names can not be found, and records it as unresolved. A call through executeModuleJs then throws and queues nothing, while an inherited method whose module is found still runs.
  • The build error for @JsDefinitionImport on a class now names JsModuleInvokers next to JsInvokers, and one test from main now expects the marker message of this branch ("extends none of …").

One open point in the code from #27491, not changed here: the dev-bundle check compares the list of unresolved functions, so in development mode a change in that list makes the precompiled dev bundle rebuild. At runtime, development mode reads that list from the project files, not from the bundle, so the rebuild may not be needed.

@mcollovati

Copy link
Copy Markdown
Contributor

One small wording point in the new text about inheritance, in Page.executeModuleJs and in JsModuleInvokers:

An interface that declares no methods has no such import

This reads as a description, but it is a rule: checkImports refuses any @JsDefinitionImport on an interface that declares no methods ("... is annotated with @JsDefinitionImport but declares no method of its own"). A developer who puts the import on a definition that only inherits its methods gets that error, and the text should tell them before.

The list item in Page.executeModuleJs is also one long sentence. A proposal with shorter sentences:

 * <li>name its module with
 * {@link JsDefinitionImport}<code>(from = ...)</code>, without
 * <code>defaultExport</code>, <code>namespace</code> or
 * <code>exports</code>. This import is required, and only one import of the
 * interface can be written this way.</li>
 * <li>not be annotated with {@link JsStringFallback}.</li>
 * </ul>
 * Imports are not inherited. When methods are declared in an interface that
 * the definition extends, that interface needs its own import without names,
 * and its methods run with that module as <code>this</code>. An interface
 * that declares no methods, such as a definition that only inherits them,
 * must not have any {@link JsDefinitionImport}.

And in JsModuleInvokers:

 * Imports are not inherited. Each interface that declares methods of the
 * definition, the definition itself or one it extends, needs its own
 * {@link JsDefinitionImport} without names, and its methods run with that
 * module as <code>this</code>. An interface that declares no methods, such as
 * a definition that only inherits them, must not have any
 * {@link JsDefinitionImport}.

The sentence "An interface whose methods would have no module as this is refused" in JsModuleInvokers can then go, since "needs its own" already says it.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the changes — left 2 comments and collected 1 finding below that could not be attached to the diff.

Finding
📝 The documented connector idiom passes an Element that silently arrives as null when the element is detached, and a shorthand method leaves no place to guard
📝 JsInvokers and JsSnippets still describe a world of two marker interfaces
🧪 No test renders a module definition whose only import is the module itself, the canonical shape

📝 JsInvokers and JsSnippets still describe a world of two marker interfaces
JsInvokers says "An interface whose methods only answer with snippets extends JsSnippets instead. An interface can not extend both", and never mentions JsModuleInvokers — no @see either. JsSnippets:32 says "An interface can not extend both marker interfaces", which is now a wrong count.

The PR updated the equivalent wording in JsDefinition, JsExpression, JsDefinitionImport and JsStringFallback, so these two are the odd ones out — and JsInvokers is where a developer choosing a marker is most likely to land.
JsInvokers.java:52 · documentation

* void useRowFormatter(Element grid);
* }
*
* page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 The documented connector idiom passes an Element that silently arrives as null when the element is detached, and a shorthand method leaves no place to guard

NodeSerializer writes null for a detached node, and a call queued through the page is owned by the root node, so it is always sent. The javadoc example page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement()) therefore runs this.initLazy(null) whenever the grid is not attached at flush time (attach plus detach in the same round trip, or a call made before attach).

This is new ground rather than the Page.executeJs(Class) status quo: that method refuses methods without @JsExpression, so every page-level call has an author-written expression where a guard fits. Flow-components does exactly that today — GridJs.initConnector is @JsExpression("if ($0) window.Vaadin.Flow.gridConnector.initLazy($0)"). The shorthand form that executeModuleJs encourages generates return this.initLazy($0); with nowhere to put the check.

Worth a sentence in the javadoc of executeModuleJs and JsModuleInvokers saying an element argument is null unless attached when the invocation is sent, and that a method needing a guard declares it with @JsExpression.

Page.java:661 · documentation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added. Page.executeModuleJs and JsModuleInvokers now say that an Element argument is null in the browser when the element is not attached at the time the call is sent. A method that has to guard against that declares its JavaScript with @JsExpression, for example @JsExpression("if ($0) this.initLazy($0)").

}
}
String call = " }).call(" + self
+ (values.isEmpty() ? "" : (", " + String.join(", ", values)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 No test renders a module definition whose only import is the module itself, the canonical shape

The new values.isEmpty() branch produces }).call($modules[0]);. Every rendering test still ends in .call(this, …) or .call($modules[0], $modules[1]); MissingThisModuleJs has the right shape but its module is unresolved, so no body is rendered, and the strict-CSP IT definition imports a second module with a name.

So the exact definition the PR documents — @JsDefinitionImport(from = "./grid-connector.js") and nothing else — never has its generated JavaScript asserted anywhere. A malformed argument list there would be a syntax error that takes the whole definitions file with it, and nothing would fail.

TaskGenerateJsDefinitions.java:1610 · tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added. moduleDefinition_callsTheExportWithTheModuleAsThis now also renders a definition whose only import is the module, and asserts the whole function, ending in }).call($modules[0]);.

Also say that a detached element argument is null and where to guard
against it, name JsModuleInvokers in JsInvokers and JsSnippets, and
test the function of a module definition that imports only its module.
@totally-not-ai

Copy link
Copy Markdown
Contributor Author

@mcollovati Done. Both texts are now yours. In Page.executeModuleJs the inheritance rule is a paragraph after the list, which says that an interface that declares no methods must not have any @JsDefinitionImport. The list item now starts with "when it declares methods", so it no longer contradicts that rule. In JsModuleInvokers, the sentence "An interface whose methods would have no module as this is refused" is gone. A new test checks the rule for a module definition: one that only inherits its methods and repeats the parent's import is refused with "declares no method of its own".

Also in this push:

  • JsInvokers and JsSnippets now name JsModuleInvokers as the third marker. Before, they said an interface can not extend "both".
  • The latest merge from main only bumped versions in pom.xml files, so nothing needed adapting.

@vaadin-review-bot vaadin-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Nothing to flag — the changes look good.

@sonarqubecloud

Copy link
Copy Markdown

@mcollovati
mcollovati added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit e65e44f Nov 30, 2026
59 checks passed
@mcollovati
mcollovati deleted the feature/js-module-invokers branch November 30, 2026 16:18
vaadin-bot added a commit to vaadin/docs that referenced this pull request Nov 30, 2026
Add Page.executeModuleJs(Class) and the JsModuleInvokers marker to
Accessing the Browser Page, and mention the third marker interface
alongside JsInvokers and JsSnippets in Calling JavaScript from the Server.

Documents vaadin/flow#27492 (`6333b7d89aa0ad3f3d83f53799d449f4767436e0`).
@github-actions

Copy link
Copy Markdown
Contributor

Pull request created: #6805

Generated by Documentation Bot · agent · 122.6 AIC · ⊞ 11.7K

@github-actions

Copy link
Copy Markdown
Contributor

Documentation Bot: Draft documentation pull request for this change: vaadin/docs#6805

Files updated:

  • articles/flow/advanced/browser-access.adoc
  • articles/flow/component-internals/element-api/calling-javascript.adoc

It was written from the state of this pull request as you see it now. Please review it and mark it ready for review.

Generated by Documentation Bot for #27492 · agent · 122.6 AIC · ⊞ 11.7K · ◷

mcollovati pushed a commit that referenced this pull request Dec 1, 2026
Part of #27425

**new feature** · flow-server · apps and components that call what a
JavaScript module exports, such as component connectors

**Background — JavaScript definitions.** A `@JsDefinition` interface
declares JavaScript that the build bundles, so the server sends only a
function id and nothing is compiled in the browser.
`@JsDefinitionImport` gives that JavaScript names from a module.

Adds a third kind of definition that calls the exports of one module,
with the module as `this`. A method without `@JsExpression` calls the
export of the same name. This PR loads the modules on the first call,
like other imports. The stacked PR on top loads them with the view, so
calls run in order.

```java
@JsDefinition
@JsDefinitionImport(from = "./grid-connector.js")
public interface GridConnectorJs extends JsModuleInvokers {
    void initLazy(Element grid); // return this.initLazy($0)
}
page.executeModuleJs(GridConnectorJs.class).initLazy(grid.getElement());
```

**Risks:**
- ⚠️ Public API: new `JsModuleInvokers`, `Page.executeModuleJs`, and a
new constant `MODULE_CALLS` in the public `JsDefinitionProxy.Kind` enum,
which can break an exhaustive `switch` over it in user code.
- ⚠️ Behaviour change: the error for an interface that extends no
marker, or more than one, has new wording, since there are now three
markers.
- ✅ No serialization, threading, security or migration concerns.

- Added `JsModuleInvokers`, a marker that does not extend `JsInvokers`,
so `Element.executeJs` refuses it at compile time.
- Added `Page.executeModuleJs(Class)` and
`JsDefinitionProxy.createModuleInvokers`.
- `checkDefinition` refuses an interface that extends more than one
marker, and a module definition whose declaring interfaces import zero
or several modules without names. It also refuses a module definition
annotated with `@JsStringFallback`, before the import checks, since a
string call has no module as `this`.
- The import without names is part of the hashed imports, so the same
JavaScript run on an element stays a different function.
- The generated function runs the JavaScript with that module as `this`.
- Updated the Javadoc of `@JsDefinition`, `@JsDefinitionImport` (its
example no longer shows connector code), `@JsExpression`, and the
`@throws` that list the markers. `JsModuleInvokers` says that `this` is
the module namespace object (named exports only, a default export is
`this.default`, and it can not be changed), and `@JsStringFallback` says
it can not mark a module definition. The Javadoc of
`Page.executeModuleJs` says when to use it instead of
`Page.executeJs(Class)` and lists what the interface needs, and the docs
say that imports are not inherited, so each interface that declares
methods of a module definition names its own module, and one that
declares no methods must have no import. They also say that a detached
`Element` argument arrives as `null`, and that a method that has to
guard against it declares its JavaScript with `@JsExpression`.
`JsInvokers` and `JsSnippets` now name `JsModuleInvokers` as the third
marker. The `@throws` of the definition methods name the allowed return
types.
- When the build can not find the file of a module that a module
definition imports, the methods its interface declares are left out of
the bundle and each call throws an `IllegalStateException` that names
the module, as for other imports. For the module that is `this`, that is
every method the interface declares. The Javadoc of
`Page.executeModuleJs` and `JsModuleInvokers` says so, and the build
error for `@JsDefinitionImport` on a class now names `JsModuleInvokers`
too.
- Updated the wire-protocol and browser-integration guidelines to list
`Page.executeModuleJs(Class)` and `JsModuleInvokers`.
- Existing tests that checked the old wording of the marker errors now
check the new wording.
- Added a strict-CSP production IT that calls an export directly and
through an expression.

Working on behalf of @mcollovati

---------

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
mcollovati pushed a commit that referenced this pull request Dec 1, 2026
) (CP: 25.4)

Fixes #27425, Depends on #27492

**behavior deviation** · flow-build-tools · apps and components that set
up a connector through `JsModuleInvokers` and call it in the same round
trip

**Background — call order.** The client runs the calls of a message one
after the other without awaiting them. A call that waits for `import()`
therefore runs its JavaScript after the calls that follow it.

A call through `Page.executeModuleJs` now runs before the calls made
after it in the same round trip. The build loads their modules with the
views that use them, the same way as `@JsModule`, so a call does not
wait. A call made where no shown view loaded the module still works, but
runs late once, and logs a warning in the browser. In production the
warning says no view shown so far loaded the module, or that the build
could not find the path, for example one that only an alias resolves. In
development it says a restart registers it after a hotswap, or that the
build could not find or check the path, such as one reached through an
alias. A missing `./` file never gets there: it stops the build
(#27568).

**Risks:**
- ⚠️ Limit: an `Element.executeJs` call made *before* a module call in
the same round trip still runs after it. Element calls are queued when
the response is written, and page calls are queued when they are made,
the same as `Page.executeJs` today. The Javadoc says so.
- ⚠️ Behaviour change: the modules of a module definition now load with
the route's chunk, or at startup for an eager route and in development
mode, not on the first call. In development mode and in a production
build that does not optimize the bundle, the build does not tell views
apart, so the modules of every module definition on the class path load
at startup, also those no view uses, and their top-level code runs then.
- ⚠️ The fallback warning names the module path, not the Java
definition, because production bundles never name Java classes. The
issue asked to name the definition.
- ⚠️ Known limit, checked by hand in development mode: a hotswap that
only redefines classes does not update the registrations. Calls still
work, but the first call on each page runs late and logs a warning until
a restart. A restart, or an edit of the module file, registers the
module again.
- ⏱️ Every generated definitions file gets two more header lines. A
chunk gets one import per module of the definitions it reaches.
- ✅ No API, serialization, threading or security concerns.

**Context.** The bundle check needs no new rule for when to rebuild. The
function ids hash the imports, so a definition or import change already
forces a rebuild, and the rebuild writes the registrations. The check,
and the Vite plugin that writes the imports of a bundle into its stats,
now read imports in either quote and undo the escapes of double-quoted
ones, since the registrations of definition modules are written that
way. The check also finds a project module imported without its
extension the way Vite does.

- Added `groupByChunk` to the frontend scanner. It uses the same
reachability as `@JsModule` to tell which chunks reach a class.
- The imports file and the route chunks import the modules of each
reached `JsModuleInvokers` definition and register them in
`window.Vaadin.Flow.jsDefinitionModules`, keyed by the resolved import
path.
- The build finds a module the way Vite does: by its path as written,
with one of Vite's default extensions (`.mjs`, `.js`, `.mts`, `.ts`,
`.jsx`, `.tsx`, `.json`), or as a folder's index file. A subpath of an
installed package whose package.json has an `exports` field is found
through that field alone, as the bundler resolves it. A `./` file from a
jar must be named exactly as it is, as the generator requires.
- A module the build can not find gets no static import, because that
import would fail the Vite build. A `./` file of the project or a jar
that the build can not find stops the build (#27568). The chunk writer
checks such a file the same way the generator does, so the two agree.
Any other path the build can not find, such as one reached through a
Vite alias, is loaded by the call.
- The generated function takes its modules from that registry without
awaiting. Only when a module is missing does it load the missing ones in
parallel, warn once per module, and register them for later calls.
- Named imports of `JsInvokers` definitions are not changed. They still
load on the first call.
- Documented the loading, call order, fallback and limits in
`JsModuleInvokers`, `@JsDefinition` and `Page.executeModuleJs`.
- `AbstractUpdateImportsTest` builds its options through a helper, so a
test can use the same class finder for the options and the scanner.
- Strict-CSP production ITs check call order when the view is shown and
later. They also check a call to a module that only another view
registers, which loads it once, warns once, and runs later calls in
order. They fail when the chunk registration is turned off.

Working on behalf of @mcollovati

---------

Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants