Skip to content

Commit b6564ce

Browse files
committed
snippet reference
1 parent 541491b commit b6564ce

File tree

5 files changed

+1733
-46
lines changed

5 files changed

+1733
-46
lines changed

jest.config.ts

+203
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
/**
2+
* For a detailed explanation regarding each configuration property, visit:
3+
* https://jestjs.io/docs/configuration
4+
*/
5+
6+
import type { Config } from 'jest';
7+
8+
const config: Config = {
9+
// All imported modules in your tests should be mocked automatically
10+
// automock: false,
11+
12+
// Stop running tests after `n` failures
13+
// bail: 0,
14+
15+
// The directory where Jest should store its cached dependency information
16+
// cacheDirectory: "/private/var/folders/k0/1yjsmvw96q529jwsnf0whysm0000gn/T/jest_dx",
17+
18+
// Automatically clear mock calls, instances, contexts and results before every test
19+
// clearMocks: false,
20+
21+
// Indicates whether the coverage information should be collected while executing the test
22+
// collectCoverage: false,
23+
24+
// An array of glob patterns indicating a set of files for which coverage information should be collected
25+
// collectCoverageFrom: undefined,
26+
27+
// The directory where Jest should output its coverage files
28+
// coverageDirectory: undefined,
29+
30+
// An array of regexp pattern strings used to skip coverage collection
31+
// coveragePathIgnorePatterns: [
32+
// "/node_modules/"
33+
// ],
34+
35+
// Indicates which provider should be used to instrument code for coverage
36+
coverageProvider: 'babel',
37+
38+
// A list of reporter names that Jest uses when writing coverage reports
39+
// coverageReporters: [
40+
// "json",
41+
// "text",
42+
// "lcov",
43+
// "clover"
44+
// ],
45+
46+
// An object that configures minimum threshold enforcement for coverage results
47+
// coverageThreshold: undefined,
48+
49+
// A path to a custom dependency extractor
50+
// dependencyExtractor: undefined,
51+
52+
// Make calling deprecated APIs throw helpful error messages
53+
// errorOnDeprecated: false,
54+
55+
// The default configuration for fake timers
56+
// fakeTimers: {
57+
// "enableGlobally": false
58+
// },
59+
60+
// Force coverage collection from ignored files using an array of glob patterns
61+
// forceCoverageMatch: [],
62+
63+
// A path to a module which exports an async function that is triggered once before all test suites
64+
// globalSetup: undefined,
65+
66+
// A path to a module which exports an async function that is triggered once after all test suites
67+
// globalTeardown: undefined,
68+
69+
// A set of global variables that need to be available in all test environments
70+
// globals: {},
71+
72+
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73+
// maxWorkers: "50%",
74+
75+
// An array of directory names to be searched recursively up from the requiring module's location
76+
// moduleDirectories: [
77+
// "node_modules"
78+
// ],
79+
80+
// An array of file extensions your modules use
81+
moduleFileExtensions: [
82+
'js',
83+
'mjs',
84+
'cjs',
85+
'jsx',
86+
'ts',
87+
'tsx',
88+
'json',
89+
'node',
90+
],
91+
92+
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
93+
// moduleNameMapper: {},
94+
95+
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
96+
// modulePathIgnorePatterns: [],
97+
98+
// Activates notifications for test results
99+
// notify: false,
100+
101+
// An enum that specifies notification mode. Requires { notify: true }
102+
// notifyMode: "failure-change",
103+
104+
// A preset that is used as a base for Jest's configuration
105+
// preset: undefined,
106+
107+
// Run tests from one or more projects
108+
// projects: undefined,
109+
110+
// Use this configuration option to add custom reporters to Jest
111+
// reporters: undefined,
112+
113+
// Automatically reset mock state before every test
114+
// resetMocks: false,
115+
116+
// Reset the module registry before running each individual test
117+
// resetModules: false,
118+
119+
// A path to a custom resolver
120+
// resolver: undefined,
121+
122+
// Automatically restore mock state and implementation before every test
123+
// restoreMocks: false,
124+
125+
// The root directory that Jest should scan for tests and modules within
126+
// rootDir: undefined,
127+
128+
// A list of paths to directories that Jest should use to search for files in
129+
// roots: [
130+
// "<rootDir>"
131+
// ],
132+
133+
// Allows you to use a custom runner instead of Jest's default test runner
134+
// runner: "jest-runner",
135+
136+
// The paths to modules that run some code to configure or set up the testing environment before each test
137+
// setupFiles: ['jest-fetch-mock'],
138+
139+
// A list of paths to modules that run some code to configure or set up the testing framework before each test
140+
setupFilesAfterEnv: [],
141+
142+
// The number of seconds after which a test is considered as slow and reported as such in the results.
143+
// slowTestThreshold: 5,
144+
145+
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
146+
// snapshotSerializers: [],
147+
148+
// The test environment that will be used for testing
149+
testEnvironment: 'node',
150+
151+
// Options that will be passed to the testEnvironment
152+
// testEnvironmentOptions: {},
153+
154+
// Adds a location field to test results
155+
// testLocationInResults: false,
156+
157+
// The glob patterns Jest uses to detect test files
158+
// testMatch: [
159+
// "**/__tests__/**/*.[jt]s?(x)",
160+
// "**/?(*.)+(spec|test).[tj]s?(x)"
161+
// ],
162+
163+
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
164+
// testPathIgnorePatterns: [
165+
// "/node_modules/"
166+
// ],
167+
168+
// The regexp pattern or array of patterns that Jest uses to detect test files
169+
// testRegex: [],
170+
171+
// This option allows the use of a custom results processor
172+
// testResultsProcessor: undefined,
173+
174+
// This option allows use of a custom test runner
175+
// testRunner: "jest-circus/runner",
176+
177+
// A map from regular expressions to paths to transformers
178+
179+
transform: {
180+
// '\\.[jt]sx?$': ['babel-jest', { configFile: './babel.config.js' }],
181+
'^.+.[jt]sx?$': ['ts-jest', { isolatedModules: true }],
182+
},
183+
184+
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
185+
186+
transformIgnorePatterns: [
187+
'/node_modules/(?!(unist-util-visit|unist-util-is|unist-util-select|unist-util-parents|unist-util-visit-parents|unist-util-position|unist-util-remove-position|unist-util-generated)/)',
188+
],
189+
190+
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
191+
// unmockedModulePathPatterns: undefined,
192+
193+
// Indicates whether each individual test should be reported during the run
194+
// verbose: undefined,
195+
196+
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
197+
// watchPathIgnorePatterns: [],
198+
199+
// Whether to use watchman for file crawling
200+
// watchman: true,
201+
};
202+
203+
export default config;

package.json

+7-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"remark": "remark",
1616
"remark:once": "npm run remark -- --quiet --frail --use remark-validate-links docs/",
1717
"remark:watch": "npm run remark -- --quiet --frail --use remark-validate-links --watch docs/",
18+
"test": "jest",
1819
"typecheck": "tsc"
1920
},
2021
"dependencies": {
@@ -58,7 +59,9 @@
5859
},
5960
"devDependencies": {
6061
"@docusaurus/module-type-aliases": "^3.5.2",
62+
"@jest/globals": "^29.7.0",
6163
"@tsconfig/docusaurus": "^2.0.3",
64+
"@types/jest": "^29.5.14",
6265
"@typescript-eslint/eslint-plugin": "^8.11.0",
6366
"concurrently": "^8.2.1",
6467
"eslint": "^8.0.1",
@@ -67,10 +70,13 @@
6770
"eslint-plugin-n": "^15.0.0",
6871
"eslint-plugin-promise": "^6.0.0",
6972
"eslint-plugin-react": "7.32.2",
73+
"jest": "^29.7.0",
7074
"node-jq": "6.0.1",
7175
"remark-cli": "^12.0.0",
7276
"remark-validate-links": "^12.1.1",
73-
"typescript": "*"
77+
"ts-jest": "^29.2.5",
78+
"ts-node": "^10.9.2",
79+
"typescript": "^5.7.2"
7480
},
7581
"browserslist": {
7682
"production": [

src/plugins/code-reference.js

+89-14
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,100 @@ const getUrl = (nodeValue) => {
1111
return url.replace(githubReplace, '$1raw.githubusercontent.com/$3/$4');
1212
};
1313

14-
const getLines = (url) => {
14+
/**
15+
* try parse int
16+
* @param {string} strNumber
17+
* @returns number | null
18+
*/
19+
const tryParseInt = (strNumber) => {
20+
try {
21+
const number = parseInt(strNumber);
22+
if (isNaN(number)) {
23+
return null;
24+
}
25+
return number;
26+
} catch (e) {
27+
console.error(e);
28+
return null;
29+
}
30+
};
31+
32+
/**
33+
* get start line and end line for a snippet from a url
34+
* @param {string} url provided url
35+
* @returns {null | [string, string]}
36+
*/
37+
export const getLines = (url) => {
1538
const lines = url.split('#')[1];
16-
if (!lines) {
39+
if (lines == null || lines === '') {
40+
return null;
41+
}
42+
if (lines.match(/^L\d+$/) == null && lines.match(/^L\d+-L\d+$/) == null) {
1743
return null;
1844
}
1945

2046
const [start, end] = lines
2147
.split('-')
2248
.map((line) => line.replace(/L(\d+)/, '$1'));
2349

24-
return [start, end];
50+
const startNum = tryParseInt(start);
51+
const endNum = tryParseInt(end);
52+
53+
return [startNum, endNum ?? startNum];
54+
};
55+
56+
export const getSnippetName = (url) => {
57+
const snippet = url.split('#')[1];
58+
if (snippet == null || snippet === '') {
59+
return null;
60+
}
61+
if (snippet.match(/^L\d+$/) != null || snippet.match(/^L\d+-L\d+$/) != null) {
62+
return null;
63+
}
64+
return snippet;
65+
};
66+
67+
export const getCodeSnippet = ({ code, lines, snippetName }) => {
68+
if (lines != null) {
69+
const codeLines = code
70+
.split('\n')
71+
.slice(lines[0] - 1, lines[1])
72+
.join('\n');
73+
return codeLines;
74+
}
75+
/**
76+
* based on https://github.com/search?q=%22%5BSTART+snippet_name%5D%22&type=code
77+
*/
78+
if (snippetName != null) {
79+
/** @type [string] */
80+
const codeArray = code.split('\n');
81+
const snippetStart = `[START ${snippetName}]`;
82+
const snippetEnd = `[END ${snippetName}]`;
83+
let startLine = null;
84+
let endLine = null;
85+
86+
for (let i = 0; i < codeArray.length; i++) {
87+
const line = codeArray[i];
88+
if (line.includes(snippetStart)) {
89+
startLine = i + 1;
90+
break;
91+
}
92+
}
93+
for (let i = 0; i < codeArray.length; i++) {
94+
const line = codeArray[i];
95+
96+
if (line.includes(snippetEnd)) {
97+
endLine = i;
98+
break;
99+
}
100+
}
101+
if (startLine != null && endLine != null) {
102+
const codeLines = codeArray.slice(startLine, endLine).join('\n');
103+
return codeLines;
104+
}
105+
return code;
106+
}
107+
return code;
25108
};
26109

27110
const plugin = () => {
@@ -37,24 +120,16 @@ const plugin = () => {
37120
const lines = getLines(url);
38121

39122
const fetchPromise = fetch(url)
40-
.then((res) => {
123+
.then(async (res) => {
41124
if (!res.ok) {
42125
throw new Error(
43126
`Failed to fetch code from ${url}: ${res.statusText}`,
44127
);
45128
}
46-
return res.text();
129+
return await res.text();
47130
})
48131
.then((code) => {
49-
if (lines) {
50-
const codeLines = code
51-
.split('\n')
52-
.slice(lines[0] - 1, lines[1])
53-
.join('\n');
54-
node.value = codeLines;
55-
} else {
56-
node.value = code;
57-
}
132+
node.value = getCodeSnippet({ code, lines, snippetName });
58133
})
59134
.catch((err) => {
60135
console.error(err);

0 commit comments

Comments
 (0)