@verajs/autoloader 0.1.0
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 +5 -0
- package/dist/development/vera-autoloader.d.ts +34 -0
- package/dist/development/vera-autoloader.d.ts.map +1 -0
- package/dist/development/vera-autoloader.js +113 -0
- package/dist/development/vera-autoloader.js.map +1 -0
- package/dist/vera-autoloader.min.js +2 -0
- package/dist/vera-autoloader.min.js.map +1 -0
- package/package.json +108 -0
package/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @verajs/autoloader
|
|
2
|
+
|
|
3
|
+
Lazy component loading by tag name (~0.6 KB gzip): the first time an undefined custom element
|
|
4
|
+
appears inside an `autoloader`-marked component, its module is fetched from a bounded URL and
|
|
5
|
+
defined. `extension: '.ts'` supports TypeScript dev servers.
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
type AutoloaderOptions = {
|
|
2
|
+
/**
|
|
3
|
+
* File extension appended to the tag name when building a component's URL.
|
|
4
|
+
*
|
|
5
|
+
* Defaults to `.js`. Set to `.ts` so TypeScript projects can autoload their sources during
|
|
6
|
+
* development — a dev server will not serve `foo.js` when only `foo.ts` exists on disk.
|
|
7
|
+
* Accepted with or without the leading dot.
|
|
8
|
+
*/
|
|
9
|
+
extension?: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
/** Autoload function to be run by autoloader each time a component with the "autoloader" attribute
|
|
13
|
+
* is rerendered
|
|
14
|
+
*/
|
|
15
|
+
type Autoloader = (element: HTMLElement) => void;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Inits an autoloader with the provided root directory, component directory and autoloader options.
|
|
19
|
+
*
|
|
20
|
+
* @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using
|
|
21
|
+
* absolute paths
|
|
22
|
+
* @param componentsDir The relative directory from the root directory. If element has an "autoload-dir" attribute, the
|
|
23
|
+
* autoloader will read from that first
|
|
24
|
+
* @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets
|
|
25
|
+
* TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`
|
|
26
|
+
* exists). Defaults to `.js`
|
|
27
|
+
* @return An autoloader function that should be run on desired elements each render (if lazy load elements are
|
|
28
|
+
* conditionally rendered)
|
|
29
|
+
*/
|
|
30
|
+
declare const initAutoloader: (rootDir: string, componentsDir?: string, options?: AutoloaderOptions) => Autoloader;
|
|
31
|
+
|
|
32
|
+
export { initAutoloader };
|
|
33
|
+
export type { AutoloaderOptions };
|
|
34
|
+
//# sourceMappingURL=vera-autoloader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vera-autoloader.d.ts","sources":["../../src/types.d.ts","../../../shared-types/src/types.d.ts","../../../../../../src/autoloader.ts"],"mappings":"AAAA,KAAK,iBAAiB;AACtB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACTA;AACA;AACA;AACA,KAAK,UAAU,aAAa,WAAW;;;;;;;;;;;;;ACapC;AACH;cAKE,cAAA,sDAAA,iBAA4F,KAAA,UAAA;;;;","names":[]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Utility function for emulating .get chaining on Map prototypes for readability in the
|
|
3
|
+
* signal handler function. This function checks for the existance of a key before getting it
|
|
4
|
+
* and creates it if it doesn't exist.
|
|
5
|
+
*
|
|
6
|
+
* @param item The item to get the key for
|
|
7
|
+
*
|
|
8
|
+
* @returns An object with new get function to chain (g) or the items final value (v)
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Remove a trailing slash from an url if its not root url (`/`).
|
|
12
|
+
*
|
|
13
|
+
* @param str String to remove trailing slash from
|
|
14
|
+
*/
|
|
15
|
+
const stripTrailingSlash = (str) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Inits an autoloader with the provided root directory, component directory and autoloader options.
|
|
19
|
+
*
|
|
20
|
+
* @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using
|
|
21
|
+
* absolute paths
|
|
22
|
+
* @param componentsDir The relative directory from the root directory. If element has an "autoload-dir" attribute, the
|
|
23
|
+
* autoloader will read from that first
|
|
24
|
+
* @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets
|
|
25
|
+
* TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`
|
|
26
|
+
* exists). Defaults to `.js`
|
|
27
|
+
* @return An autoloader function that should be run on desired elements each render (if lazy load elements are
|
|
28
|
+
* conditionally rendered)
|
|
29
|
+
*/
|
|
30
|
+
const initAutoloader = (rootDir, componentsDir, options) => {
|
|
31
|
+
/** A configuration error fails at the misconfiguration, not once per element per render. */
|
|
32
|
+
if (!rootDir)
|
|
33
|
+
throw new Error('autoloader: rootDir is required (usually import.meta.url)');
|
|
34
|
+
/** Normalized so callers may pass either `ts` or `.ts` */
|
|
35
|
+
const extension = `.${(options?.extension ?? '.js').replace(/^\./, '')}`;
|
|
36
|
+
/**
|
|
37
|
+
* Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`
|
|
38
|
+
* (the HTML parser won't produce one), but the `autoload-dir` override is free text — and
|
|
39
|
+
* CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An
|
|
40
|
+
* absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is
|
|
41
|
+
* refused.
|
|
42
|
+
*/
|
|
43
|
+
const base = new URL('.', rootDir).href;
|
|
44
|
+
/**
|
|
45
|
+
* One attempt per URL per page load. Without this, a file that fails to load was retried on
|
|
46
|
+
* every render — console spam and a network request each time — and the same tag reached
|
|
47
|
+
* through two different dirs raced to define twice.
|
|
48
|
+
*/
|
|
49
|
+
const attempted = new Set();
|
|
50
|
+
/**
|
|
51
|
+
* Creates the expected element url location to be appended to the root dir.
|
|
52
|
+
*
|
|
53
|
+
* The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global
|
|
54
|
+
* text-direction attribute (`dir="rtl"` on any i18n page would have silently redirected
|
|
55
|
+
* component loading).
|
|
56
|
+
*
|
|
57
|
+
* @param element The element the autoloader is discovering
|
|
58
|
+
* @param tag The element's name
|
|
59
|
+
* @return The element's expected location to be appended to the root dir
|
|
60
|
+
*/
|
|
61
|
+
const elementURL = (element, tag) => {
|
|
62
|
+
const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');
|
|
63
|
+
return `${dir}/${tag}${extension}`;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Loads an element and then recursively calls discover on that element.
|
|
67
|
+
*
|
|
68
|
+
* @param element The element to load
|
|
69
|
+
* @param tag The tag to build the expected url from
|
|
70
|
+
*/
|
|
71
|
+
const load = async (element, tag) => {
|
|
72
|
+
const src = new URL(elementURL(element, tag), rootDir).href;
|
|
73
|
+
if (attempted.has(src))
|
|
74
|
+
return;
|
|
75
|
+
attempted.add(src);
|
|
76
|
+
if (!src.startsWith(base)) {
|
|
77
|
+
console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
await import(/* @vite-ignore */ src);
|
|
82
|
+
await customElements.whenDefined(tag);
|
|
83
|
+
discover(element);
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
console.error(`Failed to load custom element ${tag} from ${src}:`, error);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* Finds all elements within a parent element that are not defined and attempts to load each of them
|
|
91
|
+
*
|
|
92
|
+
* @param element The element to look for undefined custom elements within
|
|
93
|
+
*/
|
|
94
|
+
const discover = (element) => {
|
|
95
|
+
if (element.getAttribute('autoloader') == null)
|
|
96
|
+
return;
|
|
97
|
+
if (element.getAttribute('autoload-ignore') != null)
|
|
98
|
+
return;
|
|
99
|
+
const componentElement = element.shadowRoot ?? element;
|
|
100
|
+
const elements = componentElement.querySelectorAll(':not(:defined)');
|
|
101
|
+
for (let i = 0; i < elements.length; i++) {
|
|
102
|
+
const el = elements[i];
|
|
103
|
+
const tag = el.localName;
|
|
104
|
+
if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {
|
|
105
|
+
load(el, tag);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
return discover;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export { initAutoloader };
|
|
113
|
+
//# sourceMappingURL=vera-autoloader.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vera-autoloader.js","sources":["../../../../../../../shared-utils/src/utils.ts","../../../../../../src/autoloader.ts"],"sourcesContent":["import { GetResult, GetValueType } from '@verajs/shared-types';\n\n/**\n * Utility function for emulating .get chaining on Map prototypes for readability in the\n * signal handler function. This function checks for the existance of a key before getting it\n * and creates it if it doesn't exist.\n *\n * @param item The item to get the key for\n *\n * @returns An object with new get function to chain (g) or the items final value (v)\n */\nexport const get = <T>(item: T) => ({\n get: <K>(key: K, defaultValue: GetValueType<T>): GetResult<GetValueType<T>> => {\n if (isInstanceOf(item, Array)) {\n /** Compared against `undefined`, not truthiness — an existing `0`/`''`/`false` entry must\n * not be clobbered with the default (the falsy-check defect class from map-support). */\n if ((item as Array<GetValueType<T>>)[key as number] === undefined) {\n (item as Array<GetValueType<T>>)[key as number] = defaultValue;\n }\n return get<GetValueType<T>>((item as Array<GetValueType<T>>)[key as number]);\n } else if (isInstanceOf(item, Map) || isInstanceOf(item, WeakMap)) {\n if (!(item as Map<K, GetValueType<T>>).has(key)) {\n (item as Map<K, GetValueType<T>>).set(key, defaultValue);\n }\n return get<GetValueType<T>>((item as Map<K, GetValueType<T>>).get(key)!);\n }\n return throwError() as GetResult<GetValueType<T>>;\n },\n value: item,\n});\n\n/**\n * Get an object's type.\n *\n * @param obj The object\n * @return The type\n */\nexport const getType = (obj: unknown) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();\n\n/**\n * Check if an item is an instance of a class type.\n *\n * @param item Item to check\n * @param classType Class type to check\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst isInstanceOf = <I, C extends Function>(item: I, classType: C) => item instanceof classType;\n\n/**\n * Whether an item is a set or map\n *\n * @param item Item to check\n */\nconst KEYED_COLLECTIONS = ['map', 'set'];\nexport const isSetOrMap = <T>(item: T) => KEYED_COLLECTIONS.includes(getType(item));\n\n/**\n * Throws a minified error with an id number\n *\n * @param minifiedError Throws a minified error\n */\nexport const throwError = (minifiedError?: number): never => {\n throw new Error(minifiedError ? `Minified error: ${minifiedError}` : '');\n};\n\n/**\n * Remove a trailing slash from an url if its not root url (`/`).\n *\n * @param str String to remove trailing slash from\n */\nexport const stripTrailingSlash = (str: string) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);\n\n/**\n * Finds the entry for `priority` in a dense, priority-sorted pair of arrays, creating one if it is\n * not there yet. `order` holds the priorities and `list` the values at matching indices.\n *\n * Priority is deliberately NOT used as an array index. Indexing by priority leaves holes — hooks at\n * 25/50/75 produce a 76-element array with 73 of them empty — and these arrays are walked on every\n * render and every write, so the holes dominated the cost.\n *\n * @param list Values, ordered by ascending priority\n * @param order Priorities, parallel to `list`\n * @param priority Priority to find or create\n * @param create Builds the value when the priority is not present yet\n * @return The existing or newly created value\n */\nexport const prioritySlot = <T>(list: T[], order: number[], priority: number, create: () => T): T => {\n let slot = 0;\n while (slot < order.length && order[slot] < priority) slot++;\n if (order[slot] === priority) return list[slot];\n\n order.splice(slot, 0, priority);\n const created = create();\n list.splice(slot, 0, created);\n return created;\n};\n","import { AutoloaderOptions } from './types.js';\nimport { Autoloader } from '@verajs/shared-types';\nimport { stripTrailingSlash } from '@verajs/shared-utils';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`\n * @return An autoloader function that should be run on desired elements each render (if lazy load elements are\n * conditionally rendered)\n */\nexport const initAutoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): Autoloader => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n const base = new URL('.', rootDir).href;\n\n /**\n * One attempt per URL per page load. Without this, a file that fails to load was retried on\n * every render — console spam and a network request each time — and the same tag reached\n * through two different dirs raced to define twice.\n */\n const attempted = new Set<string>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * @param element The element the autoloader is discovering\n * @param tag The element's name\n * @return The element's expected location to be appended to the root dir\n */\n const elementURL = (element: Element, tag: string) => {\n const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');\n return `${dir}/${tag}${extension}`;\n };\n\n /**\n * Loads an element and then recursively calls discover on that element.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n const src = new URL(elementURL(element, tag), rootDir).href;\n if (attempted.has(src)) return;\n attempted.add(src);\n\n if (!src.startsWith(base)) {\n console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);\n return;\n }\n\n try {\n await import(/* @vite-ignore */ src);\n await customElements.whenDefined(tag);\n discover(element);\n } catch (error) {\n console.error(`Failed to load custom element ${tag} from ${src}:`, error);\n }\n };\n\n /**\n * Finds all elements within a parent element that are not defined and attempts to load each of them\n *\n * @param element The element to look for undefined custom elements within\n */\n const discover = (element: Element) => {\n if (element.getAttribute('autoloader') == null) return;\n if (element.getAttribute('autoload-ignore') != null) return;\n const componentElement = element.shadowRoot ?? element;\n const elements = componentElement.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n const tag = el.localName;\n if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {\n load(el, tag);\n }\n }\n };\n\n return discover;\n};\n"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=(e,t,o)=>{if(!e)throw new Error("autoloader: rootDir is required (usually import.meta.url)");const r=`.${(o?.extension??".js").replace(/^\./,"")}`,l=new URL(".",e).href,n=new Set,a=async(o,a)=>{const i=new URL(((e,o)=>{var l;return`${"/"!==(l=e.getAttribute("autoload-dir")??t??"/")&&l.endsWith("/")?l.slice(0,-1):l}/${o}${r}`})(o,a),e).href;if(!n.has(i))if(n.add(i),i.startsWith(l))try{await import(i),await customElements.whenDefined(a),s(o)}catch(e){console.error(`Failed to load custom element ${a} from ${i}:`,e)}else console.error(`autoloader: refused ${i} for <${a}> — resolves outside ${l}`)},s=e=>{if(null==e.getAttribute("autoloader"))return;if(null!=e.getAttribute("autoload-ignore"))return;const t=(e.shadowRoot??e).querySelectorAll(":not(:defined)");for(let e=0;e<t.length;e++){const o=t[e],r=o.localName;r?.includes("-")&&!customElements.get(r)&&null==o.getAttribute("autoload-ignore")&&a(o,r)}};return s};export{e as initAutoloader};
|
|
2
|
+
//# sourceMappingURL=vera-autoloader.min.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vera-autoloader.min.js","sources":["../../../../../shared-utils/src/utils.ts","../../../../src/autoloader.ts"],"sourcesContent":["import { GetResult, GetValueType } from '@verajs/shared-types';\n\n/**\n * Utility function for emulating .get chaining on Map prototypes for readability in the\n * signal handler function. This function checks for the existance of a key before getting it\n * and creates it if it doesn't exist.\n *\n * @param item The item to get the key for\n *\n * @returns An object with new get function to chain (g) or the items final value (v)\n */\nexport const get = <T>(item: T) => ({\n get: <K>(key: K, defaultValue: GetValueType<T>): GetResult<GetValueType<T>> => {\n if (isInstanceOf(item, Array)) {\n /** Compared against `undefined`, not truthiness — an existing `0`/`''`/`false` entry must\n * not be clobbered with the default (the falsy-check defect class from map-support). */\n if ((item as Array<GetValueType<T>>)[key as number] === undefined) {\n (item as Array<GetValueType<T>>)[key as number] = defaultValue;\n }\n return get<GetValueType<T>>((item as Array<GetValueType<T>>)[key as number]);\n } else if (isInstanceOf(item, Map) || isInstanceOf(item, WeakMap)) {\n if (!(item as Map<K, GetValueType<T>>).has(key)) {\n (item as Map<K, GetValueType<T>>).set(key, defaultValue);\n }\n return get<GetValueType<T>>((item as Map<K, GetValueType<T>>).get(key)!);\n }\n return throwError() as GetResult<GetValueType<T>>;\n },\n value: item,\n});\n\n/**\n * Get an object's type.\n *\n * @param obj The object\n * @return The type\n */\nexport const getType = (obj: unknown) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();\n\n/**\n * Check if an item is an instance of a class type.\n *\n * @param item Item to check\n * @param classType Class type to check\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nconst isInstanceOf = <I, C extends Function>(item: I, classType: C) => item instanceof classType;\n\n/**\n * Whether an item is a set or map\n *\n * @param item Item to check\n */\nconst KEYED_COLLECTIONS = ['map', 'set'];\nexport const isSetOrMap = <T>(item: T) => KEYED_COLLECTIONS.includes(getType(item));\n\n/**\n * Throws a minified error with an id number\n *\n * @param minifiedError Throws a minified error\n */\nexport const throwError = (minifiedError?: number): never => {\n throw new Error(minifiedError ? `Minified error: ${minifiedError}` : '');\n};\n\n/**\n * Remove a trailing slash from an url if its not root url (`/`).\n *\n * @param str String to remove trailing slash from\n */\nexport const stripTrailingSlash = (str: string) => (str !== '/' && str.endsWith('/') ? str.slice(0, -1) : str);\n\n/**\n * Finds the entry for `priority` in a dense, priority-sorted pair of arrays, creating one if it is\n * not there yet. `order` holds the priorities and `list` the values at matching indices.\n *\n * Priority is deliberately NOT used as an array index. Indexing by priority leaves holes — hooks at\n * 25/50/75 produce a 76-element array with 73 of them empty — and these arrays are walked on every\n * render and every write, so the holes dominated the cost.\n *\n * @param list Values, ordered by ascending priority\n * @param order Priorities, parallel to `list`\n * @param priority Priority to find or create\n * @param create Builds the value when the priority is not present yet\n * @return The existing or newly created value\n */\nexport const prioritySlot = <T>(list: T[], order: number[], priority: number, create: () => T): T => {\n let slot = 0;\n while (slot < order.length && order[slot] < priority) slot++;\n if (order[slot] === priority) return list[slot];\n\n order.splice(slot, 0, priority);\n const created = create();\n list.splice(slot, 0, created);\n return created;\n};\n","import { AutoloaderOptions } from './types.js';\nimport { Autoloader } from '@verajs/shared-types';\nimport { stripTrailingSlash } from '@verajs/shared-utils';\n\n/**\n * Inits an autoloader with the provided root directory, component directory and autoloader options.\n *\n * @param rootDir The root directory of all components. Should almost always be import.meta.url unless you are using\n * absolute paths\n * @param componentsDir The relative directory from the root directory. If element has an \"autoload-dir\" attribute, the\n * autoloader will read from that first\n * @param options Autoloader options. `extension` sets the file extension appended to the tag name, which lets\n * TypeScript projects autoload `.ts` sources during dev (a dev server will not serve `foo.js` when only `foo.ts`\n * exists). Defaults to `.js`\n * @return An autoloader function that should be run on desired elements each render (if lazy load elements are\n * conditionally rendered)\n */\nexport const initAutoloader = (\n rootDir: string,\n componentsDir?: string,\n options?: AutoloaderOptions\n): Autoloader => {\n /** A configuration error fails at the misconfiguration, not once per element per render. */\n if (!rootDir) throw new Error('autoloader: rootDir is required (usually import.meta.url)');\n\n /** Normalized so callers may pass either `ts` or `.ts` */\n const extension = `.${(options?.extension ?? '.js').replace(/^\\./, '')}`;\n\n /**\n * Every resolved URL must stay inside the entry's own directory. Tag names cannot carry `/`\n * (the HTML parser won't produce one), but the `autoload-dir` override is free text — and\n * CODE-PRINCIPLES #8 requires bounding anything that turns markup into a module URL. An\n * absolute, protocol-relative, or upward-traversing value resolves outside this prefix and is\n * refused.\n */\n const base = new URL('.', rootDir).href;\n\n /**\n * One attempt per URL per page load. Without this, a file that fails to load was retried on\n * every render — console spam and a network request each time — and the same tag reached\n * through two different dirs raced to define twice.\n */\n const attempted = new Set<string>();\n\n /**\n * Creates the expected element url location to be appended to the root dir.\n *\n * The per-element override attribute is `autoload-dir` — NOT `dir`, which is HTML's global\n * text-direction attribute (`dir=\"rtl\"` on any i18n page would have silently redirected\n * component loading).\n *\n * @param element The element the autoloader is discovering\n * @param tag The element's name\n * @return The element's expected location to be appended to the root dir\n */\n const elementURL = (element: Element, tag: string) => {\n const dir = stripTrailingSlash(element.getAttribute('autoload-dir') ?? componentsDir ?? '/');\n return `${dir}/${tag}${extension}`;\n };\n\n /**\n * Loads an element and then recursively calls discover on that element.\n *\n * @param element The element to load\n * @param tag The tag to build the expected url from\n */\n const load = async (element: Element, tag: string): Promise<void> => {\n const src = new URL(elementURL(element, tag), rootDir).href;\n if (attempted.has(src)) return;\n attempted.add(src);\n\n if (!src.startsWith(base)) {\n console.error(`autoloader: refused ${src} for <${tag}> — resolves outside ${base}`);\n return;\n }\n\n try {\n await import(/* @vite-ignore */ src);\n await customElements.whenDefined(tag);\n discover(element);\n } catch (error) {\n console.error(`Failed to load custom element ${tag} from ${src}:`, error);\n }\n };\n\n /**\n * Finds all elements within a parent element that are not defined and attempts to load each of them\n *\n * @param element The element to look for undefined custom elements within\n */\n const discover = (element: Element) => {\n if (element.getAttribute('autoloader') == null) return;\n if (element.getAttribute('autoload-ignore') != null) return;\n const componentElement = element.shadowRoot ?? element;\n const elements = componentElement.querySelectorAll(':not(:defined)');\n for (let i = 0; i < elements.length; i++) {\n const el = elements[i];\n const tag = el.localName;\n if (tag?.includes('-') && !customElements.get(tag) && el.getAttribute('autoload-ignore') == null) {\n load(el, tag);\n }\n }\n };\n\n return discover;\n};\n"],"names":["initAutoloader","rootDir","componentsDir","options","Error","extension","replace","base","URL","href","attempted","Set","load","async","element","tag","src","str","getAttribute","endsWith","slice","elementURL","has","add","startsWith","import","customElements","whenDefined","discover","error","console","elements","shadowRoot","querySelectorAll","i","length","el","localName","includes","get"],"mappings":"AAsEO,MCrDMA,EAAiB,CAC5BC,EACAC,EACAC,KAGA,IAAKF,EAAS,MAAM,IAAIG,MAAM,6DAG9B,MAAMC,EAAY,KAAKF,GAASE,WAAa,OAAOC,QAAQ,MAAO,MAS7DC,EAAO,IAAIC,IAAI,IAAKP,GAASQ,KAO7BC,EAAY,IAAIC,IAwBhBC,EAAOC,MAAOC,EAAkBC,KACpC,MAAMC,EAAM,IAAIR,IAZC,EAACM,EAAkBC,KDeN,IAACE,ECb/B,MAAO,GDaiD,OAAzBA,ECdAH,EAAQI,aAAa,iBAAmBhB,GAAiB,MDczBe,EAAIE,SAAS,KAAOF,EAAIG,MAAM,GAAG,GAAMH,KCbrFF,IAAMV,GAAW,EAUdgB,CAAWP,EAASC,GAAMd,GAASQ,KACvD,IAAIC,EAAUY,IAAIN,GAGlB,GAFAN,EAAUa,IAAIP,GAETA,EAAIQ,WAAWjB,GAKpB,UACQkB,OAA0BT,SAC1BU,eAAeC,YAAYZ,GACjCa,EAASd,EACX,CAAE,MAAOe,GACPC,QAAQD,MAAM,iCAAiCd,UAAYC,KAAQa,EACrE,MAVEC,QAAQD,MAAM,uBAAuBb,UAAYD,yBAA2BR,IAU9E,EAQIqB,EAAYd,IAChB,GAA0C,MAAtCA,EAAQI,aAAa,cAAuB,OAChD,GAA+C,MAA3CJ,EAAQI,aAAa,mBAA4B,OACrD,MACMa,GADmBjB,EAAQkB,YAAclB,GACbmB,iBAAiB,kBACnD,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAASI,OAAQD,IAAK,CACxC,MAAME,EAAKL,EAASG,GACdnB,EAAMqB,EAAGC,UACXtB,GAAKuB,SAAS,OAASZ,eAAea,IAAIxB,IAA8C,MAAtCqB,EAAGlB,aAAa,oBACpEN,EAAKwB,EAAIrB,EAEb,GAGF,OAAOa,CAAQ"}
|
package/package.json
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@verajs/autoloader",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "A super small but powerful autoloader for web components that works great with VeraJs but can be used without.",
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/vera-js/vera.git",
|
|
12
|
+
"directory": "packages/autoloader"
|
|
13
|
+
},
|
|
14
|
+
"author": "VeraJS",
|
|
15
|
+
"homepage": "https://verajs.dev",
|
|
16
|
+
"main": "./dist/vera-autoloader.min.js",
|
|
17
|
+
"types": "./dist/development/vera-autoloader.d.ts",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/development/vera-autoloader.d.ts",
|
|
22
|
+
"development": "./dist/development/vera-autoloader.js",
|
|
23
|
+
"default": "./dist/vera-autoloader.min.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "wireit"
|
|
31
|
+
},
|
|
32
|
+
"wireit": {
|
|
33
|
+
"build": {
|
|
34
|
+
"dependencies": [
|
|
35
|
+
"build:development",
|
|
36
|
+
"build:production",
|
|
37
|
+
"build:types"
|
|
38
|
+
]
|
|
39
|
+
},
|
|
40
|
+
"build:development": {
|
|
41
|
+
"command": "npx rollup -c",
|
|
42
|
+
"clean": "if-file-deleted",
|
|
43
|
+
"env": {
|
|
44
|
+
"MODE": "dev"
|
|
45
|
+
},
|
|
46
|
+
"files": [
|
|
47
|
+
"src/**/*{.js,.ts}",
|
|
48
|
+
"../shared-types/src/**/*{.js,.ts}",
|
|
49
|
+
"../shared-utils/src/**/*{.js,.ts}",
|
|
50
|
+
"tsconfig.json",
|
|
51
|
+
"../../tsconfig.json",
|
|
52
|
+
"rollup.config.js",
|
|
53
|
+
"../../defaultRollupConfig.js"
|
|
54
|
+
],
|
|
55
|
+
"output": [
|
|
56
|
+
"dist/development/*.js",
|
|
57
|
+
"dist/development/*.js.map"
|
|
58
|
+
]
|
|
59
|
+
},
|
|
60
|
+
"build:production": {
|
|
61
|
+
"command": "npx rollup -c",
|
|
62
|
+
"clean": "if-file-deleted",
|
|
63
|
+
"env": {
|
|
64
|
+
"MODE": "prod"
|
|
65
|
+
},
|
|
66
|
+
"files": [
|
|
67
|
+
"src/**/*{.js,.ts}",
|
|
68
|
+
"../shared-types/src/**/*{.js,.ts}",
|
|
69
|
+
"../shared-utils/src/**/*{.js,.ts}",
|
|
70
|
+
"tsconfig.json",
|
|
71
|
+
"../../tsconfig.json",
|
|
72
|
+
"rollup.config.js",
|
|
73
|
+
"../../defaultRollupConfig.js"
|
|
74
|
+
],
|
|
75
|
+
"output": [
|
|
76
|
+
"dist/*.min.js",
|
|
77
|
+
"dist/*.min.js.map"
|
|
78
|
+
]
|
|
79
|
+
},
|
|
80
|
+
"build:types": {
|
|
81
|
+
"command": "npx rollup -c",
|
|
82
|
+
"env": {
|
|
83
|
+
"MODE": "types"
|
|
84
|
+
},
|
|
85
|
+
"files": [
|
|
86
|
+
"src/**/*{.js,.ts}",
|
|
87
|
+
"../shared-types/src/**/*{.js,.ts}",
|
|
88
|
+
"../shared-utils/src/**/*{.js,.ts}",
|
|
89
|
+
"tsconfig.json",
|
|
90
|
+
"../../tsconfig.json",
|
|
91
|
+
"rollup.config.js",
|
|
92
|
+
"../../defaultRollupConfig.js"
|
|
93
|
+
],
|
|
94
|
+
"output": [
|
|
95
|
+
"dist/development/*.d.ts",
|
|
96
|
+
"dist/development/*.d.ts.map"
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
"filename": "vera-autoloader",
|
|
101
|
+
"keywords": [
|
|
102
|
+
"verajs",
|
|
103
|
+
"vera",
|
|
104
|
+
"lazy-loading",
|
|
105
|
+
"web-components"
|
|
106
|
+
],
|
|
107
|
+
"sideEffects": false
|
|
108
|
+
}
|