@realmorg/vite-plugin 0.0.0-stage → 2.0.0-alpha.3

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/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2023 RealmOrg
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @realmorg/vite-plugin
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
+ Pre-assembles REALM components at build time so they run under a strict Content Security Policy, and writes a `custom-elements.json` manifest for editors and documentation tools.
4
+
5
+ The plugin is optional. REALM runs without a build step, so you only need it if your project already uses Vite.
6
+
7
+ ```bash
8
+ npm install -D @realmorg/vite-plugin
9
+ ```
10
+
11
+ ```js
12
+ // vite.config.js
13
+ import realm from "@realmorg/vite-plugin";
14
+
15
+ export default {
16
+ plugins: [realm()],
17
+ };
18
+ ```
19
+
20
+ After the build, the script of every `<custom-element>` in the output HTML is assembled into a module next to the file. The inline script becomes `<script src="./file.name.js">`. Nothing is evaluated at runtime, so a policy of `script-src 'self'` is enough.
21
+
22
+ | Option | Default | |
23
+ | --- | --- | --- |
24
+ | `manifest` | `"custom-elements.json"` | File name for the manifest, or `false` to skip it |
25
+
26
+ Outside Vite, call `precompile(dir)` on any folder of built HTML files.
27
+
28
+ Inline `on…` attributes on plain page elements are still inline handlers, so a strict policy blocks them, as it would without REALM.
@@ -0,0 +1,13 @@
1
+ import type { Plugin } from "vite";
2
+ import { describe } from "./manifest.js";
3
+ export { createManifest, describe } from "./manifest.js";
4
+ export interface PrecompileResult {
5
+ modules: string[];
6
+ definitions: ReturnType<typeof describe>[];
7
+ }
8
+ export declare const precompileFile: (path: string, root?: string) => PrecompileResult;
9
+ export declare const precompile: (dir: string) => PrecompileResult;
10
+ export interface RealmPluginOptions {
11
+ manifest?: string | false;
12
+ }
13
+ export default function realm(options?: RealmPluginOptions): Plugin;
package/dist/index.js ADDED
@@ -0,0 +1,92 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join, relative } from "node:path";
3
+ import { compileDefinition } from "@realmorg/realm/compiler";
4
+ import { parseHTML } from "linkedom";
5
+ import { createManifest, describe } from "./manifest.js";
6
+ export { createManifest, describe } from "./manifest.js";
7
+ const htmlFiles = (dir) => readdirSync(dir).flatMap((entry) => {
8
+ const path = join(dir, entry);
9
+ if (statSync(path).isDirectory())
10
+ return entry === "node_modules" ? [] : htmlFiles(path);
11
+ return entry.endsWith(".html") ? [path] : [];
12
+ });
13
+ const scriptTag = (script, src) => {
14
+ const type = script.getAttribute("type");
15
+ return `<script${type && type !== "module" ? ` type="${type}"` : ""} src="./${src}"></script>`;
16
+ };
17
+ const TAG = /<[a-z][^\s/>]*(?:\s+[^\s=/>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*\s*\/?>/gi;
18
+ const HANDLER = /(\s)on([a-z][\w-]*)(?=\s*=)/g;
19
+ const DEFINITION = /<custom-element[\s>][\s\S]*?<\/custom-element>/g;
20
+ const inertHandlers = (html) => html.replace(DEFINITION, (definition) => definition.replace(TAG, (tag) => tag.replace(HANDLER, "$1realm:on$2")));
21
+ export const precompileFile = (path, root = dirname(path)) => {
22
+ let html = readFileSync(path, "utf8");
23
+ const { document } = parseHTML(/<html[\s>]/i.test(html) ? html : `<!doctype html><html><body>${html}</body></html>`);
24
+ const result = { modules: [], definitions: [] };
25
+ let cursor = 0;
26
+ for (const definition of document.querySelectorAll("custom-element")) {
27
+ const open = html.indexOf("<custom-element", cursor);
28
+ const openEnd = html.indexOf(">", open) + 1;
29
+ cursor = openEnd;
30
+ result.definitions.push(describe(definition, relative(root, path)));
31
+ const compiled = compileDefinition(definition);
32
+ if (!compiled)
33
+ continue;
34
+ const module = `${basename(path, ".html")}.${compiled.name}.js`;
35
+ writeFileSync(join(dirname(path), module), compiled.module);
36
+ result.modules.push(join(dirname(path), module));
37
+ if (!compiled.script) {
38
+ const tag = `<script type="realm" src="./${module}"></script>`;
39
+ html = html.slice(0, openEnd) + tag + html.slice(openEnd);
40
+ cursor = openEnd + tag.length;
41
+ continue;
42
+ }
43
+ const text = compiled.script.textContent;
44
+ const end = html.indexOf(`${text}</script>`, openEnd) + text.length + "</script>".length;
45
+ const start = html.lastIndexOf("<script", end - text.length);
46
+ const tag = scriptTag(compiled.script, module);
47
+ html = html.slice(0, start) + tag + html.slice(end);
48
+ cursor = start + tag.length;
49
+ }
50
+ const inert = inertHandlers(html);
51
+ if (inert !== readFileSync(path, "utf8"))
52
+ writeFileSync(path, inert);
53
+ return result;
54
+ };
55
+ export const precompile = (dir) => {
56
+ const results = htmlFiles(dir).map((file) => precompileFile(file, dir));
57
+ return {
58
+ modules: results.flatMap((result) => result.modules),
59
+ definitions: results.flatMap((result) => result.definitions),
60
+ };
61
+ };
62
+ export default function realm(options = {}) {
63
+ let outDir = "dist";
64
+ let build = false;
65
+ return {
66
+ name: "realm",
67
+ configResolved(config) {
68
+ outDir = join(config.root, config.build.outDir);
69
+ build = config.command === "build";
70
+ },
71
+ configureServer(server) {
72
+ server.middlewares.use((request, response, next) => {
73
+ const url = request.url;
74
+ const path = decodeURIComponent(url);
75
+ const file = join(server.config.root, path);
76
+ const fetched = !request.headers.accept?.includes("text/html");
77
+ if (!fetched || url.includes("?") || !path.endsWith(".html") || !existsSync(file))
78
+ return next();
79
+ response.setHeader("content-type", "text/html");
80
+ response.end(readFileSync(file));
81
+ });
82
+ },
83
+ closeBundle() {
84
+ if (!build)
85
+ return;
86
+ const { definitions } = precompile(outDir);
87
+ const manifest = options.manifest ?? "custom-elements.json";
88
+ if (manifest)
89
+ writeFileSync(join(outDir, manifest), `${JSON.stringify(createManifest(definitions), null, 2)}\n`);
90
+ },
91
+ };
92
+ }
@@ -0,0 +1,67 @@
1
+ export interface Source {
2
+ path: string;
3
+ html: string;
4
+ }
5
+ interface Attribute {
6
+ name: string;
7
+ fieldName: string;
8
+ type?: {
9
+ text: string;
10
+ };
11
+ default?: string;
12
+ }
13
+ export declare const describe: (definition: Element, path: string) => {
14
+ kind: string;
15
+ name: string;
16
+ tagName: string;
17
+ customElement: boolean;
18
+ attributes: Attribute[];
19
+ events: {
20
+ name: string;
21
+ }[];
22
+ slots: {
23
+ name: string;
24
+ }[];
25
+ cssParts: {
26
+ name: string;
27
+ }[];
28
+ cssStates: {
29
+ name: string;
30
+ }[];
31
+ path: string;
32
+ };
33
+ export declare const createManifest: (definitions: ReturnType<typeof describe>[]) => {
34
+ schemaVersion: string;
35
+ modules: {
36
+ kind: string;
37
+ path: string;
38
+ declarations: {
39
+ kind: string;
40
+ name: string;
41
+ tagName: string;
42
+ customElement: boolean;
43
+ attributes: Attribute[];
44
+ events: {
45
+ name: string;
46
+ }[];
47
+ slots: {
48
+ name: string;
49
+ }[];
50
+ cssParts: {
51
+ name: string;
52
+ }[];
53
+ cssStates: {
54
+ name: string;
55
+ }[];
56
+ }[];
57
+ exports: {
58
+ kind: string;
59
+ name: string;
60
+ declaration: {
61
+ name: string;
62
+ module: string;
63
+ };
64
+ }[];
65
+ }[];
66
+ };
67
+ export {};
@@ -0,0 +1,103 @@
1
+ import { tokenize } from "@realmorg/realm/compiler";
2
+ const named = (names) => [...new Set(names)].sort().map((name) => ({ name }));
3
+ const pascal = (tag) => tag.replace(/(^|-)([a-z0-9])/g, (_match, _dash, letter) => letter.toUpperCase());
4
+ const kebab = (key) => key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
5
+ const TYPES = {
6
+ string: () => "string",
7
+ number: () => "number",
8
+ boolean: () => "boolean",
9
+ date: () => "Date",
10
+ array: () => "array",
11
+ object: () => "object",
12
+ enum: (args) => args
13
+ .replace(/^\[|\]$/g, "")
14
+ .trim()
15
+ .replace(/\s*,\s*/g, " | "),
16
+ };
17
+ const propsObject = (script) => {
18
+ const start = script.indexOf("defineProps(");
19
+ if (start === -1)
20
+ return "";
21
+ const open = script.indexOf("{", start);
22
+ let depth = 0;
23
+ for (let index = open; index < script.length; index++) {
24
+ depth += { "{": 1, "}": -1 }[script[index]] ?? 0;
25
+ if (depth === 0)
26
+ return script.slice(open + 1, index);
27
+ }
28
+ return "";
29
+ };
30
+ const splitTopLevel = (source) => {
31
+ const parts = [];
32
+ let depth = 0;
33
+ let current = "";
34
+ for (const token of tokenize(source)) {
35
+ if (token.type === "punct" && "([{".includes(token.value))
36
+ depth++;
37
+ if (token.type === "punct" && ")]}".includes(token.value))
38
+ depth--;
39
+ if (depth === 0 && token.value === ",") {
40
+ parts.push(current);
41
+ current = "";
42
+ }
43
+ else
44
+ current += `${token.value} `;
45
+ }
46
+ return [...parts, current].map((part) => part.trim()).filter(Boolean);
47
+ };
48
+ const CALL = /\.\s*(\w+)\s*\(\s*((?:[^()]|\([^()]*\))*?)\s*\)/g;
49
+ const attributesOf = (script) => splitTopLevel(propsObject(script)).flatMap((entry) => {
50
+ const [key = "", definition = ""] = entry.split(/\s*:\s*(.*)/s);
51
+ const calls = new Map([...definition.matchAll(CALL)].map((call) => [call[1], call[2]]));
52
+ const type = [...calls.keys()].find((name) => name && name in TYPES);
53
+ if (!type)
54
+ return [];
55
+ const attribute = {
56
+ name: calls.get("attribute")?.replace(/^["'`]|["'`]$/g, "") ?? kebab(key),
57
+ fieldName: key,
58
+ type: { text: TYPES[type](calls.get(type)) },
59
+ };
60
+ if (calls.has("default"))
61
+ attribute.default = calls.get("default");
62
+ return [attribute];
63
+ });
64
+ const EVENTS = /(?:dispatch\s*\(|new\s+(?:Custom)?Event\s*\()\s*["'`]([a-z][\w-]*)["'`]/g;
65
+ const STATES = /:state\(([\w-]+)\)/g;
66
+ export const describe = (definition, path) => {
67
+ const tagName = definition.getAttribute("name");
68
+ const script = definition.querySelector(":scope > script")?.textContent ?? "";
69
+ const css = [...definition.querySelectorAll(":scope > style")]
70
+ .map((style) => style.textContent)
71
+ .join("\n");
72
+ const slots = [...definition.querySelectorAll("slot")]
73
+ .map((slot) => slot.getAttribute("name") ?? "")
74
+ .filter((name) => !/^[#@]/.test(name));
75
+ const parts = [...definition.querySelectorAll("[part]")].flatMap((el) => el.getAttribute("part").split(/\s+/));
76
+ return {
77
+ kind: "class",
78
+ name: pascal(tagName),
79
+ tagName,
80
+ customElement: true,
81
+ attributes: attributesOf(script),
82
+ events: named([...script.matchAll(EVENTS)].map((match) => match[1])),
83
+ slots: named(slots),
84
+ cssParts: named(parts),
85
+ cssStates: named([...css.matchAll(STATES)].map((match) => match[1])),
86
+ path,
87
+ };
88
+ };
89
+ export const createManifest = (definitions) => ({
90
+ schemaVersion: "2.1.0",
91
+ modules: definitions.map(({ path, ...declaration }) => ({
92
+ kind: "javascript-module",
93
+ path,
94
+ declarations: [declaration],
95
+ exports: [
96
+ {
97
+ kind: "custom-element-definition",
98
+ name: declaration.tagName,
99
+ declaration: { name: declaration.name, module: path },
100
+ },
101
+ ],
102
+ })),
103
+ });
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@realmorg/vite-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.0.0-alpha.3",
4
+ "description": "Vite plugin that pre-assembles REALM components for strict Content Security Policies and writes a custom-elements.json manifest.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "dependencies": {
17
+ "linkedom": "0.18.13",
18
+ "@realmorg/realm": "2.0.0-alpha.3"
19
+ },
20
+ "peerDependencies": {
21
+ "vite": ">=7"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "26.6.5",
25
+ "@vitest/coverage-v8": "5.0.5",
26
+ "playwright": "1.64.1",
27
+ "typescript": "7.0.2",
28
+ "vite": "8.3.4",
29
+ "vitest": "5.0.5",
30
+ "tsconfig": "0.0.0"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/realmorg/realm.git",
35
+ "directory": "packages/vite-plugin"
36
+ },
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "keywords": [
41
+ "realm",
42
+ "vite-plugin",
43
+ "web-components",
44
+ "csp"
45
+ ],
46
+ "scripts": {
47
+ "build": "tsc -p tsconfig.build.json",
48
+ "test": "vitest run --coverage",
49
+ "typecheck": "tsc --noEmit"
50
+ }
6
51
  }