A platform for community discussion. Free, open, simple.
DEV: Derive styleguide code samples from the rendered example (#42100)
Sérgio Saquetima8b1606ff87a
diff --git a/frontend/asset-processor/asset-processor-rollup.js b/frontend/asset-processor/asset-processor-rollup.jsindex 8d6b40066e4..f8ca66dafd4 100644--- a/frontend/asset-processor/asset-processor-rollup.js+++ b/frontend/asset-processor/asset-processor-rollup.js@@ -10,6 +10,7 @@ import EmberThisFallback from "ember-this-fallback";import StripTestSelectorsPlugin from "strip-test-selectors/src/strip-test-selectors";import { browsers } from "../discourse/config/targets";import babelTransformModuleRenames from "../discourse/lib/babel-transform-module-renames";+import discourseSourceImports from "../discourse/lib/discourse-source-imports.mjs";import AddThemeGlobals from "./add-theme-globals";import BabelResolveCoreImports from "./babel-resolve-core-imports";import BabelResolvePluginImports from "./babel-resolve-plugin-imports";@@ -57,6 +58,7 @@ async function performRollup(modules, opts) {console.info(level, message);},plugins: [+ discourseSourceImports({ fs }),discourseFileSearch(),discourseVirtualLoader({isTheme: !!opts.themeId,diff --git a/frontend/asset-processor/build.mjs b/frontend/asset-processor/build.mjsindex b9dd03da056..a2343bf2c89 100644--- a/frontend/asset-processor/build.mjs+++ b/frontend/asset-processor/build.mjs@@ -16,6 +16,7 @@ const bundle = await rolldown({resolve: {extensions: [".mjs", ".js", ".cjs", ".json"],alias: {+ "content-tag": local("./content-tag.js"),path: "path-browserify",url: local("./url-polyfill.js"),// Absolute path so postcss's `browser` field (`source-map-js: false`) can't stub it out and disable CSS sourcemaps.diff --git a/frontend/asset-processor/discourse-source-imports.test.mjs b/frontend/asset-processor/discourse-source-imports.test.mjsnew file mode 100644index 00000000000..f08b49fc11c--- /dev/null+++ b/frontend/asset-processor/discourse-source-imports.test.mjs@@ -0,0 +1,194 @@+/* eslint-disable qunit/require-expect */+import { mkdtempSync, realpathSync, writeFileSync } from "fs";+import { tmpdir } from "os";+import { join } from "path";+import { rolldown } from "rolldown";+import { expect, test } from "vitest";+import discourseSourceImports from "../discourse/lib/discourse-source-imports.mjs";++const EXAMPLE = `const label = "Save";++export default <template>+ <button type="button">+ {{label}}+ </button>+</template>;+`;++function build(modules = { "/app/example.gjs": EXAMPLE }) {+ // Stands in for node's fs.promises / the asset processor's virtual fs: reads+ // from the map and throws for a missing file, the way a real read would.+ const fs = {+ readFile(id) {+ if (!(id in modules)) {+ throw new Error(`ENOENT: no such file, open '${id}'`);+ }+ return modules[id];+ },+ };+ const plugin = discourseSourceImports({ fs });++ // Minimal stand-in for the rollup plugin context. `error` throws, matching+ // rollup, so tests can assert on the message.+ const context = {+ resolve: (source) =>+ source.startsWith("external:")+ ? { id: source, external: true }+ : { id: source, external: false },+ error(message) {+ throw new Error(message);+ },+ addWatchFile() {},+ };++ return {+ resolveId: (specifier) =>+ plugin.resolveId.handler.call(context, specifier, "/app/importer.js"),+ load: (id) => plugin.load.handler.call(context, id),+ filters: { resolveId: plugin.resolveId.filter, load: plugin.load.filter },+ };+}++async function sourceOf(specifier, modules) {+ const plugin = build(modules);+ const id = await plugin.resolveId(specifier);+ const code = await plugin.load(id);++ return JSON.parse(code.replace(/^export default /, "").replace(/;$/, ""));+}++test("?source=file returns the whole file, dedented", async () => {+ expect(await sourceOf("/app/example.gjs?source=file")).toBe(EXAMPLE.trim());+});++test("?source=template returns only the template contents", async () => {+ expect(await sourceOf("/app/example.gjs?source=template")).toBe(+ '<button type="button">\n {{label}}\n</button>'+ );+});++test("?source=file works on a module with no template", async () => {+ const modules = { "/app/plain.js": "export const MAX = 50;\n" };++ expect(await sourceOf("/app/plain.js?source=file", modules)).toBe(+ "export const MAX = 50;"+ );+});++test("imports without a source query are left alone", async () => {+ expect(+ await build().resolveId("/app/example.gjs?other=?source=1")+ ).toBeNull();+});++test("the resolveId filter keeps every other module off the handler", () => {+ const { resolveId } = build().filters;++ // Every specifier the handler reports on has to reach it, including the ones it+ // rejects, so the value is left open and a bare `?source` still matches.+ expect(resolveId.id.test("/app/example.gjs?source=file")).toBe(true);+ expect(resolveId.id.test("/app/example.gjs?source=bogus")).toBe(true);+ expect(resolveId.id.test("/app/example.gjs?source")).toBe(true);+ expect(resolveId.id.test("/app/example.gjs?other=1&source=file")).toBe(true);++ expect(resolveId.id.test("/app/example.gjs")).toBe(false);+ expect(resolveId.id.test("/app/example.gjs?other=1")).toBe(false);+ expect(resolveId.id.test("/app/example.gjs?sourcemap=1")).toBe(false);+ expect(resolveId.id.test("/app/resource.gjs")).toBe(false);++ // A percent-encoded key parses back to `source`, but matching that costs every+ // module in the build a decode. A typo here fails as an unresolved import.+ expect(resolveId.id.test("/app/example.gjs?%73ource=file")).toBe(false);+});++test("rejects an unknown source value", async () => {+ await expect(+ build().resolveId("/app/example.gjs?source=bogus")+ ).rejects.toThrow(/single \?source= value/);+});++test("rejects a valueless source query", async () => {+ await expect(build().resolveId("/app/example.gjs?source")).rejects.toThrow(+ /single \?source= value/+ );+});++test("rejects duplicate source values rather than picking the first", async () => {+ await expect(+ build().resolveId("/app/example.gjs?source=file&source=template")+ ).rejects.toThrow(/single \?source= value/);+});++test("rejects an unrecognized query parameter alongside source", async () => {+ await expect(+ build().resolveId("/app/example.gjs?source=file&unknown")+ ).rejects.toThrow(/do not support the "unknown" query parameter/);+});++test("a module with no source of its own fails when read", async () => {+ const plugin = build();+ const id = await plugin.resolveId("/app/missing.gjs?source=file");++ await expect(plugin.load(id)).rejects.toThrow(/ENOENT/);+});++test("rejects an external module", async () => {+ await expect(+ build().resolveId("external:pkg/thing.js?source=file")+ ).rejects.toThrow(/Cannot import source from/);+});++function fixtureRoot() {+ const root = realpathSync(mkdtempSync(join(tmpdir(), "source-imports-")));++ writeFileSync(join(root, "example.gjs"), EXAMPLE);++ return root;+}++async function bundleEntry(root, entry) {+ writeFileSync(join(root, "entry.js"), entry);++ const bundle = await rolldown({+ input: join(root, "entry.js"),+ plugins: [discourseSourceImports()],+ });++ const { output } = await bundle.generate({ format: "es" });++ return output[0].code;+}++// The tests above drive the handlers directly. This runs a real rolldown build the+// way core registers the plugin, so the hook filters, resolver re-entry, disk reads,+// and virtual loading are exercised together.+test("resolves both modes through a real rolldown build", async () => {+ const root = fixtureRoot();+ const code = await bundleEntry(+ root,+ `import whole from "./example.gjs?source=file";+ import template from "./example.gjs?source=template";+ export default [whole, template];+ `+ );++ const [whole, template] = JSON.parse(code.match(/(\[".*"\])/s)[1]);++ expect(whole).toBe(EXAMPLE.trim());+ expect(template).toBe('<button type="button">\n {{label}}\n</button>');+});++test("?source=template requires exactly one template", async () => {+ const modules = {+ "/app/none.js": "export const value = 1;",+ "/app/two.gjs":+ "export const A = <template>a</template>;\nexport const B = <template>b</template>;",+ };++ for (const name of ["none.js", "two.gjs"]) {+ const plugin = build(modules);+ const id = await plugin.resolveId(`/app/${name}?source=template`);++ await expect(plugin.load(id)).rejects.toThrow(/exactly one template/);+ }+});diff --git a/frontend/discourse/lib/discourse-source-imports.mjs b/frontend/discourse/lib/discourse-source-imports.mjsnew file mode 100644index 00000000000..e22c9e5eed3--- /dev/null+++ b/frontend/discourse/lib/discourse-source-imports.mjs@@ -0,0 +1,116 @@+import { Preprocessor } from "content-tag";+import nodeFs from "fs";++const VIRTUAL_PREFIX = "\0discourse-source:";+const MODES = new Set(["file", "template"]);+const preprocessor = new Preprocessor();++/*+ * Importing `<specifier>?source=file` resolves to that module's raw, untranspiled+ * source as a string. `?source=template` narrows it to the contents of the module's+ * single `<template>`. The specifier resolves like a normal import.+ *+ * For example, a documentation page can render a component and display its source+ * without the two drifting apart.+ */+export default function discourseSourceImports({ fs = nodeFs.promises } = {}) {+ return {+ name: "discourse-source-imports",++ resolveId: {+ // The value is deliberately left open so a bad one still reaches the error+ // below rather than being filtered out into an unresolved import.+ filter: { id: /[?&]source(=|&|$)/ },+ async handler(source, importer) {+ const queryStart = source.indexOf("?");++ if (queryStart === -1) {+ return null;+ }++ const query = new URLSearchParams(source.slice(queryStart + 1));+ const modes = query.getAll("source");++ if (modes.length === 0) {+ return null;+ }++ if (modes.length > 1 || !MODES.has(modes[0])) {+ this.error(+ `Source imports require a single ?source= value of "file" or "template".`+ );+ }++ // Anything else in the query is a typo or meant for a loader that will+ // never see it, since this plugin consumes the whole specifier.+ const unknown = [...query.keys()].filter((key) => key !== "source");++ if (unknown.length > 0) {+ this.error(+ `Source imports do not support the "${unknown[0]}" query parameter.`+ );+ }++ const sourcePath = source.slice(0, queryStart);+ const resolved = await this.resolve(sourcePath, importer, {+ skipSelf: true,+ });++ if (!resolved || resolved.external) {+ this.error(`Cannot import source from "${sourcePath}".`);+ }++ // The mode goes last so the id cannot end in the source file's extension.+ // Template transforms match on how an id ends and ignore the \0 marker, so+ // an id ending in .hbs or .gjs gets compiled as a template and the string+ // this plugin produced is overwritten.+ return `${VIRTUAL_PREFIX}${resolved.id}:${modes[0]}`;+ },+ },++ load: {+ filter: { id: /^\0discourse-source:/ },+ async handler(id) {+ const separator = id.lastIndexOf(":");+ const mode = id.slice(separator + 1);+ const sourceId = id.slice(VIRTUAL_PREFIX.length, separator);++ // The virtual id never changes, so without this a watch-mode edit to the+ // source file would not invalidate this module. Inert outside watch mode.+ this.addWatchFile(sourceId);++ const source = await fs.readFile(sourceId, "utf8");+ let contents;++ if (mode === "template") {+ const templates = preprocessor.parse(source, { filename: sourceId });++ if (templates.length !== 1) {+ this.error(+ `Template source imports require exactly one template in "${sourceId}".`+ );+ }++ contents = templates[0].contents;+ } else {+ contents = source;+ }++ return `export default ${JSON.stringify(dedent(contents))};`;+ },+ },+ };+}++function dedent(source) {+ const lines = source+ .replace(/^\r?\n/, "")+ .replace(/\r?\n\s*$/, "")+ .split(/\r?\n/);+ const contentLines = lines.filter((line) => line.trim());+ const indentation = contentLines.length+ ? Math.min(...contentLines.map((line) => line.match(/^\s*/)[0].length))+ : 0;++ return lines.map((line) => line.slice(indentation)).join("\n");+}diff --git a/frontend/discourse/package.json b/frontend/discourse/package.jsonindex eb5f2d8485f..eade6dc35cc 100644--- a/frontend/discourse/package.json+++ b/frontend/discourse/package.json@@ -140,6 +140,7 @@"ansi-to-html": "^0.7.2","babel-plugin-debug-macros": "^2.0.0","babel-plugin-ember-template-compilation": "^4.0.0",+ "content-tag": "^4.0.0","deprecation-silencer": "workspace:1.0.0","discourse-i18n": "workspace:*","discourse-markdown-it": "workspace:1.0.0",diff --git a/frontend/discourse/rolldown.config.mjs b/frontend/discourse/rolldown.config.mjsindex 7b12f831ef7..f0bf1580691 100644--- a/frontend/discourse/rolldown.config.mjs+++ b/frontend/discourse/rolldown.config.mjs@@ -2,6 +2,7 @@ import * as fs from "fs";import { basename, relative } from "path";import { viteAliasPlugin, viteImportGlobPlugin } from "rolldown/experimental";import discourseChunkNamesPlugin from "./lib/discourse-chunk-names.mjs";+import discourseSourceImports from "./lib/discourse-source-imports.mjs";import dynamicChunkUrlPlugin from "./lib/dynamic-chunk-url-plugin.mjs";import writeResolverConfig from "./lib/embroider-vite-resolver-options.mjs";import maybeBabel from "./lib/maybe-babel.mjs";@@ -116,6 +117,7 @@ export function buildConfig({ devMode } = {}) {plugins: [viteAliasPlugin({ entries: aliases }),dynamicChunkUrlPlugin(),+ discourseSourceImports(),optimizedEmber(),viteImportGlobPlugin(),maybeBabel({diff --git a/lib/asset_processor.rb b/lib/asset_processor.rbindex bacb376c856..07c3909520b 100644--- a/lib/asset_processor.rb+++ b/lib/asset_processor.rb@@ -10,6 +10,7 @@ class AssetProcessornode_modules/.pnpm/lock.yamlfrontend/asset-processor/**/*.{js,mjs}frontend/discourse/lib/babel-transform-module-renames.js+ frontend/discourse/lib/discourse-source-imports.mjsfrontend/discourse/config/targets.js]diff --git a/plugins/styleguide/README.md b/plugins/styleguide/README.mdindex e070fd33a60..4ebea0fa083 100644--- a/plugins/styleguide/README.md+++ b/plugins/styleguide/README.md@@ -4,3 +4,28 @@ Adds a URL of `/styleguide` to discourse that renders widgets in variousconfigurations to aid in styling.++## Automatic code examples++Discourse's build pipeline allows adding `?source=file` or `?source=template` to+a module import. This provides a string of the raw source code for the entire+file, or just for the `<template>`. Put the example in its own module under+`examples/`, import it twice, and pass the string to `@code`:++```gjs+import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";+import CharCounterExample from "../../examples/char-counter";+import charCounterSource from "../../examples/char-counter.gjs?source=file";++export default <template>+ <StyleguideExample @title="<DCharCounter>" @code={{charCounterSource}}>+ <CharCounterExample @dummy={{@dummy}} />+ </StyleguideExample>+</template>+```++The import must resolve within the same plugin or theme bundle, and+`?source=template` requires the module to contain exactly one `<template>`.++Keep using an explicit `@code` string for curated samples that intentionally+differ from the rendered implementation.diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/char-counter.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/char-counter.gjsnew file mode 100644index 00000000000..9b4734b9d00--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/char-counter.gjs@@ -0,0 +1,13 @@+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import withEventValue from "discourse/helpers/with-event-value";+import DCharCounter from "discourse/ui-kit/d-char-counter";++export default <template>+ <DCharCounter @max="50" @value={{@dummy.charCounterContent}}>+ <textarea+ {{on "input" (withEventValue (fn (mut @dummy.charCounterContent)))}}+ class="styleguide--char-counter"+ ></textarea>+ </DCharCounter>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/spinner-small.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/spinner-small.gjsnew file mode 100644index 00000000000..2fb5fa41fa2--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/spinner-small.gjs@@ -0,0 +1,3 @@+export default <template>+ <div class="spinner small"></div>+</template>diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/06-spinners.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/06-spinners.gjsindex 02f3d518189..9e18ecd9ba6 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/06-spinners.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/atoms/06-spinners.gjs@@ -1,18 +1,16 @@import Component from "@glimmer/component";import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";+import SpinnerSmallExample from "../../examples/spinner-small";+import spinnerSmallSource from "../../examples/spinner-small.gjs?source=template";export default class Spinners extends Component {- get spinnerSmallCode() {- return `<div class="spinner small"></div>`;- }-get spinnerRegularCode() {return `<div class="spinner"></div>`;}<template>- <StyleguideExample @title="spinner - small" @code={{this.spinnerSmallCode}}>- <div class="spinner small"></div>+ <StyleguideExample @title="spinner - small" @code={{spinnerSmallSource}}>+ <SpinnerSmallExample /></StyleguideExample><StyleguideExamplediff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/char-counter.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/char-counter.gjsindex b74005dbf85..db5cb3804b8 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/char-counter.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/char-counter.gjs@@ -1,37 +1,9 @@-import Component from "@glimmer/component";-import { fn } from "@ember/helper";-import { on } from "@ember/modifier";-import withEventValue from "discourse/helpers/with-event-value";-import DCharCounter from "discourse/ui-kit/d-char-counter";import StyleguideExample from "discourse/plugins/styleguide/discourse/components/styleguide-example";+import CharCounterExample from "../../examples/char-counter";+import charCounterSource from "../../examples/char-counter.gjs?source=file";-export default class CharCounterMolecule extends Component {- get charCounterCode() {- return `-import { fn } from "@ember/helper";-import { on } from "@ember/modifier";-import CharCounter from "discourse/components/char-counter";-import withEventValue from "discourse/helpers/with-event-value";--<template>- <CharCounter @max="50" @value={{@dummy.charCounterContent}}>- <textarea- {{on "input" (withEventValue (fn (mut @dummy.charCounterContent)))}}- class="styleguide--char-counter"- ></textarea>- </CharCounter>+export default <template>+ <StyleguideExample @title="<DCharCounter>" @code={{charCounterSource}}>+ <CharCounterExample @dummy={{@dummy}} />+ </StyleguideExample></template>- `;- }-- <template>- <StyleguideExample @title="<CharCounter>" @code={{this.charCounterCode}}>- <DCharCounter @max="50" @value={{@dummy.charCounterContent}}>- <textarea- {{on "input" (withEventValue (fn (mut @dummy.charCounterContent)))}}- class="styleguide--char-counter"- ></textarea>- </DCharCounter>- </StyleguideExample>- </template>-}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 26ddeeff8e6..aa485e1259b 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -544,6 +544,9 @@ importers:babel-plugin-ember-template-compilation:specifier: ^4.0.0version: 4.0.0+ content-tag:+ specifier: ^4.0.0+ version: 4.2.0deprecation-silencer:specifier: workspace:1.0.0version: link:../deprecation-silencerdiff --git a/spec/lib/asset_processor_spec.rb b/spec/lib/asset_processor_spec.rbindex 34106320891..313103d2ca8 100644--- a/spec/lib/asset_processor_spec.rb+++ b/spec/lib/asset_processor_spec.rb@@ -78,6 +78,62 @@ RSpec.describe AssetProcessor doexpect(result).to include("dt7948.n(")end+ it "hashes every file outside the asset processor that it imports" do+ # The processor is cached under a digest of its inputs, so anything it reaches+ # outside its own directory has to be listed or its changes go unnoticed.+ processor_dir = File.expand_path("frontend/asset-processor")+ hashed =+ AssetProcessor::CACHE_DEPENDENCY_GLOBS+ .flat_map { |glob| Dir.glob(glob) }+ .map { |path| File.expand_path(path) }+ .to_set++ resolve_import = ->(specifier, from) do+ base = File.expand_path(specifier, File.dirname(from))+ candidates = [base] + %w[.js .mjs].flat_map { |ext| ["#{base}#{ext}", "#{base}/index#{ext}"] }+ candidates.find { |candidate| File.file?(candidate) }+ end++ queue =+ Dir+ .glob("frontend/asset-processor/**/*.{js,mjs}")+ .reject { |path| path.end_with?(".test.mjs") || path.include?("/node_modules/") }+ .map { |path| File.expand_path(path) }+ seen = queue.to_set+ external = {}++ until queue.empty?+ importer = queue.shift++ File+ .read(importer)+ .scan(/(?:from|import|require)\s*\(?\s*["']([^"']+)["']/)+ .flatten+ .select { |specifier| specifier.start_with?(".") }+ .each do |specifier|+ resolved = resolve_import.call(specifier, importer)+ next if resolved.nil? || resolved.include?("/node_modules/") || seen.include?(resolved)++ seen << resolved+ # Reachable core files are themselves scanned, so a transitive import+ # cannot slip past the digest either.+ external[resolved] = importer unless resolved.start_with?("#{processor_dir}/")+ queue << resolved+ end+ end++ expect(external).not_to be_empty++ aggregate_failures do+ external.each do |path, imported_by|+ expect(hashed).to include(path),+ "#{Pathname.new(path).relative_path_from(Rails.root)} is imported by " \+ "#{Pathname.new(imported_by).relative_path_from(Rails.root)} " \+ "but is not in CACHE_DEPENDENCY_GLOBS"+ end+ end+ end+describe "Transpiler#terser" doit "can minify code and provide sourcemaps" dosources = {@@ -132,6 +188,115 @@ RSpec.describe AssetProcessor doexpect(entrypoint(result, "main")["map"]).not_to be_nilend+ it "can import module source" do+ example = <<~GJS+ const label = "Save";++ export default <template>+ <button type="button">{{label}}</button>+ </template>;+ GJS++ sources = {+ "discourse/components/example.gjs" => example,+ "discourse/lib/plain.js" => "export const MAX_LENGTH = 50;\n",+ "discourse/initializers/example-source.js" => <<~JS,+ import whole from "../components/example.gjs?source=file";+ import template from "../components/example.gjs?source=template";+ import extensionless from "../components/example?source=template";+ import templateless from "../lib/plain.js?source=file";++ globalThis.whole = whole;+ globalThis.template = template;+ globalThis.extensionless = extensionless;+ globalThis.templateless = templateless;+ JS+ }++ result =+ AssetProcessor.new.rollup(+ sources,+ { entrypoints: { main: { modules: ["discourse/initializers/example-source.js"] } } },+ )++ context = MiniRacer::Context.new+ code = entrypoint(result, "main")["code"].sub(/export \{.*\};\s*\z/, "")+ context.eval(code)++ aggregate_failures do+ expect(context.eval("globalThis.whole")).to eq(example.strip)+ expect(context.eval("globalThis.template")).to eq(+ '<button type="button">{{label}}</button>',+ )+ expect(context.eval("globalThis.extensionless")).to eq(+ '<button type="button">{{label}}</button>',+ )+ expect(context.eval("globalThis.templateless")).to eq("export const MAX_LENGTH = 50;")+ end+ ensure+ context&.dispose+ end++ it "can import the source of a template-only module" do+ sources = {+ "discourse/components/tmpl.hbs" => "<div>Hello {{name}}</div>",+ "discourse/initializers/example-source.js" => <<~JS,+ import exampleSource from "../components/tmpl.hbs?source=file";++ globalThis.exampleSource = exampleSource;+ JS+ }++ result =+ AssetProcessor.new.rollup(+ sources,+ { entrypoints: { main: { modules: ["discourse/initializers/example-source.js"] } } },+ )++ context = MiniRacer::Context.new+ code = entrypoint(result, "main")["code"].sub(/export \{.*\};\s*\z/, "")+ context.eval(code)++ expect(context.eval("globalThis.exampleSource")).to eq("<div>Hello {{name}}</div>")+ ensure+ context&.dispose+ end++ it "rejects source imports it cannot read" do+ # `discourse-colocation` resolves a .js id for a component that only exists as a+ # colocated .hbs, so this reaches the source plugin with nothing behind it.+ sources = {+ "discourse/components/colocated.hbs" => "<div>Example</div>",+ "discourse/initializers/example-source.js" => <<~JS,+ import exampleSource from "../components/colocated.js?source=file";++ globalThis.exampleSource = exampleSource;+ JS+ }++ expect do+ AssetProcessor.new.rollup(+ sources,+ { entrypoints: { main: { modules: ["discourse/initializers/example-source.js"] } } },+ )+ end.to raise_error(AssetProcessor::TranspileError, /ENOENT/)+ end++ it "rejects source imports from outside the bundle" do+ sources = { "discourse/initializers/example-source.js" => <<~JS }+ import exampleSource from "discourse/components/external.gjs?source=file";++ globalThis.exampleSource = exampleSource;+ JS++ expect do+ AssetProcessor.new.rollup(+ sources,+ { entrypoints: { main: { modules: ["discourse/initializers/example-source.js"] } } },+ )+ end.to raise_error(AssetProcessor::TranspileError, /Cannot import source from/)+ end+it "supports decorators and class properties without error" doscript = <<~JS.chompexport default class MyClass {