@unframework.dev/unplugin 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,421 @@
1
- # Temporary Holding Version
1
+ # @unframework.dev/unplugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Unframework bundler plugin (plan §8.2). An import of a `.uf.tsx` file compiles it to one
4
+ framework's source with `compile()` from `@unframework.dev/compiler`, under a module id that the
5
+ framework's own Vite plugin claims, and that plugin finishes the job.
6
+
7
+ ```ts
8
+ // vite.config.ts
9
+ import unframework from "@unframework.dev/unplugin/vite";
10
+ import vue from "@vitejs/plugin-vue";
11
+
12
+ export default {
13
+ plugins: [unframework({ target: "vue" }), vue()],
14
+ };
15
+ ```
16
+
17
+ ```ts
18
+ import Hello from "./Hello.uf.tsx"; // a Vue component
19
+ ```
20
+
21
+ `unframework(options)` returns two plugins, `[pre, post]`. Put them before the framework's
22
+ plugins.
23
+
24
+ On Vite you can leave `target` out, and the framework's plugin in your configuration decides it:
25
+
26
+ ```ts
27
+ export default {
28
+ plugins: [unframework(), vue()],
29
+ };
30
+ ```
31
+
32
+ See [Target detection](#target-detection) for what it looks for.
33
+
34
+ ## Bundlers
35
+
36
+ There's one entry per bundler unplugin offers, each with the same options: `./bun`, `./esbuild`,
37
+ `./farm`, `./rolldown`, `./rollup`, `./rsbuild`, `./rspack`, `./unloader`, `./vite` and `./webpack`.
38
+ `unframeworkUnplugin`, from the `.` entry, holds them all. We test only Vite end to end, and trust
39
+ the rest to work through unplugin's generic hooks (ADR-0075), so a test only creates a plugin from
40
+ each entry. Keep in mind that a module id still needs a plugin of that bundler's to claim it, like
41
+ a Vue plugin for `.vue`, and that we recommend Vite until the other bundlers have been tried.
42
+
43
+ Only Vite detects a target, from its configuration's plugins, so every other entry throws without a
44
+ `target`.
45
+
46
+ `resolveId`, `load`, the watch edges and the guard are generic hooks, and `watchChange` hands an
47
+ edit to the project's `update` as soon as the bundler reports it. unplugin maps no such hook onto
48
+ esbuild or Bun, so there the next load's comparison finds the edit. Only what Vite alone has sits
49
+ under `vite:`:
50
+
51
+ - **Its config**, for the root, target detection and UF7010 (`configResolved`).
52
+ - **Its dependency scan**, which sets `scan`, so `vite:` has a `resolveId` that replaces the generic one and calls the same function.
53
+ - **Its environments**, which keep the guard's verdicts apart, so `vite:` has a `load` and a `transform` of its own in the same way. Any other bundler has one set of verdicts.
54
+ - **The `api`**, which reads the compiled sources.
55
+
56
+ The project's root is Vite's `root`, webpack's or Rspack's `compiler.context`, esbuild's
57
+ `absWorkingDir`, or else `process.cwd()`, which Rsbuild, Rolldown, Rollup and the others get.
58
+
59
+ A bundler whose hook context has `this.resolve`, like Rollup, Rolldown and Vite, resolves a specifier
60
+ itself, so aliases and [a package's sources](#packages-that-ship-sources) work. Without it, as on esbuild and webpack, a specifier must be a path: `./Hello.uf`,
61
+ `./Hello.uf.js` and `./Hello.uf.jsx` find `Hello.uf.tsx` or `Hello.uf.ts` beside the importer. A
62
+ package's specifier and an alias are left to the bundler, and a `.uf.tsx` file they resolve to
63
+ fails in `load` on a target whose ids have a suffix.
64
+
65
+ Any styling engine works through the virtual modules its own Vite plugin registers (plan §4.4,
66
+ ADR-0064). An import whose specifier starts with a `passThrough` prefix (`virtual:` by default)
67
+ reaches every output as written, and this plugin never resolves it: the engine's plugin does. Add
68
+ that plugin beside this one. Both run `enforce: "pre"` and neither claims the other's ids, so their
69
+ order doesn't matter. Styleframe, the engine the corpus tests with, is an example. We list its
70
+ plugin first, as its installation guide does:
71
+
72
+ ```ts
73
+ import styleframe from "styleframe/plugin/vite";
74
+
75
+ export default {
76
+ plugins: [styleframe(), unframework({ target: "vue" }), vue()],
77
+ };
78
+ ```
79
+
80
+ ```tsx
81
+ import { button } from "virtual:styleframe";
82
+ import "virtual:styleframe.css";
83
+ ```
84
+
85
+ Styleframe's scanner reads utility classes in a `.tsx` file's `className` only. For utilities
86
+ written in a `.uf.tsx` file's `class`, give it an extractor that reads `class` too, as the
87
+ integration harness does (`sourceUtilities` in `tests/integration/harness/styleframe.ts`).
88
+
89
+ ## Options
90
+
91
+ | Option | Meaning |
92
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
93
+ | `target` | A built-in target's name (`"react"`, `"vue"`, `"svelte"`, `"solid"`, `"angular"`, `"qwik"`, `"astro"`) or a third-party `Target`. Optional on Vite, which detects a built-in target. Required on every other bundler. |
94
+ | `extension` | What module ids append to the `.uf.tsx` path. Built-in targets have one; a third-party target must set it. |
95
+ | `onCompile` | Called each time a module loads, with `{ id, file, target, files, diagnostics }`. Returning a string (or a promise of one) fails that module with it: the integration harness's golden guard. |
96
+ | `plugins` | Compiler plugins, passed to `compile()` (the harness's canaries). |
97
+ | `format` | Formats the output with oxfmt. Defaults to `true`, so a module's code equals the golden file byte for byte. |
98
+ | `passThrough` | The specifier prefixes whose imports pass through to every output as written, passed to `compile()`. Defaults to `["virtual:"]`; a list replaces it, as `["virtual:", "styled-system/"]` adds an engine that generates files. A prefix that is empty, relative or absolute fails when the plugin is created. |
99
+
100
+ ## The dev server's allow list
101
+
102
+ On a Vite dev server, a `.uf.tsx` file outside `server.fs.allow` gets the same 403 as any other
103
+ file there, whichever id a request names it by: the file itself, its module id, a component id or
104
+ its scoped sheet's id, with any query. The plugin reads and compiles the file in `load`, where
105
+ Vite's own check never runs, so `load` asks Vite's `isFileLoadingAllowed` first. That honours
106
+ `server.fs.strict` and `server.fs.deny` as Vite does, and with `strict` off nothing is refused.
107
+
108
+ A file that a served module imports still loads, even from outside the allow list, because Vite
109
+ records the id it was imported by as safe, and `load` accepts that id as well as the file. So a
110
+ child component next to your project, or a package's shipped sources from a linked directory,
111
+ load as soon as something you serve imports them. Only the client environment is checked, since a
112
+ server environment's loads come from your own server code, which Vite lets read any file, and a
113
+ build is never checked. A `.uf.ts` module of composables isn't covered yet.
114
+
115
+ ## Target detection
116
+
117
+ With `target` left out, Vite's `configResolved` reads the plugin names in your configuration. A
118
+ name matches as this table writes it, so `vite:vue-jsx` and `vite-plugin-qwik-post` name no framework:
119
+
120
+ | Target | Plugin name | Plugin |
121
+ | ------- | ------------------------------- | ------------------------------- |
122
+ | Vue | `vite:vue` | `@vitejs/plugin-vue` |
123
+ | Svelte | `vite-plugin-svelte` | `@sveltejs/vite-plugin-svelte` |
124
+ | React | `vite:react-*` | `@vitejs/plugin-react` |
125
+ | Solid | `solid` | `vite-plugin-solid` |
126
+ | Qwik | `vite-plugin-qwik` | `qwikVite` from Qwik |
127
+ | Astro | `astro:*` | Astro's own plugins |
128
+ | Angular | `@analogjs/vite-plugin-angular` | `@analogjs/vite-plugin-angular` |
129
+
130
+ No match fails the start of a dev server or a build with UF7005, and plugins of two frameworks with
131
+ UF7006, which names them. Keep in mind that an Astro app that also adds a framework's plugin holds both, so pass
132
+ `target` there. Until the target is known the hooks' filters match every target's suffix, or only
133
+ `extension` when you set it, and once it's known the hooks leave the other targets' module ids alone. A third-party target is never detected.
134
+
135
+ On Vue, whichever way the target was chosen, plugin-vue's `template.compilerOptions.whitespace` of
136
+ `"preserve"` reports the warning UF7010 at the start, because outputs assume `"condense"`
137
+ (ADR-0026).
138
+
139
+ On Vue, the plugin also fills plugin-vue's `script.fs` with Node's file system when the app left it
140
+ unset, through plugin-vue's `api.options` (ADR-0082). Vue's `compileScript` reads a props type
141
+ imported from another module through it, or through TypeScript's `sys`, which TypeScript 7 doesn't
142
+ export. An app's own `script.fs` stays, and the fill reaches the app's own `.vue` files too.
143
+
144
+ ## Module ids
145
+
146
+ A module id is the absolute path of the `.uf.tsx` file plus the target's suffix (`ID_SUFFIXES`):
147
+
148
+ | Target | Module id | Claimed by |
149
+ | ------------------ | -------------------------- | ----------------------------------------- |
150
+ | React, Solid, Qwik | `/abs/Hello.uf.tsx` | the JSX transform, which claims `.tsx` |
151
+ | Vue | `/abs/Hello.uf.tsx.vue` | plugin-vue |
152
+ | Svelte | `/abs/Hello.uf.tsx.svelte` | vite-plugin-svelte |
153
+ | Astro | `/abs/Hello.uf.tsx.astro` | Astro's plugin |
154
+ | Angular | `/abs/Hello.uf.tsx.ts` | `ngtscVirtual` (Analog only claims `.ts`) |
155
+
156
+ - The code comes from `load`, never `transform`: nothing exists on disk at a module id, and every
157
+ framework plugin compiles the code it is given. Ids never start with `\0`, which the framework
158
+ plugins skip.
159
+ - `load` returns `{ code, map }` from `compile({ sourceMap: true })` (ADR-0074), and that map traces
160
+ to the `.uf.tsx` line on every target. What it becomes after the framework's plugin differs. React
161
+ and Solid still reach the `.uf.tsx` in dev and in a build, and Vue does in dev, while a Vue build
162
+ traces to the `.vue` id. On Vite, in dev, three targets take a step from `src/chain.ts` so that a
163
+ thrown error reaches its line: Svelte's compile doesn't merge the load map itself, a Qwik segment's
164
+ map goes on through its module's, and Astro's load map has a segment at column 0 of each line,
165
+ which is where its compiler traces from (ADR-0074, ADR-0078). L14 covers these in dev only.
166
+ An output with no map loads as `{ code }`. A scoped sheet's load is `{ code }` too, since its map has no segments.
167
+ - An id loads the target's output file with the id's extension (`Hello.vue`, `hello.ts`, and
168
+ `Hello.tsx` for a `.uf.tsx` id). A file with several components emits one such file each:
169
+ `.tsx` and `.ts` files are joined into one module (an import of a file of the join is left out,
170
+ an import an earlier file already made is written once, and any other name two files declare
171
+ or export is an error). The joined module's map goes through each file's own to its source, and
172
+ a file with no map stays unmapped in it. A shared `.ts` module's copy (ADR-0070) is no component's file, so no
173
+ join holds it: the output imports the module itself. On a markup target the module id loads the file's main component (its
174
+ default export, or its only exported component), and each other component loads under a
175
+ component id, `<abs>/X.uf.tsx.<output file>` (`/src/Card.uf.tsx.CardIcon.vue`, ADR-0053),
176
+ which ends in the extension the framework's plugin claims.
177
+ - That error stops two components that share a type declared in their own file: each output
178
+ declares the types its props reach, so `joinModules` reports the type as "declared by A.tsx and
179
+ B.tsx" (ADR-0034). Two outputs that print the same inline helper, such as React's `cx`, clash
180
+ the same way, and so do two imports from one module whose sets differ but share a name
181
+ (Angular's `Component` beside `Component` and `input`, Solid's `Show` beside `Show` and `For`,
182
+ or `{ CardProps }` beside `{ CardProps, Tone }` from a shared `.ts` module): only an identical
183
+ import is written once, and a name two imports bring in is declared twice. Give each such
184
+ component its own `.uf.tsx` file.
185
+ - A script module keeps the `.uf.tsx` file's exports. A `.vue`, `.svelte` or `.astro` module has
186
+ only a default export, so markup targets refuse a main component exported by name
187
+ (`export function Hello`), rather than load a module where `import { Hello }` finds nothing.
188
+ - `moduleId`, `parseModuleId`, `componentId`, `parseComponentId` and `idSuffix` build and take
189
+ these ids apart.
190
+ - **The project** (ADR-0071). Every file compiles through one project graph (`createProject`, from
191
+ `@unframework.dev/compiler`) at the project's root, shared by every module the plugin loads. Before
192
+ a load, the plugin compares each file the module reaches through the project's edges, and
193
+ each file of a package it read types from, with what the project holds of it, and hands the
194
+ changed ones to the project's `update` under every name it knows them by: relative to the
195
+ root, and `pkg:<name>` for a file of a package any module reached, where `<name>` is the name
196
+ in the file's nearest `package.json` that has one. The
197
+ project compiles again only the modules whose inputs changed, those loaded for other ids
198
+ included, and stops where a shape is unchanged. A first compile may reach a file the project
199
+ still holds as it was for another module, so the plugin checks again after it. So a compile is
200
+ reused while its file and every file it reached hold what they held, with or without the
201
+ bundler's watcher. Where the bundler has `watchChange`, it hands a changed file over before the
202
+ next load. The outputs a load sees hold the copies of the shared `.ts` modules the file reaches
203
+ (ADR-0070), as `compile()`'s do, so the golden guard judges them.
204
+ - **Children** (ADR-0053). The project resolves a file's imports, so a parent lowers its children
205
+ by their APIs. An output imports a child's output by its file
206
+ (`./Field.vue`): such a relative import from one of the plugin's modules, or from a segment
207
+ Qwik's optimizer splits off one (`Form.uf.tsx_Form_component_<hash>.js`), is looked up in the
208
+ importer's compile and resolves to the child's module id, or its component id on a markup
209
+ target where it is not its file's main component.
210
+ - **Types** (ADR-0067). The project reads types through one syntactic type oracle created at
211
+ the project's root (`createSyntacticOracle`, from `@unframework.dev/compiler`): a props type may come from
212
+ another file or a package, and a child's API from its types' shapes. The oracle follows the
213
+ source's imports, so it may read a TypeScript file outside the root.
214
+
215
+ - **Composables** (ADR-0069). A `.uf.ts` file loads under its absolute path plus the suffix the
216
+ framework's plugin claims for a TypeScript module (`COMPOSABLE_ID_SUFFIXES`):
217
+
218
+ | Target | Module id of `useToggle.uf.ts` | Claimed by |
219
+ | ------------------------ | -------------------------------- | ------------------------------------------------------------- |
220
+ | React, Vue, Solid, Astro | `/abs/useToggle.uf.ts` | Vite's own TypeScript transform |
221
+ | Qwik | `/abs/useToggle.uf.ts` | Qwik's optimizer |
222
+ | Svelte | `/abs/useToggle.uf.ts.svelte.ts` | vite-plugin-svelte, which compiles runes in `.svelte.ts` only |
223
+ | Angular | `/abs/useToggle.uf.ts.ts` | `ngtscVirtual` |
224
+
225
+ A third-party target's composables load under the `.uf.ts` id. The id loads every composable
226
+ the target's `emitComposable` emitted for the file, joined into one module. An output's relative
227
+ import of a composable's output (`./useToggle`, `./useToggle.svelte.ts`, `./use-toggle`) is
228
+ looked up in the importer's compile, as a child's is, and resolves to the module's id. A
229
+ third-party target without `emitComposable` fails the module with UF1002.
230
+ `composableIdSuffix`, `composableId` and `parseComposableId` build and take these ids apart.
231
+
232
+ How `resolveId` answers:
233
+
234
+ - **An import of a `.uf.tsx` file** resolves through the bundler (so aliases work on Vite and
235
+ Rollup's family, see [Bundlers](#bundlers)), then gets the suffix.
236
+ What decides is the file the specifier resolves to, so the forms TypeScript accepts for it,
237
+ `./Hello.uf` (`moduleResolution: "bundler"`) and `./Hello.uf.js` or `./Hello.uf.jsx`
238
+ (`"nodenext"`), compile like `./Hello.uf.tsx`. An import of a `.uf.ts` file, or a `./X.uf` that
239
+ resolves to one, gets the composables' suffix. A query stays on the id (`./Hello.uf.tsx?container` loads
240
+ `/abs/Hello.uf.tsx.astro?container`), except Vite's `?raw`, `?url`, `?worker` and
241
+ `?sharedworker`, which mean the authored file.
242
+ - **A module id coming back** maps to the absolute id with its query: an absolute id from a plugin,
243
+ a root-relative URL from the browser (`/cases/hello/Hello.uf.tsx.vue`), or a path relative to
244
+ its importer (`./Hello.uf.tsx.vue`). Ids keep Vite's forward slashes on every platform.
245
+ - **The dependency scan** (`scan: true`, set by Vite's optimizer and missing from its public type)
246
+ gets `\0uf-scan:<abs>` (`SCAN_ID_PREFIX`). The scanner reads every id it gets from disk with its
247
+ own loaders, so a module id would fail the whole scan, and the authored file would expose its
248
+ compile-time imports as dependencies; it externalises ids that contain `\0`. Each target's
249
+ toolchain lists the runtime imports of its compiled output in `optimizeDeps.include` instead.
250
+ - **A scoped sheet** (ADR-0063), `./Hello.uf.tsx.css`, which every target's output imports for
251
+ a component with a stylesheet, resolves to `/abs/Hello.uf.tsx.css` with its query, from one of
252
+ the plugin's modules or a segment Qwik's optimizer splits off one (`?inline`), and so does its
253
+ id coming back. It is checked before an output's import of another output, and it is no
254
+ component's output, so `owners` never names it. The id ends in `.css`, without a `\0`, so
255
+ Vite's CSS pipeline handles it; from any other importer it is left to Vite, which finds no
256
+ such file.
257
+ - **The watch edges** (ADR-0071). The pre plugin's `transform` calls
258
+ `this.addWatchFile(<abs>.uf.tsx)` for every id but one that is the file itself. Vite resolves
259
+ that file with the module as its importer, and the plugin answers with the real file, so the
260
+ module graph holds the file as an import of the module: editing it invalidates the module and
261
+ reruns `vitest --watch`. (In `load`, Vite would drop the file when a cold request's module is
262
+ not in its graph yet.) It adds an edge to every file the project says the output depends on,
263
+ directly or through another module: each child's `.uf.tsx`, each composable's `.uf.ts`, each
264
+ shared `.ts` module, each stylesheet and each file a type was read from, a linked workspace
265
+ package's included. So an edit to `Field.uf.tsx` invalidates `Form`'s module, and an edit to
266
+ the `.ts` file that declares a props type invalidates every module that reads the type, through
267
+ a composable too. A module of composables gets the same edges. Following another module's edges
268
+ may add one the output does not read, such as a grandchild's: an edit to it transforms the
269
+ module again, and the project compiles nothing. A package's files in `node_modules` get none,
270
+ since Vite's watcher ignores them, and neither does a file that does not exist yet, since Vite's
271
+ import analysis fails an import it cannot resolve: the next load still compares both.
272
+ - **Hot updates** (ADR-0075). On Vite, `hotUpdate` routes a changed, created or deleted file through
273
+ the project, in each environment, and answers with every module of each file the project
274
+ compiled again: its main module, its other components, its module of composables, its Qwik
275
+ segments and its scoped sheet, plugin-vue's style queries included. An edit of a stylesheet
276
+ updates the sheet and the markup together, because the scope id hashes the sheet's text
277
+ (ADR-0063). When the project compiled nothing, the plugin's modules and the nodes only its
278
+ watch edges put in the graph leave Vite's list, so nothing is sent. A module the plugin doesn't
279
+ own keeps Vite's handling, and a framework's own HMR does the rest: React, Vue, Svelte and Solid
280
+ send an update, and Astro does a full reload with the new content. Qwik's own plugin reloads the
281
+ page, or sends its `qwik:hmr` update, from the `ssr` environment only, so it does that for a
282
+ server-rendered app. For a client-rendered one, whose `ssr` environment holds none of the
283
+ change's modules, the plugin invalidates its modules and sends the full reload itself from the
284
+ client environment, whatever Qwik's hot-update setting. That way a stylesheet edit never meets
285
+ the sheet Qwik's `useStyles$` added first.
286
+
287
+ `load` answers a scoped sheet's id with the sheet this target's compile emitted, whatever its
288
+ query: plugin-vue's request for `<style src>` (`?vue&type=style&index=0&src=true&lang.css`), which
289
+ the plugin serves before plugin-vue reads the disk, and Qwik's `?inline` give the same text. The
290
+ author's `Hello.css` is never loaded: no output imports it. A file that imports no stylesheet has
291
+ no sheet, and its sheet id fails.
292
+
293
+ How `load` answers any other query is decided by the query alone, never by what the process resolved
294
+ before: a parameter named after the id's extension (`?vue&type=style&index=0&lang.css`,
295
+ `?svelte&type=style&lang.css`, `?astro&type=script…`) is the framework plugin's request for a part
296
+ of the module, which `load` leaves to that plugin; Vite's file queries are left to Vite; any other
297
+ query (`?container`) loads the component, even on a cold server.
298
+
299
+ A bare specifier that maps to a `.uf.tsx` never reaches `resolveId` on a bundler whose context can't
300
+ resolve one. On Vite this plugin also leaves a specifier that hides the extension to the plugin that
301
+ resolves it, and never sees a file a plugin answers for before this one.
302
+
303
+ On React, Solid and Qwik the resolved id is the module id, so it compiles anyway. On the other targets the authored
304
+ file would load as plain TSX, so `load` fails it with the fix: import it with a specifier that ends
305
+ in `.uf.tsx`. A `.uf.ts` file mapped that way loads as its composables where its id is the file
306
+ itself, and fails the same way on Svelte and Angular, whose ids have a suffix.
307
+
308
+ ## Packages that ship sources
309
+
310
+ A package can ship its `.uf.tsx` and `.uf.ts` files for its consumers to compile, through
311
+ `exports`:
312
+
313
+ ```json
314
+ {
315
+ "name": "@acme/ui",
316
+ "exports": { "./source/*": "./src/*", "./button": "./src/Button.uf.tsx" }
317
+ }
318
+ ```
319
+
320
+ ```ts
321
+ import Button from "@acme/ui/source/Button.uf.tsx";
322
+ import Same from "@acme/ui/button";
323
+ ```
324
+
325
+ Both imports load one module, on Vite and Rollup's family. What decides is the file a bare specifier
326
+ resolves to, so an entry that hides the extension works, and so does a `#` subpath import. A bare
327
+ specifier that resolves to anything else stays the bundler's. A shipped source differs from a local
328
+ one in these ways:
329
+
330
+ - **The dependency optimiser never sees the file.** `this.resolve` would register a `.uf.ts` file of
331
+ `node_modules` with Vite's optimiser, which bundles it as plain TypeScript, and a `.uf.tsx` file
332
+ too in a project that adds `.tsx` to `optimizeDeps.extensions`, so on Vite a bare specifier
333
+ asks a resolver of its own first, which only finds the file (ADR-0075). A specifier that names a
334
+ source and that resolver doesn't place in `node_modules` goes on through `this.resolve`, so
335
+ another plugin's answer works. A plugin isn't asked about a specifier that hides the extension. The dependency scan gets
336
+ the `\0uf-scan:` id, as it does for a local file. You don't need `optimizeDeps.exclude`.
337
+ - **SSR keeps the file in its module graph.** The plugin answers before Vite decides what to
338
+ externalise, and Vite never externalises a `.tsx` or `.ts` file, so you don't need `ssr.noExternal`.
339
+ - **The package has its own project graph,** with the package's root as its root (ADR-0071). So a diagnostic names a file the same way wherever the package is installed. A
340
+ file in `node_modules` finds its root by its path, and a linked workspace package outside the
341
+ project's root by its nearest named `package.json`. A compile error names the file relative to
342
+ the package, and then says where the package is.
343
+ - **Watching stops at `node_modules`,** as for a package's types. The next load still compares the
344
+ files. A linked package's files get the usual watch edges.
345
+
346
+ Keep in mind that the host file does the importing. A `.uf.tsx` file imports another component by a
347
+ relative path, so importing a package's component from one reports UF1202.
348
+
349
+ ## Diagnostics and the guard
350
+
351
+ - Warnings and info diagnostics go to `this.warn`, with their code frame, and fail no module.
352
+ - Errors fail the module through `this.error`, with `formatDiagnostics` (uncoloured): every error's
353
+ `UF` code, message and code frame. `this.error` only records the message on esbuild, which drops it, so
354
+ `load` throws the same message there.
355
+ - UF7005 and UF7006 fail the start of a dev server or a build, and UF7010 is a warning (see
356
+ [Target detection](#target-detection)).
357
+ - When `onCompile` returns a message, `load` still returns the compiled code, so the framework's
358
+ plugin compiles it, and the post plugin replaces the module's final code with
359
+ `throw new Error(message); export default undefined;` (plus the module's named exports). Its
360
+ importers still link, and the message reaches the test report. Throwing from `load` would reach
361
+ the browser as an HTTP 500, and Vitest would only report "Failed to fetch dynamically imported
362
+ module". A check that throws, or returns an empty message, fails the module too.
363
+ - Verdicts are kept per Vite environment. One plugin instance serves a server's client and ssr
364
+ environments, which load the same id concurrently, and each environment's post plugin reads the
365
+ verdict on its own load. A bundler with no environments has one set of verdicts.
366
+
367
+ ## The `api`
368
+
369
+ On Vite, the pre plugin, named `unframework`, exposes `api.getCompiled(id)`: the code of the last load of
370
+ a module id that finished, in any environment, or `undefined` when the id has not loaded or that
371
+ load failed. A load in progress never clears it. Angular's `ngtscVirtual` reads the virtual
372
+ sources of child components with it:
373
+
374
+ ```ts
375
+ const api = config.plugins.find((plugin) => plugin.name === "unframework")?.api;
376
+ api.getCompiled("/abs/Child.uf.tsx.ts");
377
+ ```
378
+
379
+ It exposes `api.getSheet(file)` too: the scoped sheet this target's last finished load of the
380
+ `.uf.tsx` file emitted, after the plugins' `output` hooks, or `undefined` when no load finished or
381
+ the file imports no stylesheet (ADR-0063). Vite never loads an Angular component's sheet: ngtsc
382
+ reads its `styleUrl` itself, so `ngtscVirtual` hands it the sheet from here.
383
+
384
+ The project caches each file's compile, so every id of a file shares one compile until the file,
385
+ or a file it reached, changes.
386
+
387
+ ## Astro
388
+
389
+ An Astro project adds the integration rather than the Vite plugin, so a page can import a `.uf.tsx`
390
+ component like any `.astro` one. It's the `./astro` entry, and it takes the plugin's options except
391
+ `target`, which it sets to `"astro"`:
392
+
393
+ ```ts
394
+ // astro.config.mjs
395
+ import unframework from "@unframework.dev/unplugin/astro";
396
+ import { defineConfig } from "astro/config";
397
+
398
+ export default defineConfig({
399
+ integrations: [unframework()],
400
+ });
401
+ ```
402
+
403
+ ```astro
404
+ ---
405
+ import Hello from "../components/Hello.uf.tsx";
406
+ ---
407
+
408
+ <Hello />
409
+ ```
410
+
411
+ `astro dev` and `astro build` both render the component, with its children and its stylesheet. The
412
+ output is static, as `@unframework.dev/target-astro` describes. The integration uses two of Astro's hooks:
413
+
414
+ - **`astro:config:setup`** adds the plugin. It also takes `.uf.tsx` files out of the dependency
415
+ scan's entries: Astro's entries match every `.tsx` file under `src`, and the scan would read one
416
+ as plain JSX. Without React's JSX runtime installed, the scan would fail with an error, and Vite
417
+ would lose the dependencies it would have found, pre-bundling those only as requests reach them.
418
+ - **`astro:config:done`** reads the final `compressHTML`, after every integration's setup. Anything
419
+ but `"jsx"`, Astro's default, logs the warning UF7010, because a component can then render
420
+ different whitespace from the other targets, and no file can pin the option (ADR-0026). The build
421
+ carries on.
@@ -0,0 +1,133 @@
1
+ import { composeJoinedMap, withLineStarts } from "@unframework.dev/codegen";
2
+ import { parseModule } from "@unframework.dev/parser";
3
+ import { Bundle, MagicString } from "magic-string";
4
+ //#region src/assemble.ts
5
+ const SCRIPT = /^\.tsx?$/;
6
+ /**
7
+ * The code for a module id: the one emitted file with the id's extension, or several script
8
+ * files joined into one module. Several markup files, and a markup component exported by name,
9
+ * are refused until composition (M3), which settles how a markup target's module exports the
10
+ * components of a file.
11
+ */
12
+ function assembleModule(input) {
13
+ const { target, filename, extension, files, exports } = input;
14
+ const matching = files.filter((file) => file.path.endsWith(extension));
15
+ if (matching.length === 0) return { error: `The ${target} target emitted no ${extension} file for ${filename} (it emitted ${files.map((file) => file.path).join(", ") || "nothing"}), so the module has no code. A target's module ids must end in the extension of the file it emits for each component.` };
16
+ if (SCRIPT.test(extension)) {
17
+ if (matching.length === 1) return loaded(matching[0], target);
18
+ const paths = matching.map((file) => file.path).join(", ");
19
+ return joinModules(matching, `${filename} compiles to ${matching.length} ${target} files (${paths})`, input.siblings);
20
+ }
21
+ if (matching.length > 1) {
22
+ const paths = matching.map((file) => file.path).join(", ");
23
+ return { error: `${filename} compiles to ${matching.length} ${target} files for one component (${paths}), and a ${extension} file holds one, so they cannot load as one module.` };
24
+ }
25
+ const named = exports.filter((entry) => entry.name !== "default");
26
+ if (named.length > 0) return { error: `${filename} exports ${named.map((entry) => `\`${entry.name}\``).join(", ")} by name, and the module of a ${extension} file has only a default export, so \`import { ${named[0].name} }\` would find nothing on the ${target} target. Export the file's main component as the default: \`export default function ${named[0].local}() { … }\`.` };
27
+ return loaded(matching[0], target);
28
+ }
29
+ /** What one file loads: its text, and its map when it has one. */
30
+ function loaded({ contents, map }, target) {
31
+ if (!map) return { code: contents };
32
+ return {
33
+ code: contents,
34
+ map: target === "astro" ? withLineStarts(map) : map
35
+ };
36
+ }
37
+ /**
38
+ * Joins script modules into one by concatenation. An import statement that an earlier file
39
+ * already wrote, character for character, is left out; any other name that two files declare
40
+ * or export would make the joined module invalid, so it is an error that names the clash. The
41
+ * text of a file with no map stays unmapped in the join's.
42
+ */
43
+ function joinModules(files, context, siblings = []) {
44
+ const joined = new Set(siblings.flatMap((path) => [`./${path}`, `./${path.replace(/\.[^./]+$/, "")}`]));
45
+ const seenImports = /* @__PURE__ */ new Set();
46
+ const declaredBy = /* @__PURE__ */ new Map();
47
+ const exportedBy = /* @__PURE__ */ new Map();
48
+ const bundle = new Bundle({ separator: "\n" });
49
+ for (const file of files) {
50
+ const parsed = parseModule(file.path, file.contents);
51
+ if (parsed.errors.length > 0) return { error: `${context}, and ${file.path} does not parse, so they cannot be joined into one module: ${parsed.errors[0].message}` };
52
+ const part = new MagicString(file.contents);
53
+ for (const statement of parsed.program.body) {
54
+ if (statement.type === "ImportDeclaration") {
55
+ const text = file.contents.slice(statement.start, statement.end);
56
+ if (joined.has(statement.source.value) || seenImports.has(text)) {
57
+ const end = file.contents[statement.end] === "\n" ? statement.end + 1 : statement.end;
58
+ part.remove(statement.start, end);
59
+ continue;
60
+ }
61
+ seenImports.add(text);
62
+ for (const specifier of statement.specifiers) record(declaredBy, specifier.local.name, file.path);
63
+ continue;
64
+ }
65
+ for (const name of declaredNames(statement)) record(declaredBy, name, file.path);
66
+ for (const name of exportedNames(statement)) record(exportedBy, name, file.path);
67
+ }
68
+ bundle.addSource({
69
+ filename: file.path,
70
+ content: part
71
+ });
72
+ }
73
+ const clashes = [...clashesOf(declaredBy).map(([name, paths]) => `\`${name}\` is declared by ${paths}`), ...clashesOf(exportedBy).map(([name, paths]) => `\`${name}\` is exported by ${paths}`)];
74
+ if (clashes.length > 0) return { error: `${context}, and they cannot be joined into one module: ${clashes.join("; ")}. Give each component its own .uf.tsx file.` };
75
+ const code = bundle.toString();
76
+ if (!files.some((file) => file.map)) return { code };
77
+ return {
78
+ code,
79
+ map: composeJoinedMap(bundle.generateMap({ hires: true }), files)
80
+ };
81
+ }
82
+ /** Notes that the file at `path` declares or exports `name`. */
83
+ function record(names, name, path) {
84
+ const paths = names.get(name) ?? [];
85
+ if (!paths.includes(path)) paths.push(path);
86
+ names.set(name, paths);
87
+ }
88
+ function clashesOf(names) {
89
+ return [...names].filter(([, paths]) => paths.length > 1).map(([name, paths]) => [name, paths.join(" and ")]);
90
+ }
91
+ /** The names a top-level statement binds in module scope (imports are handled separately). */
92
+ function declaredNames(statement) {
93
+ switch (statement.type) {
94
+ case "ExportNamedDeclaration": return statement.declaration ? declaredNames(statement.declaration) : [];
95
+ case "ExportDefaultDeclaration": {
96
+ const declaration = statement.declaration;
97
+ return (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSInterfaceDeclaration") && declaration.id ? [declaration.id.name] : [];
98
+ }
99
+ case "VariableDeclaration": return statement.declarations.flatMap((declarator) => patternNames(declarator.id));
100
+ case "FunctionDeclaration":
101
+ case "TSDeclareFunction":
102
+ case "ClassDeclaration": return statement.id ? [statement.id.name] : [];
103
+ case "TSTypeAliasDeclaration":
104
+ case "TSInterfaceDeclaration":
105
+ case "TSEnumDeclaration":
106
+ case "TSImportEqualsDeclaration": return [statement.id.name];
107
+ case "TSModuleDeclaration": return statement.id.type === "Identifier" ? [statement.id.name] : [];
108
+ default: return [];
109
+ }
110
+ }
111
+ function patternNames(pattern) {
112
+ switch (pattern.type) {
113
+ case "Identifier": return [pattern.name];
114
+ case "AssignmentPattern": return patternNames(pattern.left);
115
+ case "RestElement": return patternNames(pattern.argument);
116
+ case "ArrayPattern": return pattern.elements.flatMap((element) => element ? patternNames(element) : []);
117
+ }
118
+ return pattern.properties.flatMap((property) => patternNames(property.type === "RestElement" ? property : property.value));
119
+ }
120
+ /** The names a top-level statement exports. */
121
+ function exportedNames(statement) {
122
+ switch (statement.type) {
123
+ case "ExportDefaultDeclaration": return ["default"];
124
+ case "ExportNamedDeclaration": return statement.declaration ? declaredNames(statement.declaration) : statement.specifiers.map((specifier) => moduleExportName(specifier.exported));
125
+ case "ExportAllDeclaration": return statement.exported ? [moduleExportName(statement.exported)] : [];
126
+ default: return [];
127
+ }
128
+ }
129
+ function moduleExportName(name) {
130
+ return name.type === "Literal" ? name.value : name.name;
131
+ }
132
+ //#endregion
133
+ export { assembleModule, joinModules };
@@ -0,0 +1,11 @@
1
+ import { UnframeworkOptions } from "./plugin.js";
2
+ import { AstroIntegration } from "astro";
3
+ //#region src/astro.d.ts
4
+ /** Options of the Astro integration: the plugin's, without the target, which it sets to Astro. */
5
+ export type UnframeworkAstroOptions = Omit<UnframeworkOptions, "target">;
6
+ /**
7
+ * The unframework Astro integration: adds the Vite plugin with the Astro target, so an import of a
8
+ * `.uf.tsx` file loads as an `.astro` component, which Astro's own plugin compiles.
9
+ */
10
+ export default function unframework(options?: UnframeworkAstroOptions): AstroIntegration;
11
+ //#endregion
package/dist/astro.js ADDED
@@ -0,0 +1,38 @@
1
+ import unframework$1 from "./vite.js";
2
+ import { createDiagnostic, formatDiagnostic } from "@unframework.dev/diagnostics";
3
+ //#region src/astro.ts
4
+ /**
5
+ * The unframework Astro integration: adds the Vite plugin with the Astro target, so an import of a
6
+ * `.uf.tsx` file loads as an `.astro` component, which Astro's own plugin compiles.
7
+ */
8
+ function unframework(options = {}) {
9
+ return {
10
+ name: "unframework",
11
+ hooks: {
12
+ "astro:config:setup": ({ updateConfig }) => {
13
+ updateConfig({ vite: {
14
+ plugins: [unframework$1({
15
+ target: "astro",
16
+ ...options
17
+ })],
18
+ optimizeDeps: { entries: ["!**/*.uf.tsx"] }
19
+ } });
20
+ },
21
+ "astro:config:done": ({ config, logger }) => {
22
+ if (config.compressHTML === "jsx") return;
23
+ const diagnostic = createDiagnostic("UF7010", {
24
+ file: "astro.config",
25
+ span: {
26
+ start: 0,
27
+ end: 0
28
+ },
29
+ message: `Astro's compressHTML is ${String(config.compressHTML)}, and outputs assume "jsx", so a component can render different whitespace from the other targets.`,
30
+ help: "Remove the option, or set it to \"jsx\"."
31
+ });
32
+ logger.warn(formatDiagnostic(diagnostic, void 0));
33
+ }
34
+ }
35
+ };
36
+ }
37
+ //#endregion
38
+ export { unframework as default };
package/dist/bun.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { bun } from "./plugin.js";
2
+ export { bun as default };
package/dist/bun.js ADDED
@@ -0,0 +1,2 @@
1
+ import { bun } from "./plugin.js";
2
+ export { bun as default };