diff --git a/.github/workflows/node.js.yml b/.github/workflows/node.js.yml new file mode 100644 index 0000000..1e042af --- /dev/null +++ b/.github/workflows/node.js.yml @@ -0,0 +1,24 @@ +name: Node.js CI +on: + push: + branches: ['main'] + pull_request: +jobs: + build: + name: 'Node.js build: fmt, clean-install, lint, test' + runs-on: ubuntu-latest + strategy: + matrix: + node-version: + # - 20.x + - latest + steps: + - uses: actions/checkout@v3 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + - run: npm run fmt + - run: npm clean-install + - run: npm run lint + - run: npm run test diff --git a/README.md b/README.md index dbc793c..df40cc0 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ The fastest, most lightweight, fewest dependency jQuery alternative. -Development Build: 145B (with comments) \ -Production Build: 103B (min + gz) +Development Build: 572B (types + comments) \ +Production Build: 146B (min + gz) ## Example Usage @@ -18,11 +18,15 @@ console.log("innerText:", $("p:nth-child(2").innerText); ### via GitHub ```bash -my_ver="v2.1.2" +my_ver="v3.0.0" mkdir ./vendor/ + curl -fsSL "https://raw.githubusercontent.com/coolaj86/ajquery.js/${my_ver}/ajquery.js" \ -o ./vendor/ajquery.js + +# Lighthouse-optimized +npx -p uglify-js@3 uglifyjs ./vendor/ajquery.js -o ./vendor/ajquery.min.js ``` ```html @@ -32,7 +36,41 @@ curl -fsSL "https://raw.githubusercontent.com/coolaj86/ajquery.js/${my_ver}/ajqu ### via CDN ```html - + +``` + +Bundler-optimized: + +```html + +``` + +Tree-shaking-optimized: + +```html + +``` + +### via NPM + +```sh +npm install --save ajquery@3 +``` + +#### CommonJS + +```js +let AJQuery = require("ajquery"); +let $ = AJQuery.$; +let $$ = AJQuery.$$; +``` + +#### ESM + +```js +import AJQuery from "ajquery"; +let $ = AJQuery.$; +let $$ = AJQuery.$$; ``` ## API diff --git a/ajquery.cjs b/ajquery.cjs new file mode 100644 index 0000000..a80d3a2 --- /dev/null +++ b/ajquery.cjs @@ -0,0 +1,47 @@ +/** + * @typedef AJQuery + * @prop {AJQuerySelector} $ + * @prop {AJQuerySelectorAll} $$ + */ + +/** + * Select first matching element, just like console $ + * @callback AJQuerySelector + * @param {String} cssSelector + * @param {ParentNode} [$parent=document] + */ + +/** + * Select all matching child elements as a JS Array, just like console $$ + * @callback AJQuerySelectorAll + * @param {String} cssSelector + * @param {ParentNode} [$parent=document] + */ + +/** @type {AJQuery} */ +//@ts-ignore +var AJQuery = ("object" === typeof module && exports) || {}; +(function (window, AJQuery) { + "use strict"; + + /** @type {AJQuerySelector} */ + AJQuery.$ = function (cssSelector, $parent = document) { + let $child = $parent.querySelector(cssSelector); + return $child; + }; + + /** @type {AJQuerySelectorAll} */ + AJQuery.$$ = function (cssSelector, $parent = document) { + let nodeList = $parent.querySelectorAll(cssSelector); + let $children = Array.from(nodeList); + return $children; + }; + + Object.assign(window, AJQuery); + + //@ts-ignore + window.AJQuery = AJQuery; +})(globalThis.window || {}, AJQuery); +if ("object" === typeof module) { + module.exports = AJQuery; +} diff --git a/ajquery.js b/ajquery.js index 0ad0405..caaa8ab 100644 --- a/ajquery.js +++ b/ajquery.js @@ -1,7 +1,20 @@ -function $(sel, el) { - return (el || document).querySelector(sel); +/** + * Select first matching element, just like console $ + * @param {String} cssSelector + * @param {ParentNode} [$parent=document] + */ +function $(cssSelector, $parent = document) { + let $child = $parent.querySelector(cssSelector); + return $child; } -function $$(sel, el) { - return Array.from((el || document).querySelectorAll(sel)); +/** + * Select all matching child elements as a JS Array, just like console $$ + * @param {String} cssSelector + * @param {ParentNode} [$parent=document] + */ +function $$(cssSelector, $parent = document) { + let nodeList = $parent.querySelectorAll(cssSelector); + let $children = Array.from(nodeList); + return $children; } diff --git a/ajquery.mjs b/ajquery.mjs new file mode 100644 index 0000000..617efe4 --- /dev/null +++ b/ajquery.mjs @@ -0,0 +1,32 @@ +/** @import('typed-query-selector/strict') */ + +let AJQuery = { $, $$ }; + +/** + * AJQuery - The fastest, most lightweight, least dependency jQuery alternative, + * now Ai-enhanced, and better than ever! + * @namespace AJQuery + */ + +/** + * Selects the first element that matches the given selector within the specified parent. + * @param {string} sel - The CSS selector to match. + * @param {Document|Element} [$parent=document] - The parent element to search within. Defaults to document. + */ +function $(sel, $parent = document) { + let $child = $parent.querySelector(sel); + return $child; +} + +/** + * Select all matching child elements from $parent (which is document by default) + * @param {String} sel - The CSS selector to match. + * @param {Document|Element} [$parent=document] - The parent element to search within. Defaults to document. + */ +function $$(sel, $parent = document) { + let $children = $parent.querySelectorAll(sel); + let children = Array.from($children); + return children; +} + +export default AJQuery; diff --git a/benchmark.js b/benchmark.js index d6a71d4..58a1710 100644 --- a/benchmark.js +++ b/benchmark.js @@ -8,6 +8,8 @@ async function main() { console.info("Angular: 2517"); await sleep(520); console.info("React: 3785"); + await sleep(128); + console.info("Vite: 6666"); await sleep(230); console.info('"Vanilla" JS: 6237'); await sleep(65); diff --git a/example.html b/example.html index 5534620..cc0d13a 100644 --- a/example.html +++ b/example.html @@ -6,6 +6,18 @@ + + + + + + diff --git a/jsconfig.json b/jsconfig.json new file mode 100644 index 0000000..1ea57c0 --- /dev/null +++ b/jsconfig.json @@ -0,0 +1,118 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["./typings","./node_modules/@types"], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "include": [ + "ajquery.js", + "ajquery.cjs", + "ajquery.mjs", + "bin/**/*.js", + "lib/**/*.js", + "src/**/*.js" + ], + "exclude": ["node_modules"] +} diff --git a/package-lock.json b/package-lock.json index 0202445..07e3268 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ajquery", - "version": "2.1.2", + "version": "3.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ajquery", - "version": "2.1.2", + "version": "3.0.0", "license": "MPL-2.0" } } diff --git a/package.json b/package.json index 59e3660..39d07ca 100644 --- a/package.json +++ b/package.json @@ -1,18 +1,44 @@ { "name": "ajquery", - "version": "2.1.2", + "version": "3.0.0", "description": "The fastest, most lightweight, least dependency jQuery alternative", - "main": "ajquery.min.js", + "main": "ajquery.cjs", + "module": "ajquery.mjs", + "type": "commonjs", + "browser": { + "ajquery.min.cjs": "ajquery.min.js" + }, + "exports": { + ".": { + "require": "./ajquery.cjs", + "import": "./ajquery.mjs", + "default": "./ajquery.cjs" + } + }, "files": [ - "ajquery.js" + "ajquery.js", + "ajquery.min.js", + "ajquery.cjs", + "ajquery.min.cjs", + "ajquery.mjs", + "ajquery.min.mjs" ], "scripts": { - "benchmark": "node benchmark.js", + "benchmark": "node ./benchmark.js", + "build": "npm run build-all", + "bump": "npm version -m \"chore(release): bump to v%s\"", + "fmt": "npm run prettier", + "lint": "npm run jshint && npm run tsc", + "start": "open http://localhost/example.html && caddy file-server --browse --root .", + "test": "node ./tests/", + "--------": "---------------------------------------", + "build-all": "npx uglify-js ajquery.js -o ajquery.min.js && npx uglify-js ajquery.cjs -o ajquery.min.cjs && npx uglify-js ajquery.js -o ajquery.min.mjs", + "jshint": "npx -p jshint@2.x -- jshint -c ./.jshintrc ./ajquery.js ./ajquery.cjs ./ajquery.mjs", "prepare": "npm run build", - "start": "open example.html", + "prepublish": "npm run reexport-types", "prettier": "npx prettier -w '**/*.{js,md,css,html}'", - "build": "npx uglify-js ajquery.js -o ajquery.min.js", - "test": "node test.js" + "reexport-types": "npx -p jswt@1.x -- reexport", + "tsc": "npx -p typescript@5.x -- tsc -p ./jsconfig.json" }, "repository": { "type": "git", diff --git a/test.js b/tests/browser.js similarity index 100% rename from test.js rename to tests/browser.js diff --git a/tests/commonjs.cjs b/tests/commonjs.cjs new file mode 100644 index 0000000..c400d45 --- /dev/null +++ b/tests/commonjs.cjs @@ -0,0 +1,21 @@ +"use strict"; + +let AJQueryDefault = require("../"); +let AJQueryExplicit = require("../ajquery.cjs"); + +if (!AJQueryDefault.$) { + throw new Error("did not export $ correctly"); +} +if (!AJQueryDefault.$$) { + throw new Error("did not export $$ correctly"); +} + +if (AJQueryDefault.$ !== AJQueryExplicit.$) { + throw new Error("exported $s do not match"); +} + +if (AJQueryDefault.$$ !== AJQueryExplicit.$$) { + throw new Error("exported $$s do not match"); +} + +console.log(`\x1b[34mPASS\x1b[33m`); diff --git a/tests/esm.mjs b/tests/esm.mjs new file mode 100644 index 0000000..70ab827 --- /dev/null +++ b/tests/esm.mjs @@ -0,0 +1,12 @@ +"use strict"; + +import AJQueryExplicit from "../ajquery.mjs"; + +if (!AJQueryExplicit.$) { + throw new Error("did not export $ correctly"); +} +if (!AJQueryExplicit.$$) { + throw new Error("did not export $$ correctly"); +} + +console.log(`\x1b[34mPASS\x1b[33m`); diff --git a/tests/index.js b/tests/index.js new file mode 100644 index 0000000..86f5731 --- /dev/null +++ b/tests/index.js @@ -0,0 +1,109 @@ +"use strict"; + +let ChildProcess = require("child_process"); +let Fs = require("node:fs/promises"); +let Path = require("node:path"); + +async function main() { + console.info("TAP version 13"); + + let dirents = await Fs.readdir(__dirname, { withFileTypes: true }); + + let failures = 0; + let count = 0; + for (let dirent of dirents) { + if (dirent.name === "index.js") { + continue; + } + + count += 1; + let direntPath = Path.join(__dirname, dirent.name); + let relPath = Path.relative(".", direntPath); + + let success = await handleEach(count, relPath); + if (!success) { + failures += 1; + } + } + + let start = 1; + if (count < 1) { + start = 0; + } + + let passes = count - failures; + console.info(``); + console.info(`${start}..${count}`); + console.info(`# tests ${count}`); + console.info(`# pass ${passes}`); + console.info(`# fail ${failures}`); + console.info(`# skip 0`); + + if (failures !== 0) { + process.exit(1); + } +} + +async function handleEach(count, relPath) { + let success = await exec("node", [relPath]) + .then(function (result) { + console.info(`ok ${count} - ${relPath}`); + return true; + }) + .catch(function (err) { + console.info(`not ok ${count} - ${relPath}`); + if (err.code) { + console.info(` # Error: ${err.code}`); + } + if (err.stderr) { + console.info(` # Stderr: ${err.stderr}`); + } + return false; + }); + + return success; +} + +async function exec(exe, args) { + return new Promise(function (resolve, reject) { + let cmd = ChildProcess.spawn(exe, args); + + let stdout = []; + let stderr = []; + + cmd.stdout.on("data", function (data) { + stdout.push(data.toString("utf8")); + }); + + cmd.stderr.on("data", function (data) { + stderr.push(data.toString("utf8")); + }); + + cmd.on("close", function (code) { + let result = { + code: code, + stdout: stdout.join(""), + stderr: stderr.join(""), + }; + + if (!code) { + resolve(result); + return; + } + + let err = new Error(result.stderr); + Object.assign(err, result); + reject(err); + }); + }); +} + +main() + .then(function () { + process.exit(0); + }) + .catch(function (err) { + console.error("Fail:"); + console.error(err.stack || err); + process.exit(1); + });