Skip to content

Commit 181dac5

Browse files
feat: use rollup
1 parent 4855ceb commit 181dac5

11 files changed

+129
-137
lines changed

.eslintrc

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@
110110
"import/order": [2, {
111111
"groups": ["type", "builtin", "external", "internal", "parent", "sibling", "index", "object"],
112112
"alphabetize": { "order": "asc", "caseInsensitive": true }
113-
}]
113+
}],
114+
"@typescript-eslint/no-non-null-assertion": "off"
114115
}
115-
}
116+
}

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/.idea
22
/node_modules
33
/coverage
4-
/build
4+
/dist
55
.eslintcache

package.json

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,19 @@
2929
"url": "https://technote.space"
3030
}
3131
],
32-
"main": "build/index.js",
33-
"types": "build/index.d.ts",
32+
"type": "module",
33+
"exports": "./dist/index.mjs",
34+
"main": "dist/index.mjs",
3435
"files": [
3536
"build"
3637
],
3738
"scripts": {
38-
"build": "rm -rf ./build && tsc",
39+
"build": "tsc --emitDeclarationOnly && rollup -c",
3940
"cover": "vitest run --coverage",
4041
"lint": "eslint 'src/**/*.ts' '__tests__/**/*.ts' --cache",
4142
"lint:fix": "eslint --fix 'src/**/*.ts' '__tests__/**/*.ts'",
42-
"test": "yarn lint && yarn cover",
43+
"test": "yarn lint && yarn typecheck && yarn cover",
44+
"typecheck": "tsc --noEmit",
4345
"update": "npm_config_yes=true npx npm-check-updates -u --timeout 100000 && yarn install && yarn upgrade && yarn audit"
4446
},
4547
"dependencies": {
@@ -51,6 +53,8 @@
5153
"devDependencies": {
5254
"@commitlint/cli": "^17.0.2",
5355
"@commitlint/config-conventional": "^17.0.2",
56+
"@rollup/plugin-typescript": "^8.3.3",
57+
"@sindresorhus/tsconfig": "^3.0.1",
5458
"@textlint/ast-node-types": "^12.1.1",
5559
"@types/node": "^18.0.0",
5660
"@typescript-eslint/eslint-plugin": "^5.29.0",
@@ -60,6 +64,7 @@
6064
"eslint-plugin-import": "^2.26.0",
6165
"husky": "^8.0.1",
6266
"lint-staged": "^13.0.2",
67+
"rollup": "^2.75.7",
6368
"typescript": "^4.7.4",
6469
"vitest": "^0.15.2"
6570
},

rollup.config.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import pluginTypescript from '@rollup/plugin-typescript';
2+
3+
const common = {
4+
input: 'src/index.ts',
5+
plugins: [
6+
pluginTypescript(),
7+
],
8+
external: [
9+
'@technote-space/anchor-markdown-header',
10+
'@textlint/markdown-to-ast',
11+
'htmlparser2',
12+
'update-section',
13+
],
14+
};
15+
16+
export default [
17+
{
18+
...common,
19+
output: {
20+
file: 'dist/index.cjs',
21+
format: 'cjs',
22+
},
23+
},
24+
{
25+
...common,
26+
output: {
27+
file: 'dist/index.mjs',
28+
format: 'es',
29+
},
30+
},
31+
];

src/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
export { findMarkdownFiles } from './lib/file';
2-
export { transform } from './lib/transform';
1+
export { findMarkdownFiles } from './lib/file.js';
2+
export { transform } from './lib/transform.js';
33
export {
44
OPENING_COMMENT,
55
CLOSING_COMMENT,
@@ -11,4 +11,4 @@ export {
1111
DEFAULT_CUSTOM_TEMPLATE,
1212
DEFAULT_ITEM_TEMPLATE,
1313
DEFAULT_SEPARATOR,
14-
} from './constant';
14+
} from './constant.js';

src/lib/file.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import type { FileInfo, FileAndDirs } from '../types';
1+
import type { FileInfo, FileAndDirs } from '../types.js';
22
import fs from 'fs';
33
import path from 'path';
4-
import { MARKDOWN_EXTENSIONS, IGNORED_DIRS } from '..';
4+
import { MARKDOWN_EXTENSIONS, IGNORED_DIRS } from '../constant.js';
55

66
const separateFilesAndDirs = (fileInfos: Array<FileInfo>): FileAndDirs => ({
77
directories: fileInfos.filter(info => info.stat.isDirectory() && !IGNORED_DIRS.includes(info.name)),

src/lib/get-html-headers.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
1-
import type { HeaderData, Header } from '../types';
1+
import type { HeaderData, Header } from '../types.js';
22
import * as md from '@textlint/markdown-to-ast';
33
import * as htmlparser from 'htmlparser2';
44

5-
const addLinenos = (lines: Array<string>, headers: Array<HeaderData>): Array<Omit<Header, 'rank'> & HeaderData> => {
5+
const addLineNumbers = (lines: Array<string>, headers: Array<HeaderData>): Array<Omit<Header, 'rank'> & HeaderData> => {
66
let current = 0;
77
return headers.map(header => {
8-
for (let lineno = current; lineno < lines.length; lineno++) {
9-
const line = lines[lineno];
10-
if (new RegExp(header.text[0]).test(line)) {
11-
current = lineno;
8+
for (let lineNumber = current; lineNumber < lines.length; lineNumber++) {
9+
const line = lines[lineNumber]!;
10+
if (new RegExp(header.text[0]!).test(line)) {
11+
current = lineNumber;
1212
return {
1313
...header,
14-
line: lineno,
14+
line: lineNumber,
1515
name: header.text.join(''),
1616
};
1717
}
@@ -82,5 +82,5 @@ export const getHtmlHeaders = (lines: Array<string>, maxHeaderLevel: number): Ar
8282
parser.write(source);
8383
parser.end();
8484

85-
return rankify(addLinenos(lines, headers), maxHeaderLevel);
85+
return rankify(addLineNumbers(lines, headers), maxHeaderLevel);
8686
};

src/lib/params.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { SectionInfo, TransformOptions } from '../types';
1+
import type { SectionInfo, TransformOptions } from '../types.js';
22

33
const getBoolValue = (input: string): boolean => !['false', '0', '', 'no', 'n'].includes(input.trim().toLowerCase());
44
const converter = {
@@ -25,25 +25,25 @@ export const getStartSection = (lines: Array<string>, info: SectionInfo, matches
2525

2626
// eslint-disable-next-line no-magic-numbers
2727
for (let index = info.startIdx + 1; index < info.endIdx; ++index) {
28-
if (!/-->$/.test(lines[index].trim())) {
28+
if (!/-->$/.test(lines[index]!.trim())) {
2929
return lines.slice(info.startIdx, index);
3030
}
3131
}
3232

3333
// consider empty toc with params
34-
if (info.endIdx < lines.length && matchesEnd(lines[info.endIdx])) {
34+
if (info.endIdx < lines.length && matchesEnd(lines[info.endIdx]!)) {
3535
return lines.slice(info.startIdx, info.endIdx);
3636
}
3737

38-
return [lines[info.startIdx]];
38+
return [lines[info.startIdx]!];
3939
};
4040

4141
export const extractParams = (section: string): TransformOptions => Object.assign({}, ...(section.match(/\s+param::(\w+)::(.*?)::/g)?.map(
4242
target => target.match(/param::(\w+)::(.*?)::/),
4343
).filter(
44-
(items): items is Array<string> => items !== null && items[1] in converter,
44+
(items): items is Array<string> => items !== null && items[1]! in converter,
4545
).map(
46-
items => ({ [items[1]]: converter[items[1]](items[2]) }),
46+
items => ({ [items[1]!]: converter[items[1]!](items[2]) }),
4747
) ?? []));
4848

4949
export const getParamsSection = (options: TransformOptions): string => {

src/lib/transform.ts

Lines changed: 21 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { TransformOptions, Header, HeaderWithRepetition, HeaderWithAnchor, SectionInfo, TransformResult } from '../types';
1+
import type { TransformOptions, Header, HeaderWithRepetition, HeaderWithAnchor, SectionInfo, TransformResult } from '../types.js';
22
import type { TxtNode } from '@textlint/ast-node-types';
33
import { anchor, getUrlHash } from '@technote-space/anchor-markdown-header';
44
import * as md from '@textlint/markdown-to-ast';
@@ -12,10 +12,10 @@ import {
1212
DEFAULT_CUSTOM_TEMPLATE,
1313
DEFAULT_ITEM_TEMPLATE,
1414
DEFAULT_SEPARATOR,
15-
} from '..';
16-
import { getHtmlHeaders } from './get-html-headers';
17-
import { getStartSection, extractParams, getParamsSection } from './params';
18-
import { replaceVariables } from './utils';
15+
} from '../constant.js';
16+
import { getHtmlHeaders } from './get-html-headers.js';
17+
import { getStartSection, extractParams, getParamsSection } from './params.js';
18+
import { replaceVariables } from './utils.js';
1919

2020
const getTargetComments = (checkComments: Array<string>, defaultComments: string): Array<string> => {
2121
if (checkComments.length) {
@@ -105,12 +105,12 @@ export const getTitle = (title: string | undefined, lines: Array<string>, info:
105105
return title;
106106
}
107107

108-
if (info.hasStart && lines[info.startIdx + startSection.length].trim()) {
109-
if (matchesEnd(lines[info.startIdx + startSection.length])) {
108+
if (info.hasStart && lines[info.startIdx + startSection.length]!.trim()) {
109+
if (matchesEnd(lines[info.startIdx + startSection.length]!)) {
110110
return DEFAULT_TITLE;
111111
}
112112

113-
return lines[info.startIdx + startSection.length].trim();
113+
return lines[info.startIdx + startSection.length]!.trim();
114114
}
115115

116116
return DEFAULT_TITLE;
@@ -190,52 +190,34 @@ export const transform = (
190190

191191
const startSection = getStartSection(lines, info, matchesEnd(options.checkClosingComments));
192192
const extractedOptions = extractParams(startSection.join(' '));
193-
const
194-
{
195-
mode,
196-
moduleName,
197-
maxHeaderLevel,
198-
title,
199-
isNotitle,
200-
isFolding,
201-
entryPrefix,
202-
processAll,
203-
updateOnly,
204-
openingComment,
205-
closingComment,
206-
isCustomMode,
207-
customTemplate,
208-
itemTemplate,
209-
separator,
210-
footer,
211-
} = { ...options, ...extractedOptions };
212-
213-
if (!info.hasStart && updateOnly) {
193+
const _option = { ...options, ...extractedOptions };
194+
195+
if (!info.hasStart && _option.updateOnly) {
214196
return getResult({ transformed: false, reason: 'update only' });
215197
}
216198

217-
const _mode = mode || 'github.com';
218-
const _entryPrefix = entryPrefix || '-';
199+
const _mode = _option.mode || 'github.com';
200+
const _entryPrefix = _option.entryPrefix || '-';
219201

220202
// only limit *HTML* headings by default
221203
// eslint-disable-next-line no-magic-numbers
222-
const maxHeaderLevelHtml = maxHeaderLevel || 4;
204+
const maxHeaderLevelHtml = _option.maxHeaderLevel || 4;
223205

224206
// eslint-disable-next-line no-magic-numbers
225207
const currentToc = info.hasStart && lines.slice(info.startIdx, info.endIdx + 1).join('\n');
226-
const linesToToc = getLinesToToc(lines, currentToc, info, processAll);
227-
const headers = getMarkdownHeaders(linesToToc, maxHeaderLevel).concat(getHtmlHeaders(linesToToc, maxHeaderLevelHtml));
208+
const linesToToc = getLinesToToc(lines, currentToc, info, _option.processAll);
209+
const headers = getMarkdownHeaders(linesToToc, _option.maxHeaderLevel).concat(getHtmlHeaders(linesToToc, maxHeaderLevelHtml));
228210
headers.sort((header1, header2) => header1.line - header2.line);
229211

230-
const allHeaders = countHeaders(headers, _mode, moduleName);
212+
const allHeaders = countHeaders(headers, _mode, _option.moduleName);
231213
const lowestRank = Math.min(...allHeaders.map(header => header.rank));
232-
const linkedHeaders = allHeaders.map(header => addAnchor(_mode, moduleName, header));
233-
const inferredTitle = linkedHeaders.length ? determineTitle(title, isNotitle, isFolding, lines, info, startSection, matchesEnd(options.checkClosingComments)) : '';
214+
const linkedHeaders = allHeaders.map(header => addAnchor(_mode, _option.moduleName, header));
215+
const inferredTitle = linkedHeaders.length ? determineTitle(_option.title, _option.isNotitle, _option.isFolding, lines, info, startSection, matchesEnd(options.checkClosingComments)) : '';
234216

235217
// 4 spaces required for proper indention on Bitbucket and GitLab
236218
const indentation = (_mode === 'bitbucket.org' || _mode === 'gitlab.com') ? ' ' : ' ';
237-
const toc = buildToc(isCustomMode, inferredTitle, linkedHeaders, lowestRank, customTemplate, itemTemplate, separator, indentation, _entryPrefix, footer);
238-
const wrappedToc = (openingComment ?? OPENING_COMMENT) + getParamsSection(extractedOptions) + '\n' + wrapToc(toc, inferredTitle, isFolding) + '\n' + (closingComment ?? CLOSING_COMMENT);
219+
const toc = buildToc(_option.isCustomMode, inferredTitle, linkedHeaders, lowestRank, _option.customTemplate, _option.itemTemplate, _option.separator, indentation, _entryPrefix, _option.footer);
220+
const wrappedToc = (_option.openingComment ?? OPENING_COMMENT) + getParamsSection(extractedOptions) + '\n' + wrapToc(toc, inferredTitle, _option.isFolding) + '\n' + (_option.closingComment ?? CLOSING_COMMENT);
239221
if (currentToc === wrappedToc) {
240222
return getResult({ transformed: false, reason: 'not updated' });
241223
}

tsconfig.json

Lines changed: 10 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,15 @@
11
{
2+
"extends": "@sindresorhus/tsconfig",
23
"compilerOptions": {
3-
/* Basic Options */
4-
// "incremental": true, /* Enable incremental compilation */
5-
"target": "es6",
6-
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
7-
"module": "commonjs",
8-
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
9-
// "allowJs": true, /* Allow javascript files to be compiled. */
10-
// "checkJs": true, /* Report errors in .js files. */
11-
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
12-
/* Generates corresponding '.d.ts' file. */
13-
"declaration": true,
14-
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
15-
// "sourceMap": true, /* Generates corresponding '.map' file. */
16-
// "outFile": "./", /* Concatenate and emit output to single file. */
17-
"outDir": "./build",
18-
/* Redirect output structure to the directory. */
19-
"rootDir": "./src",
20-
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
21-
// "composite": true, /* Enable project compilation */
22-
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
23-
// "removeComments": true, /* Do not emit comments to output. */
24-
// "noEmit": true, /* Do not emit outputs. */
25-
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
26-
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
27-
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
28-
29-
/* Strict Type-Checking Options */
30-
"strict": true,
31-
/* Enable all strict type-checking options. */
32-
"noImplicitAny": false,
33-
/* Raise error on expressions and declarations with an implied 'any' type. */
34-
// "strictNullChecks": true, /* Enable strict null checks. */
35-
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
36-
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
37-
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
38-
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
39-
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
40-
41-
/* Additional Checks */
42-
// "noUnusedLocals": true, /* Report errors on unused locals. */
43-
// "noUnusedParameters": true, /* Report errors on unused parameters. */
44-
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
45-
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
46-
47-
/* Module Resolution Options */
48-
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
49-
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
50-
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
51-
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
52-
// "typeRoots": [], /* List of folders to include type definitions from. */
53-
// "types": [], /* Type declaration files to be included in compilation. */
54-
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
55-
"esModuleInterop": true
56-
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
57-
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
58-
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
59-
60-
/* Source Map Options */
61-
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
62-
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
63-
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
64-
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
65-
66-
/* Experimental Options */
67-
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
68-
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
4+
"outDir": "dist",
5+
"target": "es2020",
6+
"lib": [
7+
"es2020"
8+
],
9+
"noPropertyAccessFromIndexSignature": false,
10+
"noImplicitAny": false
6911
},
70-
"exclude": [
71-
"node_modules",
72-
"__tests__"
12+
"include": [
13+
"src"
7314
]
7415
}

0 commit comments

Comments
 (0)