jq79 0.7.7 → 0.7.9

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
@@ -112,7 +112,8 @@ hands back a pending component you can mount right away:
112
112
  </script>
113
113
  ```
114
114
 
115
- `fetchAll([...])` fetches several at once instead. See
115
+ `fetchAll([...])` fetches several at once instead, and `importAll([...])` takes
116
+ components and modules alike, like a `Promise.all` of `import()`s. See
116
117
  [loading remote components](docs/components.md#loading-remote-components).
117
118
 
118
119
  The library also exports `parseComponent(source)` as a shorthand for
@@ -172,7 +173,7 @@ When the fetch resolves, the assignments to `firstName`/`lastName` re-run the `$
172
173
  ## Documentation
173
174
 
174
175
  - [Tutorial](https://jgermade.github.io/jq79/tutorial/) — learn it by doing, in the browser.
175
- - [Components](docs/components.md) — lifecycle (`mount`, `mountShadow`, `detach`, `destroy`), instance events (`on`/`off`), `<style scoped>`, several components in one file with `<template name>`, loading remote components with `Component79.fetch` (chainable — fetch and mount in one expression) and `fetchAll`, and `Component79.version`.
176
+ - [Components](docs/components.md) — lifecycle (`mount`, `mountShadow`, `detach`, `destroy`), instance events (`on`/`off`), `<style scoped>`, several components in one file with `<template name>`, loading remote components with `Component79.fetch` (chainable — fetch and mount in one expression), `fetchAll` and `importAll`, and `Component79.version`.
176
177
  - [Template syntax](docs/template-syntax.md) — `{{ }}` interpolation, `:name` attribute bindings, `:text`/`:html`, `:if`/`:elseif`/`:else`, `:each`/`:key`, `:with`, `@event` listeners and modifiers, nested components.
177
178
  - [Setup scripts](docs/setup-scripts.md) — `<script :setup>` reactive scripts, `$:` declarations, `$emit`, `await $mounted()`, `$self`/`$$self`, and `export default` factory scripts (plain-JS alternative).
178
179
  - [Reactive data](docs/reactive-data.md) — the standalone `$reactive` store: `$on`, `$onAny`, `$effect`, and `$computed` for derived values.
package/dev/vite.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFile } from "node:fs/promises"
2
- import { basename, relative } from "node:path"
2
+ import { posix, relative } from "node:path"
3
3
  import { preprocessCSS, transformWithEsbuild } from "vite"
4
4
  import type { Plugin, ResolvedConfig } from "vite"
5
5
  // by package name rather than ../src: this file's types are emitted with dev/
@@ -35,8 +35,8 @@ export interface Jq79PluginOptions {
35
35
  // run the app without eval, for a CSP with no 'unsafe-eval' - the value
36
36
  // Component79.safeEval() takes, and meaning the same thing
37
37
  // (RECORD/2026-09-23.no-unsafe-eval.md). Every component is precompiled, and
38
- // its functions ship as a script of their own. `true`: those and nothing
39
- // else - whatever the build couldn't see is reported, never evaluated.
38
+ // their functions ship as one script beside the bundle. `true`: those and
39
+ // nothing else - whatever the build couldn't see is reported, never evaluated.
40
40
  // `{ nonce: true }`: whatever it couldn't see (a component built from a
41
41
  // string, an edit during HMR) is built as a <script> carrying the page's nonce
42
42
  safeEval?: boolean | { nonce?: boolean }
@@ -46,20 +46,23 @@ export interface Jq79PluginOptions {
46
46
  // Vite's own html handling (entries, asset pipeline) leaves them alone
47
47
  const COMPONENT_QUERY = "?jq79"
48
48
 
49
- // safeEval. A component's precompiled functions travel as a classic script of
50
- // their own - Card.html.jq79.js - and not inside its module: they compile
51
- // under `with`, which is a SyntaxError in strict code, and every module is
52
- // strict. In a build the script is an asset beside the chunk; in dev the
53
- // server hands it out (PRECOMPILED_PATH). Either way it pushes its functions
54
- // onto the queue the runtime drains (see "safe eval" in src/jq79.ts).
49
+ // safeEval. Precompiled functions travel as a classic script, and not inside
50
+ // a module: they compile under `with`, which is a SyntaxError in strict code,
51
+ // and every module is strict. In a build it is one script for every component
52
+ // - jq79-precompiled-[hash].js, an asset beside the chunks - and the pages that
53
+ // need it preload it (RECORD/2026-11-04.one-precompiled-script.md); in dev each
54
+ // component has its own, which the server hands out (PRECOMPILED_PATH). Either
55
+ // way it pushes its functions onto the queue the runtime drains (see "safe
56
+ // eval" in src/jq79.ts).
55
57
  //
56
58
  // The component's module waits for it - a top-level await - before it builds
57
59
  // anything, through a module every component module imports. That module
58
60
  // evaluates once, so safe mode is turned on once per app, and a page with no
59
61
  // nonce is reported once rather than once per component; and it loads each
60
- // script once, however many modules ask. The <script> carries the page's
61
- // nonce when there is one, so a CSP that works by nonce admits it; under
62
- // `script-src 'self'` the URL is what admits it.
62
+ // script once, however many modules ask - in a build they all ask for the
63
+ // same one, so the first await downloads it and the rest resolve at once. The
64
+ // <script> carries the page's nonce when there is one, so a CSP that works by
65
+ // nonce admits it; under `script-src 'self'` the URL is what admits it.
63
66
  //
64
67
  // Component79 is passed in rather than imported, so the module resolves
65
68
  // nothing: a bare "jq79" from a virtual importer is the one resolution that
@@ -105,6 +108,16 @@ export const safeEval = (Component79, url) => {
105
108
  // where the dev server hands out a component's precompiled script
106
109
  const PRECOMPILED_PATH = "/@jq79/precompiled.js"
107
110
 
111
+ // a build's one precompiled script, named as an asset: assets/jq79-precompiled-[hash].js
112
+ const PRECOMPILED_ASSET = "jq79-precompiled.js"
113
+ // what a component's module passes for that script's URL in a build. The asset
114
+ // is emitted in buildEnd, once every component is known - Rolldown has no
115
+ // setAssetSource to fill it in later, and a module is loaded before the build
116
+ // knows the rest - so a module can't name it by reference when it's loaded;
117
+ // renderChunk writes the URL over this
118
+ const PRECOMPILED_URL_PLACEHOLDER = "__JQ79_PRECOMPILED_URL__"
119
+ const PRECOMPILED_URL_PLACEHOLDER_RE = /(["'`])__JQ79_PRECOMPILED_URL__\1/g
120
+
108
121
  // the plugin's safeEval option, as what the modules pass the runtime: null
109
122
  // for off, or Component79.safeEval's own options
110
123
  const safeEvalOptions = (option: Jq79PluginOptions["safeEval"]): { nonce?: boolean } | null => {
@@ -116,21 +129,86 @@ const safeEvalOptions = (option: Jq79PluginOptions["safeEval"]): { nonce?: boole
116
129
  // doesn't compile, so only the `with` form's failure is worth a word
117
130
  const SCOPED_BODY_RE = /^(?:let \$t;| return \()/
118
131
 
119
- // a component's precompiled functions, as the classic script that registers
120
- // them (precompiledScript, in jq79/precompile). Each is compiled here first -
121
- // node can, where the page may not - so the script holds only functions that
122
- // parse; one that doesn't ships as null, and the build says so
123
- const componentScript = (source: string, warn: (message: string) => void): string =>
124
- precompiledScript(precompile(source), (params, body) => {
132
+ // one precompiled function, and whether it parses
133
+ type CheckedFunction = [params: string[], body: string, parses: boolean]
134
+
135
+ // a component's precompiled functions, each compiled here first - node can,
136
+ // where the page may not - so a script holds only functions that parse; one
137
+ // that doesn't ships as null, and the build says so, once, with its file
138
+ const componentFunctions = (source: string, warn: (message: string) => void): CheckedFunction[] =>
139
+ precompile(source).map(([params, body]) => {
125
140
  try {
126
141
  new Function(...params, body)
127
- return true
142
+ return [params, body, true]
128
143
  } catch (error) {
129
144
  if (!SCOPED_BODY_RE.test(body)) warn(`${(error as Error).message}, in: ${body.length > 120 ? `${body.slice(0, 120)}…` : body}`)
130
- return false
145
+ return [params, body, false]
131
146
  }
132
147
  })
133
148
 
149
+ // the classic script that registers functions (precompiledScript, in
150
+ // jq79/precompile): one component's in dev, every component's in a build. One
151
+ // push, each function once - the runtime keys them by (params, body), so
152
+ // `{{ name }}` written in ten components is one function, and a second entry
153
+ // would only replace the first with itself
154
+ const registeringScript = (functions: CheckedFunction[]): string => {
155
+ const unique = new Map<string, CheckedFunction>()
156
+ for (const fn of functions) {
157
+ const key = JSON.stringify([fn[0], fn[1]])
158
+ if (!unique.has(key)) unique.set(key, fn)
159
+ }
160
+ return precompiledScript(
161
+ [...unique.values()].map(([params, body]) => [params, body]),
162
+ (params, body) => unique.get(JSON.stringify([params, body]))?.[2] ?? false
163
+ )
164
+ }
165
+
166
+ type BundleFile = { type: string; fileName: string; moduleIds?: string[]; imports?: string[] }
167
+
168
+ // whether a page's entry chunk waits for the precompiled script as it loads:
169
+ // it, or a chunk it imports statically, holds a component module. A component
170
+ // behind import() asks for the script when it is imported, and a preload the
171
+ // page doesn't use straight away only earns a warning in the console
172
+ const reachesComponent = (entry: BundleFile, bundle: Record<string, BundleFile>): boolean => {
173
+ const seen = new Set<string>()
174
+ const visit = (chunk: BundleFile | undefined): boolean => {
175
+ if (!chunk || chunk.type !== "chunk" || seen.has(chunk.fileName)) return false
176
+ seen.add(chunk.fileName)
177
+ return (chunk.moduleIds ?? []).some(id => id.endsWith(COMPONENT_QUERY)) || (chunk.imports ?? []).some(file => visit(bundle[file]))
178
+ }
179
+ return visit(entry)
180
+ }
181
+
182
+ // a <script src>, quote-aware, and not a data-src
183
+ const SCRIPT_SRC_RE = /<script\b(?:"[^"]*"|'[^']*'|[^>"'])*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi
184
+
185
+ // `file` as the page has to write it to get the URL a module asks for: the
186
+ // file relative to the module's chunk, against that chunk's own URL - which
187
+ // is what new URL(..., import.meta.url) resolves. The chunk's URL is read off
188
+ // the page, from the <script src> Vite wrote for it, so `base`, a relative
189
+ // base and renderBuiltUrl are already in it. Any of the bundle's chunks will
190
+ // do, because chunks import each other by relative path - and it has to be
191
+ // any: an entry that is nothing but imports gets no <script> of its own, only
192
+ // its imports do. null when no script on the page loads one of them: no
193
+ // preload is better than one at the wrong URL, which downloads twice
194
+ const precompiledHref = (html: string, bundle: Record<string, BundleFile>, file: string): string | null => {
195
+ const chunks = Object.values(bundle).filter(out => out.type === "chunk").map(out => out.fileName)
196
+ for (const match of html.matchAll(SCRIPT_SRC_RE)) {
197
+ const src = (match[1] ?? match[2] ?? match[3]).replace(/[?#].*$/, "")
198
+ const chunk = chunks.find(name => src === name || src.endsWith(`/${name}`))
199
+ if (chunk === undefined) continue
200
+ const path = posix.relative(posix.dirname(chunk), file)
201
+ // a full URL, or a protocol-relative one
202
+ if (/^(?:[a-z][a-z\d+.-]*:)?\/\//i.test(src)) {
203
+ const scheme = src.startsWith("//") ? "https:" : ""
204
+ return new URL(path, scheme + src).href.slice(scheme.length)
205
+ }
206
+ const href = posix.join(posix.dirname(src), path)
207
+ return src.startsWith("/") || href.startsWith(".") ? href : `./${href}`
208
+ }
209
+ return null
210
+ }
211
+
134
212
  // a <script> block with its attribute string, so `lang` can be read and the
135
213
  // body replaced - the same shape as STYLE_BLOCK_RE below, quote-aware so a
136
214
  // ">" inside an attribute value (`:setup="{ n = a > 1 }"`) doesn't end the tag
@@ -507,6 +585,11 @@ export function jq79(options: Jq79PluginOptions = {}): Plugin {
507
585
  // for - so the server hands out what the plugin compiled and nothing else
508
586
  const devScripts = new Map<string, string>()
509
587
  const devIds = new Map<string, number>()
588
+ // build only: each component's functions, by file, for the one script
589
+ // buildEnd emits - its reference, and the file name renderChunk resolves it to
590
+ const buildFunctions = new Map<string, CheckedFunction[]>()
591
+ let precompiledRef: string | undefined
592
+ let precompiledFile: string | undefined
510
593
 
511
594
  let config: ResolvedConfig | null = null
512
595
 
@@ -561,20 +644,69 @@ export function jq79(options: Jq79PluginOptions = {}): Plugin {
561
644
 
562
645
  // the component's functions, compiled after its TypeScript and styles are:
563
646
  // the runtime compiles what reaches it, and this is what reaches it
564
- const script = componentScript(source, message => this.warn(`jq79: ${filename}: ${message}`))
647
+ const functions = componentFunctions(source, message => this.warn(`jq79: ${filename}: ${message}`))
565
648
  let url: string
566
649
  if (config?.command === "serve") {
567
650
  let devId = devIds.get(file)
568
651
  if (devId === undefined) devIds.set(file, devId = devIds.size)
569
- devScripts.set(String(devId), script)
652
+ devScripts.set(String(devId), registeringScript(functions))
570
653
  // versioned, so an edit loads the new functions rather than a cached copy
571
654
  url = JSON.stringify(`${config.base}${PRECOMPILED_PATH.slice(1)}?id=${devId}&v=${Date.now()}`)
572
655
  } else {
573
- const ref = this.emitFile({ type: "asset", name: `${basename(file)}.jq79.js`, source: script })
574
- url = `import.meta.ROLLUP_FILE_URL_${ref}`
656
+ buildFunctions.set(file, functions)
657
+ url = JSON.stringify(PRECOMPILED_URL_PLACEHOLDER)
575
658
  }
576
659
  return { code: componentModule(source, include, filename, url), map: null }
577
660
  },
661
+
662
+ buildStart() {
663
+ precompiledRef = undefined
664
+ precompiledFile = undefined
665
+ },
666
+
667
+ // the build's one precompiled script, from every component still in the
668
+ // module graph. What earlier builds recorded is kept and pruned rather than
669
+ // cleared in buildStart, so a watch rebuild that doesn't load a module again
670
+ // keeps its functions. Sorted by file, so the same sources make the same
671
+ // bytes, and the same hash
672
+ buildEnd(error) {
673
+ if (!safeEval || error || config?.command === "serve") return
674
+ const inGraph = new Set<string>()
675
+ for (const id of this.getModuleIds()) if (id.endsWith(COMPONENT_QUERY)) inGraph.add(id.slice(0, -COMPONENT_QUERY.length))
676
+ for (const file of buildFunctions.keys()) if (!inGraph.has(file)) buildFunctions.delete(file)
677
+ if (buildFunctions.size === 0) return
678
+ const functions = [...buildFunctions.keys()].sort().flatMap(file => buildFunctions.get(file)!)
679
+ precompiledRef = this.emitFile({ type: "asset", name: PRECOMPILED_ASSET, source: registeringScript(functions) })
680
+ },
681
+
682
+ // the placeholder, as what import.meta.ROLLUP_FILE_URL_<ref> renders to:
683
+ // the asset's path relative to the chunk, against the chunk's own URL - so
684
+ // `base` doesn't matter. Before minification, and part of the chunk's hash.
685
+ // The source map is left as it is: the placeholder sits on a line of its
686
+ // own with only `)` after it
687
+ renderChunk(code, chunk) {
688
+ if (precompiledRef === undefined || !code.includes(PRECOMPILED_URL_PLACEHOLDER)) return null
689
+ precompiledFile = this.getFileName(precompiledRef)
690
+ const path = JSON.stringify(posix.relative(posix.dirname(chunk.fileName), precompiledFile))
691
+ return { code: code.replace(PRECOMPILED_URL_PLACEHOLDER_RE, () => `new URL(${path}, import.meta.url).href`), map: null }
692
+ },
693
+
694
+ // a page that waits for the script asks for it as it parses, rather than
695
+ // once its entry has loaded and run. Same URL as the module's
696
+ // (precompiledHref), and no crossorigin, as the <script> has none: a
697
+ // preload is only reused by a request that matches it. Vite's html.cspNonce
698
+ // stamps it with the nonce, after this hook - without it,
699
+ // `script-src 'nonce-…'` refuses a preload. Build only: dev has one script
700
+ // per component, versioned per edit. Vite writes the page's <script> tags
701
+ // before it runs this hook, in every version the plugin supports
702
+ transformIndexHtml(html, ctx) {
703
+ if (!safeEval || !precompiledFile || !ctx.bundle || !ctx.chunk) return
704
+ const bundle = ctx.bundle as Record<string, BundleFile>
705
+ if (!reachesComponent(ctx.chunk as BundleFile, bundle)) return
706
+ const href = precompiledHref(html, bundle, precompiledFile)
707
+ if (href === null) return
708
+ return [{ tag: "link", attrs: { rel: "preload", as: "script", href }, injectTo: "head" }]
709
+ },
578
710
  }
579
711
  }
580
712
 
package/dist/jq79-sw.js CHANGED
@@ -21,7 +21,7 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
21
21
  ${t}`,nt=e=>`await $mounted();${e}`,Ni=e=>["$scope","$__effect","$__import","$__state",...e],Ti=e=>`return (async () => { with ($scope) { ${e} }
22
22
  ;$__state.done = true })()`,Ri=e=>["$__exports","$__default","$__import",...e],Li=e=>`return (async () => { "use strict";
23
23
  ${e}
24
- ;$__exports.done = true })()`,ot=e=>{let t=e.attrs[":setup"];return t===void 0?null:t.trim()===""?[]:ce(t)},Vi=(e,t)=>{let i=new Set;return e.forEach(s=>{(Ne(s.content)??t(s))?.forEach(({name:n})=>i.add(n))}),i},Oi=["$","$$","$create","$reactive","$toRaw","Component79"],Bi=["$mounted","$destroyed","$attached","$detached","$computed","$self","$$self","$emit","$updateModel","$slots"],ut="__jq79precompiled",ht="jq79-precompiled",Le=(e,t)=>`function anonymous(${e.join(",")}
24
+ ;$__exports.done = true })()`,ot=e=>{let t=e.attrs[":setup"];return t===void 0?null:t.trim()===""?[]:ce(t)},Vi=(e,t)=>{let i=new Set;return e.forEach(s=>{(Ne(s.content)??t(s))?.forEach(({name:n})=>i.add(n))}),i},Oi=["$","$$","$create","$reactive","$toRaw","Component79","C79"],Bi=["$mounted","$destroyed","$attached","$detached","$computed","$self","$$self","$emit","$updateModel","$slots"],ut="__jq79precompiled",ht="jq79-precompiled",Le=(e,t)=>`function anonymous(${e.join(",")}
25
25
  ) {
26
26
  ${t}
27
27
  }`;var Di=e=>typeof e!="string",Mi=e=>{let{[at]:t,...i}=e.attrs;return{tag:e.tag,attrs:i,...t===void 0?{}:{component:t},children:e.children.map(s=>typeof s=="string"?s:Mi(s))}},Fi=e=>e.children.map(t=>typeof t=="string"?t:Fi(t)).join(""),br=(e,t)=>{let s=(e.component??e.tag).replace(/-/g,"").toLowerCase(),r=new Set(t.filter(n=>/^[A-Z]/.test(n)&&n.replace(/-/g,"").toLowerCase()===s));return r.add(e.component??le(e.tag).replace(/^./,n=>n.toUpperCase())),[...r]},$i=(e,t,i)=>{for(let s of e){if(typeof s=="string"){s.includes("{{")&&Si(s).forEach(n=>{typeof n!="string"&&i(n.expr)});continue}let r=s.attrs;if(":if"in r&&i(r[":if"]),":elseif"in r&&i(r[":elseif"]),":each"in r){let n=r[":each"].match(Ci);n&&i(n[3]),":key"in r&&i(r[":key"])}":with"in r&&i(r[":with"]);for(let n in r)(n===":slot"||n.startsWith(":slot."))&&ce(r[n]||void 0)?.forEach(({default:o})=>{o!==void 0&&i(o)});if(wi(s.tag))for(let n in r)Re(n)||n.startsWith("@")||!n.startsWith(":")||i(r[n]||n.slice(1));else{if(s.component!==void 0||s.tag.includes("-")){br(s,t).forEach(n=>i(n));for(let n in r){let o=r[n];if(n===":props"||n.startsWith(":props."))i(o);else{if(Re(n))continue;if(n.startsWith("@"))i(o,["$event"]);else if(n===":model"||n.startsWith(":model.")){let u=o||(n===":model"?"model":le(n.slice(7)));i(u),i(Ei(u),["$value"])}else n.startsWith(":")?i(o||le(n.slice(1))):i(JSON.stringify(o))}}}for(let n in r){let o=r[n];if(n.startsWith("@"))i(o,["$event"]);else{if(n===":model"||n.startsWith(":model."))continue;if(n===":class"||n.startsWith(":class.")||n===":text"||n===":html"||n===":html.allowed"||n===":value"||n===":checked"||n===":selected")i(o);else{if(Re(n))continue;n.startsWith(":")&&i(o||le(n.slice(1)))}}}}$i(s.children,t,i)}},Ui=e=>{let t=new Map,i=(u,h)=>{t.set(Pi(u,h),[u,h])},s=(u,h=[])=>{let l=[...ki,...h],c=Ii(u,h);c!==null&&i(l,c),i(l,Ai(u))},r=ui(yi(e)).filter(Di),n=[],o=[r.filter(u=>u.tag!=="template")];return r.filter(u=>u.tag==="template").forEach(u=>{let h=u.attrs.name;h===void 0||!_i.test(h)||n.includes(h)||(n.push(h),o.push(u.children.filter(Di)))}),o.forEach(u=>yr(u,n,i,s)),[...t.values()]},yr=(e,t,i,s)=>{let r=e.filter(c=>c.tag==="script").map(c=>({attrs:c.attrs,content:Fi(c)})),n=e.filter(c=>c.tag!=="script"&&c.tag!=="style").map(Mi),o;try{o=Vi(r,ot)}catch{return}let u=Object.fromEntries(t.filter(c=>!o.has(c)).map(c=>[c,!0])),h=Object.keys({...Object.fromEntries(Oi.map(c=>[c,!0])),...Object.fromEntries(Bi.map(c=>[c,!0])),...u}),l=[...t];r.forEach(c=>{let d=":mounted"in c.attrs,m=mi(c.content);if(m!==null)Ne(c.content)?.forEach(({name:E,default:P})=>{l.push(E),P!==void 0&&s(P)}),i(Ri(h),Li(d?nt(m):m));else{let{vars:S,code:E}=Pe(c.content);l.push(...S),ot(c)?.forEach(({name:P,default:N})=>{l.push(P),N!==void 0&&s(N)}),i(Ni(h),Ti(d?nt(E):E))}}),$i(n,l,s)},Wi=(e,t)=>{let i=e.map(([s,r])=>`[${JSON.stringify(s)}, ${JSON.stringify(r)}, ${t(s,r)?Le(s,r):"null"}]`);return`(self.${ut} = self.${ut} || []).push(