diff --git a/guardrails.ratchet.json b/guardrails.ratchet.json index c7ae60294..5afdfc742 100644 --- a/guardrails.ratchet.json +++ b/guardrails.ratchet.json @@ -8,9 +8,9 @@ "anti-slop/no-runtime-typeof": 28, "typescript/no-base-to-string": 1, "typescript/no-unnecessary-type-parameters": 6, - "typescript/no-unsafe-argument": 559, - "typescript/no-unsafe-assignment": 1613, - "typescript/no-unsafe-return": 424, + "typescript/no-unsafe-argument": 477, + "typescript/no-unsafe-assignment": 1451, + "typescript/no-unsafe-return": 395, "typescript/restrict-template-expressions": 1, "typescript/unbound-method": 9, "typescript/use-unknown-in-catch-callback-variable": 5 diff --git a/packages/dms/playground/checks/aliases.cjs b/packages/dms/playground/checks/aliases.cjs index 47c47f70e..8c5a44c97 100644 --- a/packages/dms/playground/checks/aliases.cjs +++ b/packages/dms/playground/checks/aliases.cjs @@ -1,22 +1,21 @@ const { readdirSync, readFileSync, realpathSync } = require("node:fs"); -const { createRequire, isBuiltin } = require("node:module"); -const { - basename, - dirname, - extname, - isAbsolute, - join, - relative, - resolve, - sep, -} = require("node:path"); +const { isBuiltin } = require("node:module"); +const nodePath = require("node:path"); +const { sep } = nodePath; const ts = require("typescript"); const { z } = require("zod"); +const { + unwrap, + constantValue, + importMeta, + propertyName, + loaderReference, +} = require("./syntax.cjs"); -const root = resolve(__dirname, ".."); -const repository = resolve(root, "../../.."); +const root = nodePath.resolve(__dirname, ".."); +const repository = nodePath.resolve(root, "../../.."); const config = ts.readConfigFile( - join(repository, ".dependency-cruiser.tsconfig.json"), + nodePath.join(repository, ".dependency-cruiser.tsconfig.json"), (path) => ts.sys.readFile(path), ); const { options } = ts.parseJsonConfigFileContent( @@ -29,25 +28,18 @@ const cache = ts.createModuleResolutionCache( (path) => path, options, ); -const frontendRequire = createRequire( - join(root, "../frontend-vue/package.json"), -); -const { parse, compileTemplate } = frontendRequire("vue/compiler-sfc"); -const css = createRequire(frontendRequire.resolve("jsdom/package.json"))( - "css-tree", -); -const { globSync } = createRequire( - frontendRequire.resolve("vite/package.json"), -)("tinyglobby"); -const server = realpathSync(join(root, "src")); -const client = realpathSync(join(root, "frontend-vue")); +const { + vue: { parse, compileTemplate }, + glob: { globSync }, + css, +} = require("./frontend-tools.cjs"); +const server = realpathSync(nodePath.join(root, "src")); +const client = realpathSync(nodePath.join(root, "frontend-vue")); const layers = ["core", "ui", "layout", "auth", "onboarding"].map((layer) => - realpathSync(join(root, `../frontend-vue/layers/dms-${layer}/app`)), + realpathSync(nodePath.join(root, `../frontend-vue/layers/dms-${layer}/app`)), ); const specifierSchema = z.string(); -const rankRules = require( - join(repository, ".dependency-cruiser/playground.cjs"), -) +const rankRules = require("../../../../.dependency-cruiser/playground.cjs") .forbidden.filter((rule) => rule.name.endsWith("-no-upward")) .map((rule) => ({ from: new RegExp(rule.from.path), @@ -60,30 +52,6 @@ const loaderLibraries = new Set([ "child_process", "process", ]); -const loaderNames = new Set([ - "require", - "createRequire", - "eval", - "Function", - "System", - "Worker", - "URL", - "SharedWorker", - "importScripts", - "_load", - "_resolveFilename", - "getBuiltinModule", - "dlopen", - "mainModule", - "loadModule", - "globalThis", - "global", - "module", - "document", - "window", - "self", - "process", -]); const globalMethods = new Map([ ["window", new Set(["addEventListener", "removeEventListener"])], ["process", new Set(["uptime"])], @@ -119,7 +87,7 @@ const nonExecutableKinds = new Map([ ]); const trustedManifests = new Map([ [ - join(root, "package.json"), + nodePath.join(root, "package.json"), new Set([ "name", "version", @@ -133,7 +101,7 @@ const trustedManifests = new Map([ ]), ], [ - join(client, "package.json"), + nodePath.join(client, "package.json"), new Set(["name", "version", "private", "type", "main", "engines"]), ], ]); @@ -168,58 +136,31 @@ const vueScriptKinds = new Map([ ["ts", ts.ScriptKind.TS], ["tsx", ts.ScriptKind.TSX], ]); +/** @type {string[]} */ const failures = []; -function unwrap(node) { - while ( - ts.isParenthesizedExpression(node) || - ts.isAsExpression(node) || - ts.isTypeAssertionExpression(node) || - ts.isNonNullExpression(node) || - ts.isSatisfiesExpression(node) - ) { - node = node.expression; - } - return node; -} - -function constantValue(expression) { - const node = unwrap(expression); - if (ts.isStringLiteralLike(node)) return node.text; - if (ts.isNumericLiteral(node)) return Number(node.text); - if (node.kind === ts.SyntaxKind.TrueKeyword) return true; - if (node.kind === ts.SyntaxKind.FalseKeyword) return false; - if (node.kind === ts.SyntaxKind.NullKeyword) return null; - if (ts.isTemplateExpression(node)) { - let text = node.head.text; - for (const span of node.templateSpans) { - const value = constantValue(span.expression); - if (value === undefined) return undefined; - text += String(value) + span.literal.text; - } - return text; - } - if ( - ts.isBinaryExpression(node) && - node.operatorToken.kind === ts.SyntaxKind.PlusToken - ) { - const left = constantValue(node.left); - const right = constantValue(node.right); - if (left !== undefined && right !== undefined) return left + right; - } - return undefined; -} - +/** + * @param {string} path + * @param {string} area + * @returns {boolean} + */ function inside(path, area) { - const suffix = relative(area, path); + const suffix = nodePath.relative(area, path); return ( - suffix !== ".." && !suffix.startsWith(`..${sep}`) && !isAbsolute(suffix) + suffix !== ".." && + !suffix.startsWith(`..${sep}`) && + !nodePath.isAbsolute(suffix) ); } +/** + * @param {string} specifier + * @param {string} importer + * @returns {string | undefined} + */ function fallbackTarget(specifier, importer) { - if (specifier.startsWith(".") || isAbsolute(specifier)) { - const target = resolve(dirname(importer), specifier); + if (specifier.startsWith(".") || nodePath.isAbsolute(specifier)) { + const target = nodePath.resolve(nodePath.dirname(importer), specifier); return ts.sys.fileExists(target) ? target : undefined; } for (const [pattern, targets] of Object.entries(options.paths)) { @@ -230,16 +171,26 @@ function fallbackTarget(specifier, importer) { specifier.length - suffix.length, ); for (const target of targets) { - const path = resolve(options.baseUrl, target.replace("*", match)); + const path = nodePath.resolve( + options.baseUrl, + target.replace("*", match), + ); if (ts.sys.fileExists(path)) return path; } } return undefined; } +/** + * @param {string} importer + * @param {string} target + * @param {string | undefined} query + * @param {boolean} viteAssets + * @returns {boolean} + */ function permittedEdge(importer, target, query, viteAssets) { if ([server, client, ...layers].some((area) => inside(target, area))) { - const extension = extname(target); + const extension = nodePath.extname(target); const inert = nonExecutableKinds.get(query ?? extension); if ( target.split(sep).some((part) => skippedDirectories.has(part)) || @@ -252,8 +203,8 @@ function permittedEdge(importer, target, query, viteAssets) { ) return false; } - const from = relative(repository, importer).split(sep).join("/"); - const to = relative(repository, target).split(sep).join("/"); + const from = nodePath.relative(repository, importer).split(sep).join("/"); + const to = nodePath.relative(repository, target).split(sep).join("/"); if (rankRules.some((rule) => rule.from.test(from) && rule.to.test(to))) return false; return ( @@ -264,6 +215,12 @@ function permittedEdge(importer, target, query, viteAssets) { ); } +/** + * @param {string} specifier + * @param {string} importer + * @param {boolean} viteAssets + * @returns {boolean} + */ function permitted(specifier, importer, viteAssets) { importer = realpathSync(importer); const isClient = inside(importer, client); @@ -314,12 +271,18 @@ function permitted(specifier, importer, viteAssets) { (isClient && layers.some( (area) => - request.startsWith(`#${basename(dirname(area))}/app/`) && - inside(canonical, area), + request.startsWith( + `#${nodePath.basename(nodePath.dirname(area))}/app/`, + ) && inside(canonical, area), )) ); } +/** + * @param {unknown} value + * @param {string} path + * @param {boolean} [viteAssets] + */ function checkSpecifier(value, path, viteAssets = true) { const specifier = specifierSchema.safeParse(value); if (!specifier.success) { @@ -336,12 +299,17 @@ function checkSpecifier(value, path, viteAssets = true) { } } +/** + * @param {string} pattern + * @param {string} importer + * @returns {{ pattern: string, request: (file: string) => string } | undefined} + */ function globPattern(pattern, importer) { if (pattern.startsWith("./") || pattern.startsWith("../")) { return { - pattern: resolve(dirname(importer), pattern), + pattern: nodePath.resolve(nodePath.dirname(importer), pattern), request: (file) => - `./${relative(dirname(importer), file).split(sep).join("/")}`, + `./${nodePath.relative(nodePath.dirname(importer), file).split(sep).join("/")}`, }; } if (!/^#dms-(?:core|ui|layout|auth|onboarding)\/app\//.test(pattern)) @@ -349,16 +317,23 @@ function globPattern(pattern, importer) { for (const [alias, targets] of Object.entries(options.paths)) { const prefix = alias.replace(/\*$/, ""); if (!pattern.startsWith(prefix)) continue; - const directory = resolve(options.baseUrl, targets[0].replace(/\*$/, "")); + const directory = nodePath.resolve( + options.baseUrl, + targets[0].replace(/\*$/, ""), + ); return { - pattern: resolve(directory, pattern.slice(prefix.length)), + pattern: nodePath.resolve(directory, pattern.slice(prefix.length)), request: (file) => - prefix + relative(directory, file).split(sep).join("/"), + prefix + nodePath.relative(directory, file).split(sep).join("/"), }; } return undefined; } +/** + * @param {ts.Expression | undefined} argument + * @returns {z.infer | false | undefined} + */ function permittedGlobSettings(argument) { const settings = argument && unwrap(argument); const values = {}; @@ -378,6 +353,11 @@ function permittedGlobSettings(argument) { return parsed.success ? parsed.data : undefined; } +/** + * @param {ts.CallExpression} node + * @param {string} importer + * @returns {boolean} + */ function checkGlob(node, importer) { const argument = node.arguments[0] && unwrap(node.arguments[0]); const expressions = @@ -391,7 +371,9 @@ function checkGlob(node, importer) { ); const settings = permittedGlobSettings(node.arguments[1]); if (!parsed.success || !settings || node.arguments.length > 2) return false; + /** @type {NonNullable>[]} */ const positives = []; + /** @type {NonNullable>[]} */ const negatives = []; for (const pattern of parsed.data) { const negative = pattern.startsWith("!"); @@ -422,42 +404,11 @@ function checkGlob(node, importer) { return true; } -function importMeta(node) { - return ( - ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword - ); -} - -function propertyName(node) { - if (ts.isPropertyAccessExpression(node)) return node.name.text; - if (ts.isElementAccessExpression(node) && node.argumentExpression) - return constantValue(node.argumentExpression); - return undefined; -} - -function loaderReference(node) { - if (importMeta(node)) return "import.meta"; - if (node.kind === ts.SyntaxKind.ImportKeyword) return "import"; - if (ts.isIdentifier(node) && ["module", "document"].includes(node.text)) { - const property = [ - ts.isPropertyAccessExpression, - ts.isPropertyAssignment, - ts.isPropertySignature, - ts.isPropertyDeclaration, - ].some((matches) => matches(node.parent)); - if (property && node.parent.name === node) return undefined; - } - if (ts.isIdentifier(node) && loaderNames.has(node.text)) return node.text; - const property = propertyName(node); - if ( - (loaderNames.has(property) && !["module", "document"].includes(property)) || - property === "constructor" || - property === "import" - ) - return `property ${property}`; - return undefined; -} - +/** + * @param {ts.CallExpression} node + * @param {string} path + * @param {WeakSet} allowed + */ function checkCall(node, path, allowed) { const callee = unwrap(node.expression); if ( @@ -492,6 +443,11 @@ function checkCall(node, path, allowed) { } } +/** + * @param {string} text + * @param {string} path + * @param {ts.ScriptKind} [kind] + */ function checkScript(text, path, kind = ts.getScriptKindFromFileName(path)) { const source = ts.createSourceFile( path, @@ -508,6 +464,7 @@ function checkScript(text, path, kind = ts.getScriptKindFromFileName(path)) { return; } const allowed = new WeakSet(); + /** @param {ts.Node} node */ function visit(node) { if (ts.isCallExpression(node)) checkCall(node, path, allowed); if ( @@ -531,6 +488,10 @@ function checkScript(text, path, kind = ts.getScriptKindFromFileName(path)) { visit(source); } +/** + * @param {import("vue/compiler-sfc").SFCStyleBlock} block + * @param {string} path + */ function checkStyle(block, path) { if (block.src !== undefined) { failures.push(`${path}: external playground styles are forbidden`); @@ -558,6 +519,7 @@ function checkStyle(block, path) { } } +/** @param {string} path */ function checkVue(path) { const { descriptor, errors } = parse(readFileSync(path, "utf8"), { filename: path, @@ -609,6 +571,7 @@ function checkVue(path) { checkScript(compiled.code, filename, ts.ScriptKind.TS); } +/** @param {string} path */ function checkManifest(path) { const fields = trustedManifests.get(path); if (!fields) { @@ -617,15 +580,18 @@ function checkManifest(path) { ); return; } - const manifest = JSON.parse(readFileSync(path, "utf8")); + const manifest = z.unknown().parse(JSON.parse(readFileSync(path, "utf8"))); + if (manifest === null || manifest === undefined) + throw new TypeError(`${path}: playground package manifest is null`); for (const field of Object.keys(manifest)) if (!fields.has(field)) failures.push(`${path}: unsupported playground package field ${field}`); } +/** @param {string} directory */ function checkDirectory(directory) { for (const entry of readdirSync(directory, { withFileTypes: true })) { - const path = join(directory, entry.name); + const path = nodePath.join(directory, entry.name); if (entry.isSymbolicLink()) { failures.push(`${path}: playground source symlinks are forbidden`); } else if (entry.isDirectory()) { @@ -638,15 +604,15 @@ function checkDirectory(directory) { failures.push(`${path}: playground CSS files are forbidden`); } else if (entry.name.endsWith(".vue")) { checkVue(path); - } else if (codeExtensions.has(extname(entry.name))) { + } else if (codeExtensions.has(nodePath.extname(entry.name))) { checkScript(readFileSync(path, "utf8"), path); } } } -checkManifest(join(root, "package.json")); -checkDirectory(join(root, "src")); -checkDirectory(join(root, "frontend-vue")); +checkManifest(nodePath.join(root, "package.json")); +checkDirectory(nodePath.join(root, "src")); +checkDirectory(nodePath.join(root, "frontend-vue")); if (failures.length) { process.stderr.write(`${failures.join("\n")}\n`); process.exitCode = 1; diff --git a/packages/dms/playground/checks/fixtures.mjs b/packages/dms/playground/checks/fixtures.mjs new file mode 100644 index 000000000..15ad93c96 --- /dev/null +++ b/packages/dms/playground/checks/fixtures.mjs @@ -0,0 +1,49 @@ +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { rmSync, writeFileSync } from "node:fs"; +import nodePath from "node:path"; +import assert from "node:assert/strict"; + +export const root = nodePath.resolve(import.meta.dirname, ".."); +const scanner = nodePath.join(import.meta.dirname, "aliases.cjs"); + +/** + * @param {string} path + * @param {string} source + * @param {boolean} accepted + * @param {number | null} [expectedFailures] null accepts any non-empty set of diagnostics + */ +export function checkFixture( + path, + source, + accepted, + expectedFailures = accepted ? 0 : 1, +) { + writeFileSync(path, source); + /** @type {import("node:child_process").SpawnSyncReturns} */ + let result; + try { + result = spawnSync(process.execPath, [scanner], { encoding: "utf8" }); + } finally { + rmSync(path); + } + assert.equal(result.status, accepted ? 0 : 1, result.stdout + result.stderr); + const diagnostics = result.stderr + .split("\n") + .filter((line) => line.startsWith(`${path}:`)); + if (expectedFailures === null) { + assert.ok(diagnostics.length > 0, result.stderr); + } else { + assert.equal(diagnostics.length, expectedFailures, result.stderr); + } + return result; +} + +/** @param {string} area */ +export function fixturePath(area) { + return nodePath.join( + root, + area, + `__import_guard_${randomUUID().replaceAll("-", "")}.ts`, + ); +} diff --git a/packages/dms/playground/checks/frontend-tools.cjs b/packages/dms/playground/checks/frontend-tools.cjs new file mode 100644 index 000000000..d1fa7bafa --- /dev/null +++ b/packages/dms/playground/checks/frontend-tools.cjs @@ -0,0 +1,43 @@ +const { createRequire } = require("node:module"); +const nodePath = require("node:path"); + +const frontendRequire = createRequire( + nodePath.resolve(__dirname, "../../frontend-vue/package.json"), +); + +/** + * The Vue compiler, resolved from the frontend package the playground does not depend on. + * @returns {typeof import("../../frontend-vue/node_modules/vue/compiler-sfc")} + */ +function loadVueCompiler() { + return frontendRequire("vue/compiler-sfc"); +} + +/** + * The glob matcher vite ships, typed for the calls the checks make. + * @returns {{ globSync: (patterns: string | string[], options: { cwd?: string, absolute: boolean, dot?: boolean, expandDirectories?: boolean, ignore: string[] }) => string[] }} + */ +function loadGlob() { + return createRequire(frontendRequire.resolve("vite/package.json"))( + "tinyglobby", + ); +} + +/** + * The CSS parser jsdom ships; it publishes no declarations, so this types the two calls the checks make. + * @returns {{ + * parse: (css: string, options: { parseCustomProperty: boolean, onParseError: (error: Error) => void }) => object, + * walk: (ast: object, visit: (node: { type: string, name?: string }) => void) => void, + * }} + */ +function loadCssTree() { + return createRequire(frontendRequire.resolve("jsdom/package.json"))( + "css-tree", + ); +} + +module.exports = { + vue: loadVueCompiler(), + glob: loadGlob(), + css: loadCssTree(), +}; diff --git a/packages/dms/playground/checks/imports.test.cjs b/packages/dms/playground/checks/imports.test.mjs similarity index 66% rename from packages/dms/playground/checks/imports.test.cjs rename to packages/dms/playground/checks/imports.test.mjs index 3acf98d83..87d4e765c 100644 --- a/packages/dms/playground/checks/imports.test.cjs +++ b/packages/dms/playground/checks/imports.test.mjs @@ -1,49 +1,24 @@ -const assert = require("node:assert/strict"); -const { spawnSync } = require("node:child_process"); -const { randomUUID } = require("node:crypto"); -const { mkdirSync, rmSync, symlinkSync, writeFileSync } = require("node:fs"); -const { dirname, join, resolve } = require("node:path"); -const { test } = require("node:test"); +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import nodePath from "node:path"; +import { test } from "node:test"; +import { checkFixture, fixturePath, root } from "./fixtures.mjs"; -const root = resolve(__dirname, ".."); -const scanner = join(__dirname, "aliases.cjs"); +const scanner = nodePath.join(import.meta.dirname, "aliases.cjs"); -function checkFixture( - path, - source, - accepted, - expectedFailures = accepted ? 0 : 1, -) { - writeFileSync(path, source); - let result; - try { - result = spawnSync(process.execPath, [scanner], { encoding: "utf8" }); - } finally { - rmSync(path); - } - assert.equal(result.status, accepted ? 0 : 1, result.stdout + result.stderr); - const diagnostics = result.stderr - .split("\n") - .filter((line) => line.startsWith(`${path}:`)); - if (expectedFailures === null) { - assert.ok(diagnostics.length > 0, result.stderr); - } else { - assert.equal(diagnostics.length, expectedFailures, result.stderr); - } - return result; -} - -test("checks resolved import targets regardless of expression spelling or Vue source form", (t) => { +await test("checks resolved import targets regardless of expression spelling or Vue source form", (t) => { const baseline = spawnSync(process.execPath, [scanner], { encoding: "utf8" }); assert.equal(baseline.status, 0, baseline.stderr); const id = `__import_guard_${randomUUID().replaceAll("-", "")}`; - const hidden = join( + const hidden = nodePath.join( root, `../frontend-vue/layers/dms-core/app/node_modules/${id}`, ); - const dist = join(root, `dist/${id}.js`); - for (const path of [join(hidden, "index.js"), dist]) { - mkdirSync(dirname(path), { recursive: true }); + const dist = nodePath.join(root, `dist/${id}.js`); + for (const path of [nodePath.join(hidden, "index.js"), dist]) { + mkdirSync(nodePath.dirname(path), { recursive: true }); writeFileSync(path, "module.exports = 1;\n"); } t.after(() => { @@ -51,6 +26,7 @@ test("checks resolved import targets regardless of expression spelling or Vue so rmSync(dist); }); + /** @type {{ path: string, extension: string, wrap: (code: string) => string, client: boolean }[]} */ const contexts = [ { path: "src", extension: "ts", wrap: (code) => code, client: false }, { @@ -73,7 +49,11 @@ test("checks resolved import targets regardless of expression spelling or Vue so }, ]; for (const context of contexts) { - const path = join(root, context.path, `${id}.${context.extension}`); + const path = nodePath.join( + root, + context.path, + `${id}.${context.extension}`, + ); const ownDist = context.client ? `../../dist/${id}` : `../dist/${id}`; const backend = context.client ? "../../../src/index" : "../../src/index"; checkFixture( @@ -107,7 +87,7 @@ test("checks resolved import targets regardless of expression spelling or Vue so ); } } - const vue = join(root, "frontend-vue/app", `${id}.vue`); + const vue = nodePath.join(root, "frontend-vue/app", `${id}.vue`); checkFixture( vue, '', @@ -120,15 +100,7 @@ test("checks resolved import targets regardless of expression spelling or Vue so ); }); -function fixturePath(area) { - return join( - root, - area, - `__import_guard_${randomUUID().replaceAll("-", "")}.ts`, - ); -} - -test("rejects client import.meta.glob access to backend and interface sources", () => { +await test("rejects client import.meta.glob access to backend and interface sources", () => { const path = fixturePath("frontend-vue/app"); for (const pattern of [ "../../../src/**/*.ts", @@ -154,7 +126,7 @@ test("rejects client import.meta.glob access to backend and interface sources", ); }); -test("rejects client new URL access to backend source through import.meta.url", () => { +await test("rejects client new URL access to backend source through import.meta.url", () => { const result = checkFixture( fixturePath("frontend-vue/app"), 'new URL("../../../src/index.ts", import.meta.url);', @@ -164,7 +136,7 @@ test("rejects client new URL access to backend source through import.meta.url", assert.equal(result.status, 1); }); -test("rejects wrapped client relative dynamic imports into shared Vue layers", () => { +await test("rejects wrapped client relative dynamic imports into shared Vue layers", () => { const result = checkFixture( fixturePath("frontend-vue/app"), 'import(("../../../frontend-vue/layers/dms-core/app/utils/http-status" satisfies string));', @@ -174,11 +146,11 @@ test("rejects wrapped client relative dynamic imports into shared Vue layers", ( assert.equal(result.status, 1); }); -test("rejects server module.require and require.resolve access to own dist", (t) => { +await test("rejects server module.require and require.resolve access to own dist", (t) => { const path = fixturePath("src"); const id = `__import_guard_${randomUUID().replaceAll("-", "")}`; - const dist = join(root, "dist", `${id}.js`); - mkdirSync(dirname(dist), { recursive: true }); + const dist = nodePath.join(root, "dist", `${id}.js`); + mkdirSync(nodePath.dirname(dist), { recursive: true }); writeFileSync(dist, "module.exports = 1;\n"); t.after(() => rmSync(dist)); for (const loader of ["module.require", "require.resolve"]) { @@ -200,7 +172,7 @@ test("rejects server module.require and require.resolve access to own dist", (t) } }); -test("rejects same-tier and upward chart imports through wrapped require", () => { +await test("rejects same-tier and upward chart imports through wrapped require", () => { const path = fixturePath("src/chart"); for (const target of ["../quick-actions", "../index"]) { const result = checkFixture( @@ -215,7 +187,7 @@ test("rejects same-tier and upward chart imports through wrapped require", () => checkFixture(path, 'require(("./category" satisfies string));', true); }); -test("rejects server type imports from the client frontend-module package", () => { +await test("rejects server type imports from the client frontend-module package", () => { const result = checkFixture( fixturePath("src"), 'import type * as FrontendModule from "@antelopejs/dms-frontend/templates/vue/frontend-module.ts";', @@ -225,7 +197,7 @@ test("rejects server type imports from the client frontend-module package", () = assert.equal(result.status, 1); }); -test("rejects backend loaders in Vue templates rather than scanning only scripts", () => { +await test("rejects backend loaders in Vue templates rather than scanning only scripts", () => { const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); for (const source of [ ``, @@ -253,10 +225,10 @@ test("rejects backend loaders in Vue templates rather than scanning only scripts } }); -test("rejects scanned file symlinks instead of canonicalizing chart imports into quick-actions", (t) => { +await test("rejects scanned file symlinks instead of canonicalizing chart imports into quick-actions", (t) => { const id = `__import_guard_${randomUUID().replaceAll("-", "")}`; - const target = join(root, "src/quick-actions", `${id}.ts`); - const link = join(root, "src/chart", `${id}.ts`); + const target = nodePath.join(root, "src/quick-actions", `${id}.ts`); + const link = nodePath.join(root, "src/chart", `${id}.ts`); t.after(() => { rmSync(link, { force: true }); rmSync(target, { force: true }); @@ -271,7 +243,7 @@ test("rejects scanned file symlinks instead of canonicalizing chart imports into ); }); -test("rejects external Vue scripts rather than accepting uninspected contents", (t) => { +await test("rejects external Vue scripts rather than accepting uninspected contents", (t) => { const vue = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); const script = vue.replace(/\.vue$/, ".inc"); t.after(() => rmSync(script, { force: true })); @@ -285,13 +257,13 @@ test("rejects external Vue scripts rather than accepting uninspected contents", assert.equal(result.status, 1); }); -test("rejects source edges into every directory skipped by the scanner", (t) => { +await test("rejects source edges into every directory skipped by the scanner", (t) => { const path = fixturePath("frontend-vue/app"); const directory = path.replace(/\.ts$/, ""); t.after(() => rmSync(directory, { recursive: true, force: true })); for (const skipped of [".nuxt", ".output", "dist", "node_modules"]) { - const hidden = join(directory, skipped, "hidden.ts"); - mkdirSync(dirname(hidden), { recursive: true }); + const hidden = nodePath.join(directory, skipped, "hidden.ts"); + mkdirSync(nodePath.dirname(hidden), { recursive: true }); writeFileSync(hidden, 'import "../../../../../src/index.ts";\n'); const result = checkFixture( path, @@ -304,7 +276,7 @@ test("rejects source edges into every directory skipped by the scanner", (t) => checkFixture(path, 'import "./composables/usePageSetupLog";', true); }); -test("checks JSX loaders with the declared script kind and rejects parse recovery", () => { +await test("checks JSX loaders with the declared script kind and rejects parse recovery", () => { for (const extension of ["tsx", "jsx"]) { const path = fixturePath("frontend-vue/app").replace( /\.ts$/, @@ -348,7 +320,7 @@ test("checks JSX loaders with the declared script kind and rejects parse recover ); }); -test("rejects uninspected Vite inc targets even beside a TypeScript shadow", (t) => { +await test("rejects uninspected Vite inc targets even beside a TypeScript shadow", (t) => { const path = fixturePath("frontend-vue/app"); const bridge = path.replace(/\.ts$/, ".inc"); const shadow = `${bridge}.ts`; @@ -377,7 +349,7 @@ test("rejects uninspected Vite inc targets even beside a TypeScript shadow", (t) checkFixture(path, `export * from "./${target.split("/").at(-1)}";`, false); }); -test("rejects uninspected Node inc targets that can execute backend code", (t) => { +await test("rejects uninspected Node inc targets that can execute backend code", (t) => { const path = fixturePath("src").replace(/\.ts$/, ".cjs"); const bridge = path.replace(/\.cjs$/, ".inc"); t.after(() => rmSync(bridge, { force: true })); @@ -393,7 +365,7 @@ test("rejects uninspected Node inc targets that can execute backend code", (t) = assert.equal(result.status, 1); }); -test("rejects extensionless executable targets rather than trusting their local path", (t) => { +await test("rejects extensionless executable targets rather than trusting their local path", (t) => { const path = fixturePath("src").replace(/\.ts$/, ".cjs"); const bridge = path.replace(/\.cjs$/, ""); t.after(() => rmSync(bridge, { force: true })); @@ -409,7 +381,7 @@ test("rejects extensionless executable targets rather than trusting their local assert.equal(result.status, 1); }); -test("permits inert target kinds without treating Node require as a Vite asset loader", (t) => { +await test("permits inert target kinds without treating Node require as a Vite asset loader", (t) => { const path = fixturePath("frontend-vue/app"); const prefix = path.replace(/\.ts$/, ""); const sources = new Map([ @@ -444,20 +416,23 @@ test("permits inert target kinds without treating Node require as a Vite asset l checkFixture(path, `import asset = require("./${name}.css");`, false); }); -test("rejects scanned directory symlinks instead of silently skipping own-dist imports", (t) => { +await test("rejects scanned directory symlinks instead of silently skipping own-dist imports", (t) => { const id = `__import_guard_${randomUUID().replaceAll("-", "")}`; - const target = join(root, id); - const link = join(root, "src", id); - const dist = join(root, "dist", `${id}.js`); + const target = nodePath.join(root, id); + const link = nodePath.join(root, "src", id); + const dist = nodePath.join(root, "dist", `${id}.js`); t.after(() => { rmSync(link, { force: true }); rmSync(target, { recursive: true, force: true }); rmSync(dist, { force: true }); }); mkdirSync(target); - mkdirSync(dirname(dist), { recursive: true }); + mkdirSync(nodePath.dirname(dist), { recursive: true }); writeFileSync(dist, "module.exports = 1;\n"); - writeFileSync(join(target, "index.ts"), `require("../dist/${id}.js");\n`); + writeFileSync( + nodePath.join(target, "index.ts"), + `require("../dist/${id}.js");\n`, + ); symlinkSync(target, link, "dir"); const result = spawnSync(process.execPath, [scanner], { encoding: "utf8" }); assert.equal(result.status, 1, result.stdout + result.stderr); @@ -489,22 +464,22 @@ for (const { name, metadata, request } of [ request: ".", }, ]) { - test(`rejects package metadata resolution through ${name}`, (t) => { + await test(`rejects package metadata resolution through ${name}`, (t) => { const directory = fixturePath("src").replace(/\.ts$/, ""); mkdirSync(directory); t.after(() => rmSync(directory, { recursive: true, force: true })); - writeFileSync(join(directory, "safe.ts"), "export {};\n"); + writeFileSync(nodePath.join(directory, "safe.ts"), "export {};\n"); writeFileSync( - join(directory, "bridge.inc"), + nodePath.join(directory, "bridge.inc"), 'module.exports = require("../../../src/index.ts");', ); writeFileSync( - join(directory, "probe.cjs"), + nodePath.join(directory, "probe.cjs"), `require(${JSON.stringify(request)});`, ); assert.equal( checkFixture( - join(directory, "package.json"), + nodePath.join(directory, "package.json"), JSON.stringify(metadata), false, ).status, @@ -513,104 +488,18 @@ for (const { name, metadata, request } of [ }); } -test("rejects hidden/nested package.json across walked roots", (t) => { +await test("rejects hidden/nested package.json across walked roots", (t) => { for (const area of ["src", "frontend-vue", "frontend-vue/app"]) { const directory = fixturePath(area).replace(/\.ts$/, ""); - const nested = join(directory, ".hidden", "nested"); + const nested = nodePath.join(directory, ".hidden", "nested"); mkdirSync(nested, { recursive: true }); t.after(() => rmSync(directory, { recursive: true, force: true })); assert.equal( - checkFixture(join(nested, "package.json"), "{}", false).status, + checkFixture(nodePath.join(nested, "package.json"), "{}", false).status, 1, ); } }); -test("rejects inline and external Vue custom blocks", () => { - const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); - for (const block of [ - '{"message":"hello"}', - '', - ]) - assert.equal( - checkFixture(path, `${block}`, false) - .status, - 1, - ); -}); - -test("rejects CSS module imports and CSS @import files", (t) => { - const path = fixturePath("frontend-vue/app"); - const style = path.replace(/\.ts$/, ".css"); - t.after(() => rmSync(style, { force: true })); - writeFileSync(style, '@import "../../../src/index.ts";'); - for (const suffix of ["", "?raw", "?url"]) - assert.equal( - checkFixture( - path, - `import "./${style.split("/").at(-1)}${suffix}";`, - false, - null, - ).status, - 1, - ); -}); - -test("rejects Vue style-src including safe targets", () => { - const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); - for (const source of [ - "./composables/usePageSetupLog.ts", - "../../../src/index.ts", - ]) - assert.equal( - checkFixture( - path, - ``, - false, - ).status, - 1, - ); -}); - -test("rejects inline CSS @import/url, escapes, and unknown syntax", () => { - const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); - for (const source of [ - '@import "../../../src/index.ts";', - '.probe { background: url("../../../src/index.ts"); }', - String.raw`@\69mport "../../../src/index.ts";`, - String.raw`.probe { background: u\72l("../../../src/index.ts"); }`, - '.probe { --asset: url("../../../src/index.ts"); }', - '.probe { background: image-set("../../../src/index.ts" 1x); }', - '.probe { background: var(--asset, url("../../../src/index.ts")); }', - ".probe { color: ; broken }", - ]) - assert.equal( - checkFixture( - path, - ``, - false, - ).status, - 1, - ); -}); - -test("preserves safe existing inline styles", () => { - const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); - assert.equal( - checkFixture( - path, - ``, - true, - ).status, - 0, - ); -}); - -require("./manifest.test.cjs"); +await import("./manifest.test.mjs"); +await import("./styles.test.mjs"); diff --git a/packages/dms/playground/checks/internal-typescript.d.ts b/packages/dms/playground/checks/internal-typescript.d.ts new file mode 100644 index 000000000..57921cb10 --- /dev/null +++ b/packages/dms/playground/checks/internal-typescript.d.ts @@ -0,0 +1,14 @@ +import "typescript"; + +declare module "typescript" { + /** Exported at runtime by the compiler but left out of its public declarations. */ + function getScriptKindFromFileName(fileName: string): ScriptKind; + + /** Strips the parentheses, assertions and non-null operators around an expression. */ + function skipOuterExpressions(node: Expression): Expression; + + interface SourceFile { + /** Filled by the parser and left out of the public declarations. */ + readonly parseDiagnostics: readonly DiagnosticWithLocation[]; + } +} diff --git a/packages/dms/playground/checks/manifest.test.cjs b/packages/dms/playground/checks/manifest.test.cjs deleted file mode 100644 index ff92d779c..000000000 --- a/packages/dms/playground/checks/manifest.test.cjs +++ /dev/null @@ -1,60 +0,0 @@ -const assert = require("node:assert/strict"); -const { spawnSync } = require("node:child_process"); -const { mkdtempSync, rmSync, writeFileSync } = require("node:fs"); -const { tmpdir } = require("node:os"); -const { join, resolve } = require("node:path"); -const { test } = require("node:test"); - -const root = resolve(__dirname, ".."); -const scanner = join(__dirname, "aliases.cjs"); - -test("rejects browser remapping and unknown fields in both trusted manifests", (t) => { - const fixtures = mkdtempSync(join(tmpdir(), "playground-manifests-")); - t.after(() => rmSync(fixtures, { recursive: true, force: true })); - const preload = join(fixtures, "manifest.cjs"); - for (const directory of [root, join(root, "frontend-vue")]) { - const manifest = join(directory, "package.json"); - writeFileSync( - preload, - ` - const fs = require("node:fs"); - const read = fs.readFileSync; - fs.readFileSync = (file, ...options) => file === ${JSON.stringify(manifest)} - ? process.env.PLAYGROUND_MANIFEST_FIXTURE : read(file, ...options); - `, - ); - for (const field of [ - null, - "browser", - "module", - "types", - "imports", - "exports", - "react-native", - "workspaces", - "futureResolver", - ]) { - const metadata = { name: "guard-fixture" }; - if (field !== null) - metadata[field] = { - "./app/safe.ts": "../../src/utils/run-in-batches.ts", - }; - const result = spawnSync( - process.execPath, - ["--require", preload, scanner], - { - encoding: "utf8", - env: { - ...process.env, - PLAYGROUND_MANIFEST_FIXTURE: JSON.stringify(metadata), - }, - }, - ); - assert.equal( - result.status, - field === null ? 0 : 1, - result.stdout + result.stderr, - ); - } - } -}); diff --git a/packages/dms/playground/checks/manifest.test.mjs b/packages/dms/playground/checks/manifest.test.mjs new file mode 100644 index 000000000..d6cbeec58 --- /dev/null +++ b/packages/dms/playground/checks/manifest.test.mjs @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { test } from "node:test"; + +const root = path.resolve(import.meta.dirname, ".."); +const scanner = path.join(import.meta.dirname, "aliases.cjs"); + +await test("rejects browser remapping and unknown fields in both trusted manifests", (t) => { + const fixtures = mkdtempSync(path.join(tmpdir(), "playground-manifests-")); + t.after(() => rmSync(fixtures, { recursive: true, force: true })); + const preload = path.join(fixtures, "manifest.cjs"); + for (const directory of [root, path.join(root, "frontend-vue")]) { + const manifest = path.join(directory, "package.json"); + writeFileSync( + preload, + ` + const fs = require("node:fs"); + const read = fs.readFileSync; + fs.readFileSync = (file, ...options) => file === ${JSON.stringify(manifest)} + ? process.env.PLAYGROUND_MANIFEST_FIXTURE : read(file, ...options); + `, + ); + for (const field of [ + null, + "browser", + "module", + "types", + "imports", + "exports", + "react-native", + "workspaces", + "futureResolver", + "__proto__", + ]) { + const remap = JSON.stringify({ + "./app/safe.ts": "../../src/utils/run-in-batches.ts", + }); + const fixture = + field === null + ? '{"name":"guard-fixture"}' + : `{"name":"guard-fixture",${JSON.stringify(field)}:${remap}}`; + const result = spawnSync( + process.execPath, + ["--require", preload, scanner], + { + encoding: "utf8", + env: { + ...process.env, + PLAYGROUND_MANIFEST_FIXTURE: fixture, + }, + }, + ); + assert.equal( + result.status, + field === null ? 0 : 1, + result.stdout + result.stderr, + ); + if (field !== null) + assert.match( + result.stderr, + new RegExp(`unsupported playground package field ${field}$`, "m"), + ); + } + } +}); diff --git a/packages/dms/playground/checks/raw-sources.cjs b/packages/dms/playground/checks/raw-sources.cjs index 5b8f07efb..e11a56e2a 100644 --- a/packages/dms/playground/checks/raw-sources.cjs +++ b/packages/dms/playground/checks/raw-sources.cjs @@ -7,24 +7,28 @@ const { statSync, } = require("node:fs"); const { createRequire } = require("node:module"); -const { dirname, extname, join, relative, resolve, sep } = require("node:path"); +const nodePath = require("node:path"); +const { sep } = nodePath; const ts = require("typescript"); -const playground = resolve(__dirname, ".."); -const repository = resolve(playground, "../../.."); -const frontendRequire = createRequire( - join(playground, "../frontend-vue/package.json"), -); -const { parse } = frontendRequire("vue/compiler-sfc"); -const { globSync } = createRequire( - frontendRequire.resolve("vite/package.json"), -)("tinyglobby"); -const { ANTELOPE_IGNORE_PATTERNS } = createRequire( - join(repository, "package.json"), -)("@antelopejs/tooling-configs/oxc/lint"); -const { ignorePatterns } = require( - join(repository, "oxlint.config.ts"), -).default; +const playground = nodePath.resolve(__dirname, ".."); +const repository = nodePath.resolve(playground, "../../.."); +/** + * The lint presets of the workspace root. + * @returns {typeof import("@antelopejs/tooling-configs/oxc/lint")} + */ +function loadLintPresets() { + return createRequire(nodePath.join(repository, "package.json"))( + "@antelopejs/tooling-configs/oxc/lint", + ); +} + +const { + vue: { parse }, + glob: { globSync }, +} = require("./frontend-tools.cjs"); +const { ANTELOPE_IGNORE_PATTERNS } = loadLintPresets(); +const { ignorePatterns } = require("../../../../oxlint.config.ts").default; /** The directory oxlint leaves to the Vue layer's own ESLint config. */ const ESLINT_OWNED = "packages/dms/frontend-vue/**"; @@ -39,15 +43,25 @@ const scriptExtensions = new Set([ ".cts", ]); const lintedExtensions = new Set([...scriptExtensions, ".vue"]); +/** @type {string[]} */ const failures = []; +/** @type {Set} */ const rawFiles = new Set(); -/** Repository-relative POSIX path of an absolute path. */ +/** + * Repository-relative POSIX path of an absolute path. + * @param {string} path + * @returns {string} + */ function repositoryPath(path) { - return relative(repository, path).split(sep).join("/"); + return nodePath.relative(repository, path).split(sep).join("/"); } -/** Text of a property name the parser can read without evaluating code. */ +/** + * Text of a property name the parser can read without evaluating code. + * @param {ts.ObjectLiteralElementLike} property + * @returns {string | undefined} + */ function propertyName(property) { const name = property.name; if (name && ts.isComputedPropertyName(name)) @@ -63,51 +77,72 @@ function propertyName(property) { * Whether an ignore pattern names a `.claude/skills` link into `.agents/skills`, * or everything below one. The lint reads the link's files at their target, so * ignoring the link hides nothing. + * @param {string} pattern + * @returns {boolean} */ function isSkillLink(pattern) { const entry = pattern.replace(/\/\*\*$/u, ""); if (!/^\.claude\/skills\/[^/]+$/u.test(entry)) return false; - const path = join(repository, entry); + const path = nodePath.join(repository, entry); return ( existsSync(path) && lstatSync(path).isSymbolicLink() && realpathSync(path).startsWith( - join(realpathSync(repository), ".agents/skills") + sep, + nodePath.join(realpathSync(repository), ".agents/skills") + sep, ) ); } -/** The file Vite loads for a path written without its extension or as a directory. */ +/** + * The file Vite loads for a path written without its extension or as a directory. + * @param {string} path + * @returns {string | undefined} + */ function resolveSource(path) { if (existsSync(path) && statSync(path).isFile()) return path; const candidates = [...lintedExtensions].flatMap((extension) => [ `${path}${extension}`, - join(path, `index${extension}`), + nodePath.join(path, `index${extension}`), ]); return candidates.find((candidate) => existsSync(candidate)); } -/** Whether a Vite query string requests the raw source. */ +/** + * Whether a Vite query string requests the raw source. + * @param {string} query + * @returns {boolean} + */ function isRawQuery(query) { return new URLSearchParams(query.replace(/^\?/u, "")).has("raw"); } -/** Where Node resolves a bare specifier from a file, if anywhere. */ +/** + * Where Node resolves a bare specifier from a file, if anywhere. + * @param {string} path + * @param {string} file + * @returns {string | undefined} + */ function packageFile(path, file) { try { - return createRequire(join(repository, file)).resolve(path); + return createRequire(nodePath.join(repository, file)).resolve(path); } catch { return undefined; } } -/** Records the target of an import specifier that carries `?raw`. */ +/** + * Records the target of an import specifier that carries `?raw`. + * @param {string} specifier + * @param {string} file + */ function addSpecifier(specifier, file) { const query = specifier.indexOf("?"); if (query === -1 || !isRawQuery(specifier.slice(query))) return; const path = specifier.slice(0, query); if (path.startsWith("./") || path.startsWith("../")) { - const target = resolveSource(resolve(repository, dirname(file), path)); + const target = resolveSource( + nodePath.resolve(repository, nodePath.dirname(file), path), + ); if (target) rawFiles.add(repositoryPath(target)); else failures.push(`${file}: "${specifier}" resolves to no file`); return; @@ -116,7 +151,12 @@ function addSpecifier(specifier, file) { failures.push(`${file}: import "${specifier}" by relative path`); } -/** Whether `import.meta.glob` options request raw sources. */ +/** + * Whether `import.meta.glob` options request raw sources. + * @param {ts.Expression | undefined} options + * @param {string} file + * @returns {boolean} + */ function isRawGlob(options, file) { if (options === undefined) return false; if (!ts.isObjectLiteralExpression(options)) { @@ -146,7 +186,11 @@ function isRawGlob(options, file) { }); } -/** Records every file an `import.meta.glob` call loads as raw source. */ +/** + * Records every file an `import.meta.glob` call loads as raw source. + * @param {ts.CallExpression} call + * @param {string} file + */ function addGlob(call, file) { const [patterns, options] = call.arguments; if (!isRawGlob(options, file)) return; @@ -164,7 +208,7 @@ function addGlob(call, file) { failures.push(`${file}: write ?raw glob patterns as relative literals`); return; } - const cwd = resolve(repository, dirname(file)); + const cwd = nodePath.resolve(repository, nodePath.dirname(file)); for (const match of globSync(sources, { cwd, absolute: true, @@ -173,7 +217,11 @@ function addGlob(call, file) { rawFiles.add(repositoryPath(match)); } -/** Whether a node is the `import.meta.glob` member. */ +/** + * Whether a node is the `import.meta.glob` member. + * @param {ts.Node} node + * @returns {boolean} + */ function isGlobMember(node) { if (!ts.isPropertyAccessExpression(node) || node.name.text !== "glob") return false; @@ -184,7 +232,11 @@ function isGlobMember(node) { ); } -/** Records the `?raw` imports below one syntax node. */ +/** + * Records the `?raw` imports below one syntax node. + * @param {ts.Node} node + * @param {string} file + */ function visit(node, file) { if ( (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && @@ -207,7 +259,12 @@ function visit(node, file) { ts.forEachChild(node, (child) => visit(child, file)); } -/** Records the `?raw` imports of one script body. */ +/** + * Records the `?raw` imports of one script body. + * @param {string} source + * @param {string} file + * @param {ts.ScriptKind} kind + */ function scan(source, file, kind) { visit( ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, kind), @@ -223,10 +280,11 @@ const files = execFileSync( .split("\0") .filter( (file) => - lintedExtensions.has(extname(file)) && existsSync(join(repository, file)), + lintedExtensions.has(nodePath.extname(file)) && + existsSync(nodePath.join(repository, file)), ); for (const file of files) { - const source = readFileSync(join(repository, file), "utf8"); + const source = readFileSync(nodePath.join(repository, file), "utf8"); if (!source.includes("raw")) continue; if (!file.endsWith(".vue")) { scan( @@ -250,9 +308,13 @@ const listed = new Set( !isSkillLink(pattern), ), ); +/** + * @param {string} left + * @param {string} right + */ const byPath = (left, right) => left.localeCompare(right); const linted = [...rawFiles].filter((file) => - lintedExtensions.has(extname(file)), + lintedExtensions.has(nodePath.extname(file)), ); for (const file of linted.sort(byPath)) if (!listed.has(file)) diff --git a/packages/dms/playground/checks/styles.test.mjs b/packages/dms/playground/checks/styles.test.mjs new file mode 100644 index 000000000..d44c5d8f5 --- /dev/null +++ b/packages/dms/playground/checks/styles.test.mjs @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import { rmSync, writeFileSync } from "node:fs"; +import { test } from "node:test"; +import { checkFixture, fixturePath } from "./fixtures.mjs"; + +await test("rejects inline and external Vue custom blocks", () => { + const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); + for (const block of [ + '{"message":"hello"}', + '', + ]) + assert.equal( + checkFixture(path, `${block}`, false) + .status, + 1, + ); +}); + +await test("rejects CSS module imports and CSS @import files", (t) => { + const path = fixturePath("frontend-vue/app"); + const style = path.replace(/\.ts$/, ".css"); + t.after(() => rmSync(style, { force: true })); + writeFileSync(style, '@import "../../../src/index.ts";'); + for (const suffix of ["", "?raw", "?url"]) + assert.equal( + checkFixture( + path, + `import "./${style.split("/").at(-1)}${suffix}";`, + false, + null, + ).status, + 1, + ); +}); + +await test("rejects Vue style-src including safe targets", () => { + const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); + for (const source of [ + "./composables/usePageSetupLog.ts", + "../../../src/index.ts", + ]) + assert.equal( + checkFixture( + path, + ``, + false, + ).status, + 1, + ); +}); + +await test("rejects inline CSS @import/url, escapes, and unknown syntax", () => { + const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); + for (const source of [ + '@import "../../../src/index.ts";', + '.probe { background: url("../../../src/index.ts"); }', + String.raw`@\69mport "../../../src/index.ts";`, + String.raw`.probe { background: u\72l("../../../src/index.ts"); }`, + '.probe { --asset: url("../../../src/index.ts"); }', + '.probe { background: image-set("../../../src/index.ts" 1x); }', + '.probe { background: var(--asset, url("../../../src/index.ts")); }', + ".probe { color: ; broken }", + ]) + assert.equal( + checkFixture( + path, + ``, + false, + ).status, + 1, + ); +}); + +await test("preserves safe existing inline styles", () => { + const path = fixturePath("frontend-vue/app").replace(/\.ts$/, ".vue"); + assert.equal( + checkFixture( + path, + ``, + true, + ).status, + 0, + ); +}); diff --git a/packages/dms/playground/checks/syntax.cjs b/packages/dms/playground/checks/syntax.cjs new file mode 100644 index 000000000..23e6f05cf --- /dev/null +++ b/packages/dms/playground/checks/syntax.cjs @@ -0,0 +1,124 @@ +const ts = require("typescript"); + +const loaderNames = new Set([ + "require", + "createRequire", + "eval", + "Function", + "System", + "Worker", + "URL", + "SharedWorker", + "importScripts", + "_load", + "_resolveFilename", + "getBuiltinModule", + "dlopen", + "mainModule", + "loadModule", + "globalThis", + "global", + "module", + "document", + "window", + "self", + "process", +]); +/** + * @param {ts.Node} node + * @returns {ts.Node} + */ +function unwrap(node) { + while ( + ts.isParenthesizedExpression(node) || + ts.isAsExpression(node) || + ts.isTypeAssertionExpression(node) || + ts.isNonNullExpression(node) || + ts.isSatisfiesExpression(node) + ) { + node = node.expression; + } + return node; +} +/** + * @param {ts.Node} expression + * @returns {string | number | boolean | null | undefined} + */ +function constantValue(expression) { + const node = unwrap(expression); + if (ts.isStringLiteralLike(node)) return node.text; + if (ts.isNumericLiteral(node)) return Number(node.text); + if (node.kind === ts.SyntaxKind.TrueKeyword) return true; + if (node.kind === ts.SyntaxKind.FalseKeyword) return false; + if (node.kind === ts.SyntaxKind.NullKeyword) return null; + if (ts.isTemplateExpression(node)) { + let text = node.head.text; + for (const span of node.templateSpans) { + const value = constantValue(span.expression); + if (value === undefined) return undefined; + text += String(value) + span.literal.text; + } + return text; + } + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.PlusToken + ) { + const left = constantValue(node.left); + const right = constantValue(node.right); + if (left !== undefined && right !== undefined) return left + right; + } + return undefined; +} +/** + * @param {ts.Node} node + * @returns {boolean} + */ +function importMeta(node) { + return ( + ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword + ); +} +/** + * @param {ts.Node} node + * @returns {string | number | boolean | null | undefined} + */ +function propertyName(node) { + if (ts.isPropertyAccessExpression(node)) return node.name.text; + if (ts.isElementAccessExpression(node) && node.argumentExpression) + return constantValue(node.argumentExpression); + return undefined; +} +/** + * @param {ts.Node} node + * @returns {string | undefined} + */ +function loaderReference(node) { + if (importMeta(node)) return "import.meta"; + if (node.kind === ts.SyntaxKind.ImportKeyword) return "import"; + if (ts.isIdentifier(node) && ["module", "document"].includes(node.text)) { + const property = [ + ts.isPropertyAccessExpression, + ts.isPropertyAssignment, + ts.isPropertySignature, + ts.isPropertyDeclaration, + ].some((matches) => matches(node.parent)); + if (property && node.parent.name === node) return undefined; + } + if (ts.isIdentifier(node) && loaderNames.has(node.text)) return node.text; + const property = propertyName(node); + if ( + (loaderNames.has(property) && !["module", "document"].includes(property)) || + property === "constructor" || + property === "import" + ) + return `property ${property}`; + return undefined; +} +module.exports = { + unwrap, + constantValue, + importMeta, + propertyName, + loaderReference, +}; diff --git a/packages/dms/playground/checks/tsconfig.json b/packages/dms/playground/checks/tsconfig.json new file mode 100644 index 000000000..2b768df43 --- /dev/null +++ b/packages/dms/playground/checks/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "../../../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "allowJs": true, + "incremental": false, + "declaration": false, + "module": "nodenext", + "moduleResolution": "nodenext", + "allowImportingTsExtensions": true, + "types": ["node"] + }, + "include": ["**/*.cjs", "**/*.mjs", "**/*.d.ts"] +} diff --git a/packages/dms/playground/package.json b/packages/dms/playground/package.json index 58c1c9b45..d015d271b 100644 --- a/packages/dms/playground/package.json +++ b/packages/dms/playground/package.json @@ -6,7 +6,7 @@ "packageManager": "pnpm@10.2.0", "scripts": { "build": "rimraf dist && tsc", - "test": "node checks/aliases.cjs && node --test checks/imports.test.cjs", + "test": "node checks/aliases.cjs && node --test checks/imports.test.mjs", "dev": "ajs project run -w", "frontend:dev": "ajs dms dev" },