jq79 0.7.10 → 0.7.11

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.
@@ -12,4 +12,9 @@ export declare const parsePropsPattern: (pattern: string | undefined) => PropDec
12
12
  export declare const parseFactoryProps: (src: string) => PropDecl[] | null;
13
13
  export declare const transformFactoryScript: (src: string) => string | null;
14
14
  export declare const freeIdentifiers: (expr: string) => string[] | null;
15
+ export type Preload = {
16
+ spec: string;
17
+ kind: "component" | "page" | "fetch";
18
+ };
19
+ export declare const preloadSpecifiers: (src: string) => Preload[];
15
20
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jq79",
3
- "version": "0.7.10",
3
+ "version": "0.7.11",
4
4
  "description": "Mini reactive component library: single-file .html components, Svelte-style setup scripts, fine-grained proxy reactivity. No compiler, no bundler, no dependencies — works from any static host.",
5
5
  "keywords": [
6
6
  "reactive",
package/src/jq79.ts CHANGED
@@ -3,7 +3,7 @@ import { $, $$, $create, sanitizeHTML, allowedHosts } from "./dom"
3
3
  import type { AllowUrl, QueryAll, QueryOne } from "./dom"
4
4
  import { $reactive, $toRaw, $computed, untracked, createEffectScope, ALSO_WAKEN_BY, OWNER } from "./reactive"
5
5
  import type { ReactiveDeepData, EffectScope } from "./reactive"
6
- import { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, type PropDecl } from "./transform"
6
+ import { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, preloadSpecifiers, type PropDecl } from "./transform"
7
7
  import {
8
8
  COMPONENT_NAME_RE, COMPONENT_TAG_ATTR, CONTROL_ATTRS, EACH_PATTERN, EXPR_PARAMS, PRECOMPILED_PARAM, PRECOMPILED_QUEUE,
9
9
  componentTagName, functionText,
@@ -3332,8 +3332,10 @@ const componentPartsFrom = (elements: Element[], hashSource: string): ComponentP
3332
3332
  // loads .html URLs as components, delegating anything else to native import().
3333
3333
  // Goes to fetchComponent rather than Component79.fetch because an import wants
3334
3334
  // the component, not the chainable handle the public entry point returns
3335
+ const HTML_URL_RE = /\.html?([?#]|$)/
3336
+
3335
3337
  const importResource = (url: string): Promise<any> =>
3336
- /\.html?([?#]|$)/.test(url) ? fetchComponent(url) : import(url)
3338
+ HTML_URL_RE.test(url) ? fetchComponent(url) : import(url)
3337
3339
 
3338
3340
  // a relative specifier means "next to the file that wrote it", so it is
3339
3341
  // resolved against the component's own URL before importResource sees it -
@@ -3995,6 +3997,74 @@ const fetchComponent = async (rawUrl: string): Promise<Component79> => {
3995
3997
  return new Component79(text, { filename: url })
3996
3998
  }
3997
3999
 
4000
+ // ---------------------------------------------------------------------------
4001
+ // preloading (RECORD/2026-11-05.a-preload-scanner.md)
4002
+ //
4003
+ // Before a definition's scripts first run, every download their top level is
4004
+ // sure to ask for starts at once - so `await import("./a.html")` on one line
4005
+ // and `await import("./b.html")` on the next are one round trip, not two, and
4006
+ // still run in that order. Each specifier resolves as its call would, and
4007
+ // lands where that call will look: a component in the cache, a module in the
4008
+ // browser's module map (modulepreload fetches and parses, never evaluates)
4009
+ // ---------------------------------------------------------------------------
4010
+
4011
+ // the script blocks already preloaded: one scan per definition, however many
4012
+ // instances render it
4013
+ const preloadedScripts = new WeakSet<TagBlock>()
4014
+ const preloadedModules = new Set<string>()
4015
+
4016
+ const preloadModule = (url: string) => {
4017
+ if (preloadedModules.has(url)) return
4018
+ preloadedModules.add(url)
4019
+ const link = document.createElement("link")
4020
+ link.rel = "modulepreload"
4021
+ const nonce = pageNonce()
4022
+ if (nonce) link.setAttribute("nonce", nonce)
4023
+ link.href = url
4024
+ document.head.append(link)
4025
+ }
4026
+
4027
+ // a script block's body, quote-aware in its attributes, for a file that is
4028
+ // text and not yet a component: what a preloaded child is when it arrives
4029
+ const SCRIPT_BODY_RE = /<script\b(?:"[^"]*"|'[^']*'|[^>"'])*>([\s\S]*?)<\/script\s*>/gi
4030
+ // the files whose scripts were read for preloads as they arrived: each once,
4031
+ // so two components importing each other end there
4032
+ const preloadedFiles = new Set<string>()
4033
+
4034
+ // one script's preloads, resolved as its calls will be. A component it
4035
+ // preloads is read in turn when it arrives - its imports start before it
4036
+ // renders, and so on down - against its own URL, and with no modules map:
4037
+ // a fetched component has none
4038
+ const preloadSource = (source: string, filename: string | undefined, modules: Record<string, any> | undefined) => {
4039
+ for (const { spec, kind } of preloadSpecifiers(source)) {
4040
+ // the bundle already holds it
4041
+ if (kind === "component" && modules && spec in modules) continue
4042
+ // fetch() goes to the cache as written; the imports resolve first, as
4043
+ // importResource is handed them
4044
+ const url = resolveBare(kind === "fetch" ? spec : resolveSpecifier(spec, kind === "component" ? filename : undefined))
4045
+ if (kind === "fetch" || HTML_URL_RE.test(url)) {
4046
+ // with the cache off there is nowhere to keep it, and the real request
4047
+ // would download it again. A failure is the real request's to report
4048
+ if (componentCache) componentSource(url).then(text => preloadFile(text, url), () => {})
4049
+ } else if (RESOLVABLE_SPECIFIER_RE.test(url)) preloadModule(url)
4050
+ }
4051
+ }
4052
+
4053
+ const preloadFile = (text: string, url: string) => {
4054
+ const key = cacheKey(url)
4055
+ if (preloadedFiles.has(key)) return
4056
+ preloadedFiles.add(key)
4057
+ for (const [, body] of text.matchAll(SCRIPT_BODY_RE)) preloadSource(body, url, undefined)
4058
+ }
4059
+
4060
+ const preloadScripts = (scripts: TagBlock[], filename: string | undefined, modules: Record<string, any> | undefined) => {
4061
+ for (const script of scripts) {
4062
+ if (preloadedScripts.has(script)) continue
4063
+ preloadedScripts.add(script)
4064
+ preloadSource(script.content, filename, modules)
4065
+ }
4066
+ }
4067
+
3998
4068
  // ---------------------------------------------------------------------------
3999
4069
  // safe eval's worker
4000
4070
  //
@@ -4339,13 +4409,14 @@ export class Component79 {
4339
4409
  //
4340
4410
  // Returns the setting as it stands after the call
4341
4411
  static cache(enabled?: boolean): boolean {
4342
- if (enabled === false) componentCache = null
4412
+ if (enabled === false) { componentCache = null; preloadedFiles.clear() }
4343
4413
  else if (enabled === true) componentCache ??= new Map()
4344
4414
  return !!componentCache
4345
4415
  }
4346
4416
 
4347
4417
  static clearCache(): void {
4348
4418
  componentCache?.clear()
4419
+ preloadedFiles.clear()
4349
4420
  }
4350
4421
 
4351
4422
  static fetch(url: string): PendingComponent79 {
@@ -4614,6 +4685,7 @@ export class Component79 {
4614
4685
  const gates: Promise<void>[] = []
4615
4686
  let allSync = true
4616
4687
 
4688
+ preloadScripts(this.scripts, this.filename, this.modules)
4617
4689
  this.scripts.forEach((script, index) => {
4618
4690
  let resolveGate!: () => void
4619
4691
  gates.push(new Promise<void>(resolve => { resolveGate = resolve }))
package/src/transform.ts CHANGED
@@ -899,3 +899,103 @@ export const freeIdentifiers = (expr: string): string[] | null => {
899
899
  if (shortCircuits && names.size > 1) return null
900
900
  return [...names]
901
901
  }
902
+
903
+ // ---------------------------------------------------------------------------
904
+ // the preload scanner (RECORD/2026-11-05.a-preload-scanner.md): the literal
905
+ // specifiers a script asks for in top-level statements that run whatever
906
+ // happens, so the runtime can start every download before the script's first
907
+ // line and let the script take them in its own order. What might not run is
908
+ // left alone - a function's body, a block, a branch, a loop, a handler - and
909
+ // so is anything the scanner can't read whole: a missed preload costs what it
910
+ // costs today, a wrong one an extra download of a file
911
+ // ---------------------------------------------------------------------------
912
+
913
+ // how a specifier resolves - the way the call that names it does:
914
+ // - "component": import(), $importAll and a static import, against the
915
+ // component's file and through its modules map; .html is a component,
916
+ // anything else a module
917
+ // - "page": C79.importAll, the same against the page
918
+ // - "fetch": C79.fetch / fetchAll, always a component, against the page
919
+ // (no kind is spelled "import": dist/jq79.js is held to having no import
920
+ // statement in it, and the test can't tell one from a string that ends so)
921
+ export type Preload = { spec: string; kind: "component" | "page" | "fetch" }
922
+
923
+ // where a statement or an initializer starts with a call that downloads:
924
+ // an optional await, then the call up to its opening bracket(s)
925
+ const PRELOAD_CALL_RE = /(?:await\s+)?(?:import\s*\(|(\$importAll)\s*\(\s*\[|(C79|Component79)\s*\.\s*(fetch|fetchAll|importAll)\s*\(\s*(\[)?)/y
926
+ const PRELOAD_LITERAL_RE = /(["'])([^"'\n\\]+)\1/y
927
+ // a statement that guards the next one without braces - `if (x)`, a loop's
928
+ // header, `else`, `do` - so that one may not run
929
+ const GUARD_RE = /^(?:(?:if|for|while|with)\b[\s\S]*\)|[\s\S]*\b(?:else|do))$/
930
+
931
+ // the literal specifiers of the call `text` starts with: an array's entries
932
+ // up to the first that isn't a literal on its own (`"./a" + x` is not one)
933
+ const preloadCall = (text: string, own: Set<string>): Preload[] => {
934
+ PRELOAD_CALL_RE.lastIndex = 0
935
+ const call = PRELOAD_CALL_RE.exec(text)
936
+ if (!call) return []
937
+ const [, importAll, library, method, bracket] = call
938
+ if (own.has(importAll ?? library ?? "")) return [] // the script's own, not jq79's
939
+ const list = importAll !== undefined || bracket !== undefined
940
+ // fetch takes one URL, its plurals an array: anything else throws
941
+ if (method !== undefined && (method === "fetch") === list) return []
942
+ const kind: Preload["kind"] = library === undefined ? "component" : method === "importAll" ? "page" : "fetch"
943
+
944
+ const found: Preload[] = []
945
+ let i = skipToToken(text, PRELOAD_CALL_RE.lastIndex)
946
+ for (;;) {
947
+ PRELOAD_LITERAL_RE.lastIndex = i
948
+ const literal = PRELOAD_LITERAL_RE.exec(text)
949
+ if (!literal) return found
950
+ const end = skipToToken(text, PRELOAD_LITERAL_RE.lastIndex)
951
+ const next = text[end]
952
+ if (!list) return next === ")" || next === "," ? [{ spec: literal[2], kind }] : []
953
+ if (next !== "," && next !== "]") return found
954
+ found.push({ spec: literal[2], kind })
955
+ if (next === "]") return found
956
+ i = skipToToken(text, end + 1)
957
+ }
958
+ }
959
+
960
+ export const preloadSpecifiers = (src: string): Preload[] => {
961
+ const statements: string[] = []
962
+ for (let i = skipToToken(src, 0); i < src.length; i = skipToToken(src, i + 1)) {
963
+ const end = findStatementEnd(src, i)
964
+ statements.push(src.slice(i, end).trim().replace(/^export\s+(?!default\b)/, ""))
965
+ i = end
966
+ }
967
+
968
+ // a declaration's initializers, or null for a statement that isn't one
969
+ const initializers = (statement: string): { target: string; init: string }[] | null => {
970
+ DECLARATION_START_RE.lastIndex = 0
971
+ const declaration = DECLARATION_START_RE.exec(statement)
972
+ if (!declaration) return null
973
+ return splitDeclarators(statement.slice(declaration[0].length)).map(({ raw }) => {
974
+ const body = raw.trim()
975
+ const assign = defaultAssignIndex(body)
976
+ return assign === -1 ? { target: body, init: "" } : { target: body.slice(0, assign).trim(), init: body.slice(assign + 1).trim() }
977
+ })
978
+ }
979
+
980
+ // a script that declares its own C79, Component79 or $importAll calls
981
+ // that, not the library's
982
+ const own = new Set<string>()
983
+ statements.forEach(statement => initializers(statement)?.forEach(({ target }) => patternBindings(target).forEach(name => own.add(name))))
984
+
985
+ const found: Preload[] = []
986
+ let guarded = false
987
+ for (const statement of statements) {
988
+ if (!guarded) {
989
+ STATIC_IMPORT_RE.lastIndex = 0
990
+ const staticImport = STATIC_IMPORT_RE.exec(statement)
991
+ if (staticImport) {
992
+ if (!/^type\s/.test(staticImport[1] ?? "")) found.push({ spec: staticImport[3], kind: "component" })
993
+ } else {
994
+ const declared = initializers(statement)
995
+ for (const text of declared ? declared.map(({ init }) => init) : [statement]) found.push(...preloadCall(text, own))
996
+ }
997
+ }
998
+ guarded = GUARD_RE.test(statement)
999
+ }
1000
+ return found
1001
+ }