repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
rsdoctor | github_2023 | web-infra-dev | typescript | Range.setStartPosition | setStartPosition(startLineNumber: number, startColumn: number) {
return new Range(
startLineNumber,
startColumn,
this.endLineNumber,
this.endColumn,
);
} | /**
* Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L358-L365 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.collapseToStart | collapseToStart() {
return Range.collapseToStart(this);
} | /**
* Create a new empty range using this range's start position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L369-L371 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.collapseToStart | static collapseToStart(range: Range) {
return new Range(
range.startLineNumber,
range.startColumn,
range.startLineNumber,
range.startColumn,
);
} | /**
* Create a new empty range using this range's start position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L375-L382 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.collapseToEnd | collapseToEnd() {
return Range.collapseToEnd(this);
} | /**
* Create a new empty range using this range's end position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L386-L388 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.collapseToEnd | static collapseToEnd(range: Range) {
return new Range(
range.endLineNumber,
range.endColumn,
range.endLineNumber,
range.endColumn,
);
} | /**
* Create a new empty range using this range's end position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L392-L399 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.delta | delta(lineCount: number) {
return new Range(
this.startLineNumber + lineCount,
this.startColumn,
this.endLineNumber + lineCount,
this.endColumn,
);
} | /**
* Moves the range by the given amount of lines.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L403-L410 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.fromPositions | static fromPositions(
start: {
lineNumber: number;
column: number;
},
end = start,
) {
return new Range(
start.lineNumber,
start.column,
end.lineNumber,
end.column,
);
} | // --- | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L412-L425 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.isIRange | static isIRange(obj: Range) {
return (
obj &&
typeof obj.startLineNumber === 'number' &&
typeof obj.startColumn === 'number' &&
typeof obj.endLineNumber === 'number' &&
typeof obj.endColumn === 'number'
);
} | /**
* Test if `obj` is an `IRange`.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L440-L448 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.areIntersectingOrTouching | static areIntersectingOrTouching(a: Range, b: Range) {
// Check if `a` is before `b`
if (
a.endLineNumber < b.startLineNumber ||
(a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn)
) {
return false;
}
// Check if `b` is before `a`
if (
b.endLineNumber < a.startLineNumber ||
(b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn)
) {
return false;
}
// These ranges must intersect
return true;
} | /**
* Test if the two ranges are touching in any way.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L452-L469 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.areIntersecting | static areIntersecting(a: Range, b: Range) {
// Check if `a` is before `b`
if (
a.endLineNumber < b.startLineNumber ||
(a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn)
) {
return false;
}
// Check if `b` is before `a`
if (
b.endLineNumber < a.startLineNumber ||
(b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn)
) {
return false;
}
// These ranges must intersect
return true;
} | /**
* Test if the two ranges are intersecting. If the ranges are touching it returns true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L473-L490 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.compareRangesUsingStarts | static compareRangesUsingStarts(a: Range, b: Range) {
if (a && b) {
const aStartLineNumber = a.startLineNumber | 0;
const bStartLineNumber = b.startLineNumber | 0;
if (aStartLineNumber === bStartLineNumber) {
const aStartColumn = a.startColumn | 0;
const bStartColumn = b.startColumn | 0;
if (aStartColumn === bStartColumn) {
const aEndLineNumber = a.endLineNumber | 0;
const bEndLineNumber = b.endLineNumber | 0;
if (aEndLineNumber === bEndLineNumber) {
const aEndColumn = a.endColumn | 0;
const bEndColumn = b.endColumn | 0;
return aEndColumn - bEndColumn;
}
return aEndLineNumber - bEndLineNumber;
}
return aStartColumn - bStartColumn;
}
return aStartLineNumber - bStartLineNumber;
}
const aExists = a ? 1 : 0;
const bExists = b ? 1 : 0;
return aExists - bExists;
} | /**
* A function that compares ranges, useful for sorting ranges
* It will first compare ranges on the startPosition and then on the endPosition
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L495-L519 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.compareRangesUsingEnds | static compareRangesUsingEnds(
a: {
endLineNumber: number;
endColumn: number;
startLineNumber: number;
startColumn: number;
},
b: {
endLineNumber: number;
endColumn: number;
startLineNumber: number;
startColumn: number;
},
) {
if (a.endLineNumber === b.endLineNumber) {
if (a.endColumn === b.endColumn) {
if (a.startLineNumber === b.startLineNumber) {
return a.startColumn - b.startColumn;
}
return a.startLineNumber - b.startLineNumber;
}
return a.endColumn - b.endColumn;
}
return a.endLineNumber - b.endLineNumber;
} | /**
* A function that compares ranges, useful for sorting ranges
* It will first compare ranges on the endPosition and then on the startPosition
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L524-L548 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.spansMultipleLines | static spansMultipleLines(range: Range) {
return range.endLineNumber > range.startLineNumber;
} | /**
* Test if the range spans multiple lines.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L552-L554 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.with | with(newLineNumber = this.lineNumber, newColumn = this.column) {
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
}
return new Position(newLineNumber, newColumn);
} | /**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L581-L586 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.delta | delta(deltaLineNumber = 0, deltaColumn = 0) {
return this.with(
this.lineNumber + deltaLineNumber,
this.column + deltaColumn,
);
} | /**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L593-L598 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.equals | equals(other: any) {
return Position.equals(this, other);
} | /**
* Test if this position equals other position
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L602-L604 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.equals | static equals(
a: any,
b: {
lineNumber: any;
column: any;
},
) {
if (!a && !b) {
return true;
}
return !!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column;
} | /**
* Test if position `a` equals position `b`
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L608-L619 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.isBefore | isBefore(other: any) {
return Position.isBefore(this, other);
} | /**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L624-L626 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.isBefore | static isBefore(
a: any,
b: {
lineNumber: number;
column: number;
},
) {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
} | /**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L631-L645 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.isBeforeOrEqual | isBeforeOrEqual(other: any) {
return Position.isBeforeOrEqual(this, other);
} | /**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L650-L652 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.isBeforeOrEqual | static isBeforeOrEqual(
a: any,
b: {
lineNumber: number;
column: number;
},
) {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column <= b.column;
} | /**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L657-L671 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.compare | static compare(
a: {
lineNumber: number;
column: number;
},
b: {
lineNumber: number;
column: number;
},
) {
const aLineNumber = a.lineNumber | 0;
const bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
const aColumn = a.column | 0;
const bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
} | /**
* A function that compares positions, useful for sorting
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L675-L693 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.clone | clone() {
return new Position(this.lineNumber, this.column);
} | /**
* Clone this position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L697-L699 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.toString | toString() {
return `(${this.lineNumber},${this.column})`;
} | /**
* Convert to a human-readable representation.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L703-L705 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.lift | static lift(pos: { lineNumber: any; column: any }) {
return new Position(pos.lineNumber, pos.column);
} | /**
* Create a `Position` from an `IPosition`.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L710-L712 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Position.isIPosition | static isIPosition(obj: { lineNumber: any; column: any }) {
return (
obj &&
typeof obj.lineNumber === 'number' &&
typeof obj.column === 'number'
);
} | /**
* Test if `obj` is an `IPosition`.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L716-L722 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | LocalServerDataLoader.onDataUpdate | public onDataUpdate<T extends SDK.ServerAPI.API | SDK.ServerAPI.APIExtends>(
api: T,
fn: (response: SDK.ServerAPI.SocketResponseType<T>) => void,
) {
if (!this.events.has(api)) {
this.events.set(api, new Set());
}
if (this.events.get(api)!.has(fn)) {
return;
}
this.events.get(api)!.add(fn);
getSocket().on(api as string, fn);
} | /**
* add event listener when received data from server.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/utils/data/local.ts#L106-L120 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | getBundleRuntime | function getBundleRuntime(
content: string,
modulesLocations: Record<string, { start: number; end: number }> | null,
) {
const sortedLocations = Object.values(modulesLocations || {}).sort(
(a, b) => a.start - b.start,
);
let result = '';
let lastIndex = 0;
for (const { start, end } of sortedLocations) {
result += content.slice(lastIndex, start);
lastIndex = end;
}
return result + content.slice(lastIndex, content.length);
} | /**
* Returns bundle source except modules
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/core/src/build-utils/build/utils/parseBundle.ts#L274-L291 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | getStringBetween | function getStringBetween(
raw: string,
position: number,
start: RegExp,
end: RegExp,
) {
try {
const matchStart = raw.match(start);
const startFlagIndex = matchStart?.length
? raw.indexOf(matchStart[0], position)
: -1;
if (startFlagIndex === -1 || !matchStart?.length) {
return {
result: null,
remain: position,
};
}
const startTagLength = matchStart[0].length;
const matchEnd = raw.match(end);
const endFlagIndex = matchEnd?.length
? raw.indexOf(matchEnd[0], startFlagIndex + startTagLength)
: -1;
if (endFlagIndex === -1 || !matchEnd?.length) {
return {
result: null,
remain: position,
};
}
let innerContent = raw
.slice(startFlagIndex + startTagLength, endFlagIndex)
.trim();
if (innerContent.endsWith(',')) {
innerContent = innerContent.slice(0, -1);
}
return {
result: innerContent,
remain: matchEnd?.length
? endFlagIndex + matchEnd[0].length
: endFlagIndex,
loc: {
start: startFlagIndex + startTagLength,
end: endFlagIndex,
},
};
} catch (e: any) {
debug(() => e);
return {
result: null,
remain: position,
};
}
} | /**
*
* @description The purpose of this function is to obtain the code in the start and end tags of Rsdoctor.
*
* @param {string} raw
* @param {number} position
* @param {RegExp} start
* @param {RegExp} end
* @return {*}
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/core/src/build-utils/build/utils/parseBundle.ts#L526-L579 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | getModulesInfos | async function getModulesInfos(
compiler: Plugin.BaseCompiler,
moduleGraph: SDK.ModuleGraphInstance,
chunkGraph: SDK.ChunkGraphInstance,
parseBundle: boolean,
) {
if (!moduleGraph) {
return;
}
try {
const parsedModulesData =
(await ChunksBuildUtils.getAssetsModulesData(
moduleGraph,
chunkGraph,
compiler.outputPath,
parseBundle,
)) || {};
ChunksUtils.transformAssetsModulesData(parsedModulesData, moduleGraph);
} catch (e) {}
} | /**
* @protected
* @description This function to get module parsed code and size;
* @param {Compiler} compiler
* @param {StatsCompilation} stats
* @param {ModuleGraph} moduleGraph
* @return {*}
* @memberof RsdoctorWebpackPlugin
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/core/src/inner-plugins/plugins/ensureModulesChunkGraph.ts#L130-L149 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | wrapper | const wrapper =
(callback: Function) =>
(loaderContext: LoaderContext<unknown>, module: NormalModule) => {
// loaders which are already intercepted in afterPlugins hook by Rsdoctor.
const proxyLoaders = module?.loaders || loaderContext?.loaders || [];
// return origin loaders not doctor internal loaders
const originLoaders = proxyLoaders.map((loader) => {
const opts: ProxyLoaderOptions = loader.options || {};
if (opts[Loader.LoaderInternalPropertyName]) {
return {
...loader,
loader: opts[Loader.LoaderInternalPropertyName].loader,
options: omit(opts, Loader.LoaderInternalPropertyName),
};
}
return loader;
});
const newLoaders = cloneDeep(originLoaders);
if (
typeof compiler.options.cache === 'object' &&
'version' in compiler.options.cache &&
typeof compiler.options.cache.version === 'string' &&
compiler.options.cache.version.indexOf('next/dist/build') > -1
) {
callback(loaderContext, module || {});
} else {
const proxyModule = new Proxy(module || {}, {
get(target, p, receiver) {
if (p === 'loaders') return newLoaders;
return Reflect.get(target, p, receiver);
},
set(target, p, newValue, receiver) {
const _newValue = cloneDeep(newValue);
if (p === 'loaders') {
if (Array.isArray(_newValue)) {
newLoaders.length = 0;
_newValue.forEach((e) => {
newLoaders.push(e);
});
}
}
return Reflect.set(target, p, _newValue, receiver);
},
deleteProperty(target, p) {
return Reflect.deleteProperty(target, p);
},
});
callback(loaderContext, proxyModule);
}
// loaders are overwrite when originLoader is not same with newLoaders
if (!isEqual(originLoaders, newLoaders)) {
// intercept new loaders
const rules = this.getInterceptRules(
compiler,
newLoaders.map((e) => {
return {
loader: e.loader,
options: e.options,
};
}),
);
module.loaders = rules.map((e, i) => {
return {
...newLoaders[i],
loader: e.loader!,
options: e.options,
};
});
}
}; | /**
* some plugin will overwrite and validate loader or loader options in [normalModuleLoader](https://webpack.js.org/api/compilation-hooks/#normalmoduleloader) hook.
* such as (@arco-plugins/webpack-react)[https://github.com/arco-design/arco-plugins/blob/main/packages/plugin-webpack-react/src/arco-design-plugin/utils/index.ts#L134]
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/core/src/inner-plugins/plugins/loader.ts#L53-L128 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | ChunkGraph.toData | toData(type: SDK.ToDataType): SDK.ChunkGraphData {
return {
assets: Array.from(this._assetMap.values()).map((item) =>
item.toData(type),
),
chunks: Array.from(this._chunkMap.values()).map((item) => item.toData()),
entrypoints: Array.from(this._entrypointMap.values()).map((item) =>
item.toData(),
),
};
} | /** output the chunk graph data */ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/graph/src/graph/chunk-graph/graph.ts#L51-L61 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | resolveFixture | const resolveFixture = (...paths: string[]) => {
return path.resolve(__dirname, 'fixture', ...paths);
}; | // TODO: simplify the module-graph-basic.json data size. | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/graph/tests/module-graph.test.ts#L6-L8 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | RsdoctorRspackPlugin.ensureModulesChunksGraphApplied | public ensureModulesChunksGraphApplied(
compiler: Plugin.BaseCompilerType<'rspack'>,
) {
ensureModulesChunksGraphFn(compiler, this);
} | /**
* @description Generate ModuleGraph and ChunkGraph from stats and webpack module apis;
* @param {Compiler} compiler
* @return {*}
* @memberof RsdoctorWebpackPlugin
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/rspack-plugin/src/plugin.ts#L173-L177 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | inlineScripts | function inlineScripts(basePath: string, scripts: string[]): string {
return scripts
.map((src) => {
const scriptPath = path.resolve(basePath, src);
try {
const scriptContent = fse.readFileSync(scriptPath, 'utf-8');
return `<script>${scriptContent}</script>`;
} catch (error) {
console.error(`Could not read script at ${scriptPath}:`, error);
return '';
}
})
.join('');
} | // Helper function to inline JavaScript files | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/sdk/src/sdk/sdk/index.ts#L530-L543 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | inlineCss | function inlineCss(basePath: string, cssFiles: string[]): string {
return cssFiles
.map((href) => {
const cssPath = path.resolve(basePath, href);
try {
const cssContent = fse.readFileSync(cssPath, 'utf-8');
return `<style>${cssContent}</style>`;
} catch (error) {
console.error(`Could not read CSS at ${cssPath}:`, error);
return '';
}
})
.join('');
} | // Helper function to inline CSS files | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/sdk/src/sdk/sdk/index.ts#L546-L559 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | FileSharding.createVirtualShardingFiles | public createVirtualShardingFiles(ext = '', index = 0) {
const bf = Buffer.from(this.content, this.encoding);
const res: Buffer[] = [];
const threshold = this.limitBytes;
let tmpBytes = 0;
while (bf.byteLength > tmpBytes) {
res.push(bf.subarray(tmpBytes, tmpBytes + threshold));
tmpBytes += threshold;
}
return res.map((e, i) => ({ filename: `${i + index}${ext}`, content: e }));
} | /**
* @param ext the extension name of the output file (must starts with ".")
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/utils/src/build/file/sharding.ts#L15-L27 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | FileSharding.writeStringToFolder | public async writeStringToFolder(folder: string, ext = '', index?: number) {
const dist = path.resolve(folder);
await fse.ensureDir(dist);
const res = this.createVirtualShardingFiles(ext, index);
await Promise.all(
res.map(
(e) =>
new Promise((resolve, reject) => {
const stream = fs.createWriteStream(
path.join(dist, e.filename),
this.encoding,
);
stream.end(e.content);
stream.once('close', () => resolve(undefined));
stream.once('error', (err) => reject(err));
}),
),
);
return res;
} | /**
* @param folder absolute path of folder which used to save string sharding files.
* @param ext the extension name of the output file (must starts with ".")
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/utils/src/build/file/sharding.ts#L33-L54 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | DevToolError.toJSON | toJSON() {
return {
message: this.toString(),
name: this.name,
stack: this.stack,
};
} | /**
* for json stringify
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/utils/src/error/error.ts#L240-L246 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Document.createFinder | private createFinder() {
const find = new LinesAndColumns(this._text);
this.positionAt = (offset) => {
if (offset >= this._text.length) {
offset = this._text.length - 1;
}
if (offset < 0) {
offset = 0;
}
const result = find.locationForIndex(offset);
if (!result) {
return;
}
return {
line: result.line + 1,
column: result.column,
};
};
this.offsetAt = (position) => {
return (
find.indexForLocation({
line: position.line - 1,
column: position.column,
}) ?? undefined
);
};
} | /** Generate location search */ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/utils/src/rule-utils/document/document.ts#L23-L55 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Document.edit | edit(data: DocumentEditData) {
let { _text: content } = this;
const startOffset = isNumber(data.start)
? data.start
: this.offsetAt(data.start);
const endOffset = isNumber(data.end) ? data.end : this.offsetAt(data.end);
if (isUndefined(startOffset) || isUndefined(endOffset)) {
return;
}
const startTxt = content.substring(0, startOffset);
const endTxt = content.substring(endOffset, content.length);
content = startTxt + data.newText + endTxt;
return content;
} | /** Edit document data */ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/utils/src/rule-utils/document/document.ts#L81-L98 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | RsdoctorWebpackPlugin.ensureModulesChunksGraphApplied | public ensureModulesChunksGraphApplied(compiler: Compiler) {
ensureModulesChunksGraphFn(compiler, this);
} | /**
* @description Generate ModuleGraph and ChunkGraph from stats and webpack module apis;
* @param {Compiler} compiler
* @return {*}
* @memberof RsdoctorWebpackPlugin
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/webpack-plugin/src/plugin.ts#L197-L199 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | loadMultipleFile | function loadMultipleFile() {
let multiple: typeof import('../dist/multiple');
multiple = require('../dist/multiple');
return multiple!;
} | /**
* create sandbox to load src/multiple.ts to avoid sdk save in global variable between different test cases.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/webpack-plugin/tests/multiple.test.ts#L6-L10 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | loadMultipleFile | function loadMultipleFile() {
let multiple: typeof import('../dist/multiple');
multiple = require('../dist/multiple');
return multiple!;
} | /**
* create sandbox to load src/multiple.ts to avoid sdk save in global variable between different test cases.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/webpack-plugin/tests/multipleWithStage.test.ts#L6-L10 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
discuit | github_2023 | discuitnet | typescript | hostnameToURL | function hostnameToURL(addr: string) {
let scheme: string = '',
hostname: string = '',
port: string = '';
let n = addr.indexOf('://');
if (n !== -1) {
scheme = addr.substring(0, n);
addr = addr.substring(n + 3);
if (!(scheme === 'http' || scheme === 'https')) {
throw new Error(`unknown scheme: ${scheme}`);
}
}
n = addr.indexOf(':');
if (n !== -1) {
hostname = addr.substring(0, n);
port = addr.substring(n);
const portErr = new Error('port is not a number');
if (port.length === 1) {
throw portErr;
}
port = port.substring(1);
if (isNaN(parseInt(port.substring(1), 10))) {
throw portErr;
}
} else {
hostname = addr;
}
if (!hostname && !port) {
throw new Error('empty address');
}
if (!hostname) {
hostname = 'localhost';
}
if (!scheme) {
scheme = port === '443' ? 'https' : 'http';
}
let portString = '';
if (port && !((scheme === 'http' && port === '80') || (scheme === 'https' && port === '443'))) {
portString = `:${port}`;
}
return `${scheme}://${hostname}${portString}`;
} | /**
* Takes in a string of the form 'host:port' and returns a full URL. Either the
* 'host' part or the 'port' could be ommitted, but not both.
*
*/ | https://github.com/discuitnet/discuit/blob/6e09c263dcf4fb2866931e8a6c31b2387ab63441/ui/vite.config.ts#L95-L142 | 6e09c263dcf4fb2866931e8a6c31b2387ab63441 |
discuit | github_2023 | discuitnet | typescript | listener | const listener = async () => {
if (!document.hidden) await forceSwUpdate();
}; | // every 2 minutes | https://github.com/discuitnet/discuit/blob/6e09c263dcf4fb2866931e8a6c31b2387ab63441/ui/src/AppUpdate.tsx#L19-L21 | 6e09c263dcf4fb2866931e8a6c31b2387ab63441 |
discuit | github_2023 | discuitnet | typescript | shouldDisplayUpdatePrompt | function shouldDisplayUpdatePrompt() {
const val = window.localStorage.getItem(localStorageKey);
if (val === null) {
return true;
}
const valInt = parseInt(val, 10);
if (isNaN(valInt)) {
return true;
}
const current = Date.now() / 1000;
return current - valInt > 20 * 60;
} | /**
* Returns true if the update prompt has not been displayed to the user in the
* last 20 minutes.
*
* @returns booleon
*/ | https://github.com/discuitnet/discuit/blob/6e09c263dcf4fb2866931e8a6c31b2387ab63441/ui/src/AppUpdate.tsx#L129-L140 | 6e09c263dcf4fb2866931e8a6c31b2387ab63441 |
play-nextjs | github_2023 | NextJSTemplates | typescript | scrollToTop | const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
}; | // Top: 0 takes us all the way back to the top of the page | https://github.com/NextJSTemplates/play-nextjs/blob/ea21d405bb4187aa7433fb8ce8c018d5753cbd0d/src/components/ScrollToTop/index.tsx#L8-L13 | ea21d405bb4187aa7433fb8ce8c018d5753cbd0d |
play-nextjs | github_2023 | NextJSTemplates | typescript | toggleVisibility | const toggleVisibility = () => {
if (window.pageYOffset > 300) {
setIsVisible(true);
} else {
setIsVisible(false);
}
}; | // Button is displayed after scrolling for 500 pixels | https://github.com/NextJSTemplates/play-nextjs/blob/ea21d405bb4187aa7433fb8ce8c018d5753cbd0d/src/components/ScrollToTop/index.tsx#L17-L23 | ea21d405bb4187aa7433fb8ce8c018d5753cbd0d |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-astro/internal.ts#L48-L64 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-bun/index.ts#L26-L42 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-deno/index.ts#L24-L40 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-nest/index.ts#L40-L56 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | decorate | function decorate(decorators: any[], target: any, key?: any, desc?: any): any {
return Reflect.decorate(decorators, target, key, desc);
} | /* Begin utilties pulled from TypeScript's tslib */ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-nest/index.ts#L586-L588 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | param | function param(
paramIndex: number,
decorator: (target: any, key: any, paramIndex: number) => void,
) {
return function (target: any, key: any) {
decorator(target, key, paramIndex);
};
} | // Creates a decorator for a constructor parameter. Pulled out of `tslib` to | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-nest/index.ts#L592-L599 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | isUndefined | const isUndefined = (obj: any) => typeof obj === "undefined"; | /* End utilities pulled from TypeScript's tslib */ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-nest/index.ts#L607-L607 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | isOptionalFactoryDependency | function isOptionalFactoryDependency(
x: InjectionToken | OptionalFactoryDependency,
): x is OptionalFactoryDependency {
return !!((x as any)?.token && !(x as any)?.prototype);
} | // The below are taken from Nest.js to avoid needing to avoid using the | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-nest/index.ts#L635-L639 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-next/index.ts#L46-L62 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-node/index.ts#L24-L40 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-remix/index.ts#L23-L39 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Deduplicate with other packages | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet-sveltekit/index.ts#L24-L40 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | Performance.measure | measure(label: string) {
const start = performance.now();
return () => {
const end = performance.now();
const diff = end - start;
this.log.debug("LATENCY %s: %sms", label, diff.toFixed(3));
};
} | // TODO(#2020): We should no-op this if loglevel is not `debug` to do less work | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet/index.ts#L212-L219 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | withRule | function withRule<Rule extends Primitive | Product>(
baseRules: ArcjetRule[],
rule: Rule,
) {
const rules = [...baseRules, ...rule].sort(
(a, b) => a.priority - b.priority,
);
return Object.freeze({
withRule(rule: Primitive | Product) {
return withRule(rules, rule);
},
async protect(
ctx: ArcjetAdapterContext,
request: ArcjetRequest<ExtraProps<typeof rules>>,
): Promise<ArcjetDecision> {
return protect(rules, ctx, request);
},
});
} | // This is a separate function so it can be called recursively | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet/index.ts#L1677-L1696 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | areHeadersEqual | function areHeadersEqual(a: unknown, b: unknown): boolean | undefined {
const isAHeaders = a instanceof Headers;
const isBHeaders = b instanceof Headers;
if (isAHeaders && isBHeaders) {
const aKeys = Array.from(a.keys());
const bKeys = Array.from(b.keys());
return (
aKeys.every((key) => b.has(key)) &&
bKeys.every((key) => a.has(key)) &&
Array.from(a.entries()).every(([key, value]) => {
return b.get(key) === value;
})
);
} else if (isAHeaders === isBHeaders) {
return undefined;
} else {
return false;
}
} | // Instances of Headers contain symbols that may be different depending | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/arcjet/test/arcjet.test.ts#L67-L86 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | leadingInt | function leadingInt(s: string): [number, string] {
let i = 0;
let x = 0;
for (; i < s.length; i++) {
const c = s[i];
if (!integers.includes(c)) {
break;
}
x = x * 10 + parseInt(c, 10);
if (x > maxUint32) {
// overflow
throw new Error("bad [0-9]*"); // never printed
}
}
return [x, s.slice(i)];
} | // leadingInt consumes the leading [0-9]* from s. | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/duration/index.ts#L53-L68 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | getEmailHash | async function getEmailHash(email: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(email);
const hash = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hash));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
} | // A very simple hash to avoid sending PII to Arcjet. You may wish to add a | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/examples/nextjs-authjs-5/middleware.ts#L25-L32 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ajProtectedPOST | const ajProtectedPOST = async (req: NextRequest) => {
const decision = await aj.protect(req);
console.log("Arcjet decision", decision);
if (decision.isDenied()) {
if (decision.reason.isRateLimit()) {
return NextResponse.json({ error: "Too Many Requests" }, { status: 429 });
} else {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
}
return handlers.POST(req);
}; | // Protect the sensitive actions e.g. login, signup, etc with Arcjet | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/examples/nextjs-authjs-5/app/auth/[...nextauth]/route.ts#L24-L37 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | GET | const GET = async (req: NextRequest) => {
return handlers.GET(req);
} | // You could also protect the GET handler, but these tend to be less sensitive | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/examples/nextjs-authjs-5/app/auth/[...nextauth]/route.ts#L41-L43 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | getClient | async function getClient() {
// If the user is not logged in then give them a low rate limit
const user = await currentUser();
if (!user) {
return (
arcjet
// Add a sliding window to limit requests to 5 per minute
.withRule(slidingWindow({ mode: "LIVE", max: 5, interval: 60 }))
// Add detection to block all detected bots
.withRule(detectBot({ mode: "LIVE", allow: [] }))
);
}
// If the user is logged in but does not have permission to update stats
// then give them a medium rate limit.
const canUpdate = await permit.check(user.id, "update", "stats");
if (!canUpdate) {
return (
arcjet
// Add a sliding window to limit requests to 10 per minute
.withRule(slidingWindow({ mode: "LIVE", max: 10, interval: 60 }))
);
}
// User is logged in and has permission to update stats,
// so give them no rate limit
return arcjet;
} | // Returns ad-hoc rules depending on whether the user is logged in, and if they | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/examples/nextjs-permit/src/app/api/stats/route.ts#L12-L39 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | detectDash | function detectDash(tokens: string[]): Array<"CONTAINS_DASH" | undefined> {
return tokens.map((token) => {
if (token.includes("-")) {
return "CONTAINS_DASH";
}
});
} | // This function is called by the `sensitiveInfo` rule to perform custom detection on strings. | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/examples/nextjs-sensitive-info/app/api/arcjet/route.ts#L5-L11 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetHeaders.append | append(key: string, value: string): void {
if (typeof key !== "string" || typeof value !== "string") {
return;
}
if (key.toLowerCase() !== "cookie") {
super.append(key, value);
}
} | /**
* Append a key and value to the headers, while filtering any key named
* `cookie`.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)
*
* @param key The key to append in the headers
* @param value The value to append for the key in the headers
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/headers/index.ts#L61-L69 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetHeaders.set | set(key: string, value: string): void {
if (typeof key !== "string" || typeof value !== "string") {
return;
}
if (key.toLowerCase() !== "cookie") {
super.set(key, value);
}
} | /**
* Set a key and value in the headers, but filtering any key named `cookie`.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)
*
* @param key The key to set in the headers
* @param value The value to set for the key in the headers
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/headers/index.ts#L78-L86 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | readGroups | const readGroups = (p: Parser, groups: Uint16Array): [number, boolean] => {
const limit = groups.length;
for (const i of groups.keys()) {
// Try to read a trailing embedded IPv4 address. There must be at least
// two groups left
if (i < limit - 1) {
const ipv4 = p.readSeparator(":", i, (p) => p.readIPv4Address());
if (isIPv4Tuple(ipv4)) {
const [one, two, three, four] = ipv4;
groups[i + 0] = u16FromBytes([one, two]);
groups[i + 1] = u16FromBytes([three, four]);
return [i + 2, true];
}
}
const group = p.readSeparator(":", i, (p) => p.readNumber(16, 4, true));
if (typeof group !== "undefined") {
groups[i] = group;
} else {
return [i, false];
}
}
return [groups.length, false];
}; | // Read a chunk of an IPv6 address into `groups`. Returns the number of | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/ip/index.ts#L207-L233 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | findIP | function findIP(request: RequestLike, options: Options = {}): string {
const { platform, proxies } = options;
// Prefer anything available via the platform over headers since headers can
// be set by users. Only if we don't have an IP available in `request` do we
// search the `headers`.
if (isGlobalIP(request.ip, proxies)) {
return request.ip;
}
const socketRemoteAddress = request.socket?.remoteAddress;
if (isGlobalIP(socketRemoteAddress, proxies)) {
return socketRemoteAddress;
}
const infoRemoteAddress = request.info?.remoteAddress;
if (isGlobalIP(infoRemoteAddress, proxies)) {
return infoRemoteAddress;
}
// AWS Api Gateway + Lambda
const requestContextIdentitySourceIP =
request.requestContext?.identity?.sourceIp;
if (isGlobalIP(requestContextIdentitySourceIP, proxies)) {
return requestContextIdentitySourceIP;
}
// Validate we have some object for `request.headers`
if (typeof request.headers !== "object" || request.headers === null) {
return "";
}
// Platform-specific headers should only be accepted when we can determine
// that we are running on that platform. For example, the `CF-Connecting-IP`
// header should only be accepted when running on Cloudflare; otherwise, it
// can be spoofed.
if (platform === "cloudflare") {
// CF-Connecting-IPv6: https://developers.cloudflare.com/fundamentals/reference/http-request-headers/#cf-connecting-ipv6
const cfConnectingIPv6 = getHeader(request.headers, "cf-connecting-ipv6");
if (isGlobalIPv6(cfConnectingIPv6, proxies)) {
return cfConnectingIPv6;
}
// CF-Connecting-IP: https://developers.cloudflare.com/fundamentals/reference/http-request-headers/#cf-connecting-ip
const cfConnectingIP = getHeader(request.headers, "cf-connecting-ip");
if (isGlobalIP(cfConnectingIP, proxies)) {
return cfConnectingIP;
}
// If we are using a platform check and don't have a Global IP, we exit
// early with an empty IP since the more generic headers shouldn't be
// trusted over the platform-specific headers.
return "";
}
// Fly.io: https://fly.io/docs/machines/runtime-environment/#fly_app_name
if (platform === "fly-io") {
// Fly-Client-IP: https://fly.io/docs/networking/request-headers/#fly-client-ip
const flyClientIP = getHeader(request.headers, "fly-client-ip");
if (isGlobalIP(flyClientIP, proxies)) {
return flyClientIP;
}
// If we are using a platform check and don't have a Global IP, we exit
// early with an empty IP since the more generic headers shouldn't be
// trusted over the platform-specific headers.
return "";
}
if (platform === "vercel") {
// https://vercel.com/docs/edge-network/headers/request-headers#x-real-ip
// Also used by `@vercel/functions`, see:
// https://github.com/vercel/vercel/blob/d7536d52c87712b1b3f83e4b0fd535a1fb7e384c/packages/functions/src/headers.ts#L12
const xRealIP = getHeader(request.headers, "x-real-ip");
if (isGlobalIP(xRealIP, proxies)) {
return xRealIP;
}
// https://vercel.com/docs/edge-network/headers/request-headers#x-vercel-forwarded-for
// By default, it seems this will be 1 address, but they discuss trusted
// proxy forwarding so we try to parse it like normal. See
// https://vercel.com/docs/edge-network/headers/request-headers#custom-x-forwarded-for-ip
const xVercelForwardedFor = getHeader(
request.headers,
"x-vercel-forwarded-for",
);
const xVercelForwardedForItems = parseXForwardedFor(xVercelForwardedFor);
// As per MDN X-Forwarded-For Headers documentation at
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
// We may find more than one IP in the `x-forwarded-for` header. Since the
// first IP will be closest to the user (and the most likely to be spoofed),
// we want to iterate tail-to-head so we reverse the list.
for (const item of xVercelForwardedForItems.reverse()) {
if (isGlobalIP(item, proxies)) {
return item;
}
}
// https://vercel.com/docs/edge-network/headers/request-headers#x-forwarded-for
// By default, it seems this will be 1 address, but they discuss trusted
// proxy forwarding so we try to parse it like normal. See
// https://vercel.com/docs/edge-network/headers/request-headers#custom-x-forwarded-for-ip
const xForwardedFor = getHeader(request.headers, "x-forwarded-for");
const xForwardedForItems = parseXForwardedFor(xForwardedFor);
// As per MDN X-Forwarded-For Headers documentation at
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
// We may find more than one IP in the `x-forwarded-for` header. Since the
// first IP will be closest to the user (and the most likely to be spoofed),
// we want to iterate tail-to-head so we reverse the list.
for (const item of xForwardedForItems.reverse()) {
if (isGlobalIP(item, proxies)) {
return item;
}
}
// If we are using a platform check and don't have a Global IP, we exit
// early with an empty IP since the more generic headers shouldn't be
// trusted over the platform-specific headers.
return "";
}
// Standard headers used by Amazon EC2, Heroku, and others.
const xClientIP = getHeader(request.headers, "x-client-ip");
if (isGlobalIP(xClientIP, proxies)) {
return xClientIP;
}
// Load-balancers (AWS ELB) or proxies.
const xForwardedFor = getHeader(request.headers, "x-forwarded-for");
const xForwardedForItems = parseXForwardedFor(xForwardedFor);
// As per MDN X-Forwarded-For Headers documentation at
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
// We may find more than one IP in the `x-forwarded-for` header. Since the
// first IP will be closest to the user (and the most likely to be spoofed),
// we want to iterate tail-to-head so we reverse the list.
for (const item of xForwardedForItems.reverse()) {
if (isGlobalIP(item, proxies)) {
return item;
}
}
// DigitalOcean.
// DO-Connecting-IP: https://www.digitalocean.com/community/questions/app-platform-client-ip
const doConnectingIP = getHeader(request.headers, "do-connecting-ip");
if (isGlobalIP(doConnectingIP, proxies)) {
return doConnectingIP;
}
// Fastly and Firebase hosting header (When forwared to cloud function)
// Fastly-Client-IP
const fastlyClientIP = getHeader(request.headers, "fastly-client-ip");
if (isGlobalIP(fastlyClientIP, proxies)) {
return fastlyClientIP;
}
// Akamai
// True-Client-IP
const trueClientIP = getHeader(request.headers, "true-client-ip");
if (isGlobalIP(trueClientIP, proxies)) {
return trueClientIP;
}
// Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies
// X-Real-IP
const xRealIP = getHeader(request.headers, "x-real-ip");
if (isGlobalIP(xRealIP, proxies)) {
return xRealIP;
}
// Rackspace LB and Riverbed's Stingray?
const xClusterClientIP = getHeader(request.headers, "x-cluster-client-ip");
if (isGlobalIP(xClusterClientIP, proxies)) {
return xClusterClientIP;
}
const xForwarded = getHeader(request.headers, "x-forwarded");
if (isGlobalIP(xForwarded, proxies)) {
return xForwarded;
}
const forwardedFor = getHeader(request.headers, "forwarded-for");
if (isGlobalIP(forwardedFor, proxies)) {
return forwardedFor;
}
const forwarded = getHeader(request.headers, "forwarded");
if (isGlobalIP(forwarded, proxies)) {
return forwarded;
}
// Google Cloud App Engine
// X-Appengine-User-IP: https://cloud.google.com/appengine/docs/standard/reference/request-headers?tab=node.js
const xAppEngineUserIP = getHeader(request.headers, "x-appengine-user-ip");
if (isGlobalIP(xAppEngineUserIP, proxies)) {
return xAppEngineUserIP;
}
return "";
} | // Heavily based on https://github.com/pbojinov/request-ip | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/ip/index.ts#L634-L832 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | nested | function nested(keys: string[]): RequestLike {
if (keys.length > 1) {
return {
...Object.fromEntries([[keys[0], nested(keys.slice(1))]]),
headers: new Headers(),
};
} else {
return {
...Object.fromEntries([[keys[0], ip]]),
headers: new Headers(),
};
}
} | // Create a nested request-like object based on the keys passed to the function | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/ip/test/ipv4.test.ts#L183-L195 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | nested | function nested(keys: string[]): RequestLike {
if (keys.length > 1) {
return {
...Object.fromEntries([[keys[0], nested(keys.slice(1))]]),
headers: new Headers(),
};
} else {
return {
...Object.fromEntries([[keys[0], ip]]),
headers: new Headers(),
};
}
} | // Create a nested request-like object based on the keys passed to the function | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/ip/test/ipv6.test.ts#L111-L123 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | tryStringify | function tryStringify(o: unknown) {
try {
return JSON.stringify(o, bigintReplacer);
} catch (e) {
return "[Circular]";
}
} | // TODO: Deduplicate this and sprintf implementation | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/logger/index.ts#L12-L18 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | errorMessage | function errorMessage(err: unknown): string {
if (err) {
if (typeof err === "string") {
return err;
}
if (
typeof err === "object" &&
"message" in err &&
typeof err.message === "string"
) {
return err.message;
}
}
return "Unknown problem";
} | // TODO: Dedupe with `errorMessage` in core | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/client.ts#L24-L40 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.hasCity | hasCity(): this is RequiredProps<this, "city"> {
return typeof this.city !== "undefined";
} | // TODO: If we have city, what other data are we sure to have? | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L585-L587 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.hasRegion | hasRegion(): this is RequiredProps<this, "region"> {
return typeof this.region !== "undefined";
} | // TODO: If we have region, what other data are we sure to have? | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L590-L592 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.hasCountry | hasCountry(): this is RequiredProps<this, "country" | "countryName"> {
return typeof this.country !== "undefined";
} | // TODO: If we have country, should we also have continent? | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L596-L598 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.hasContintent | hasContintent(): this is RequiredProps<this, "continent" | "continentName"> {
return typeof this.continent !== "undefined";
} | // If we have continent, we should have continent name | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L601-L603 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.hasASN | hasASN(): this is RequiredProps<
this,
"asn" | "asnName" | "asnDomain" | "asnType" | "asnCountry"
> {
return typeof this.asn !== "undefined";
} | // If we have ASN, we should have every piece of ASN information. | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L606-L611 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.isHosting | isHosting(): boolean {
// @ts-expect-error because we attach this with Object.defineProperties
return this._isHosting;
} | /**
* @returns `true` if the IP address belongs to a hosting provider.
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L620-L623 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.isVpn | isVpn(): boolean {
// @ts-expect-error because we attach this with Object.defineProperties
return this._isVpn;
} | /**
* @returns `true` if the IP address belongs to a VPN provider.
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L628-L631 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.isProxy | isProxy(): boolean {
// @ts-expect-error because we attach this with Object.defineProperties
return this._isProxy;
} | /**
* @returns `true` if the IP address belongs to a proxy provider.
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L636-L639 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.isTor | isTor(): boolean {
// @ts-expect-error because we attach this with Object.defineProperties
return this._isTor;
} | /**
* @returns `true` if the IP address belongs to a Tor node.
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L644-L647 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | ArcjetIpDetails.isRelay | isRelay(): boolean {
// @ts-expect-error because we attach this with Object.defineProperties
return this._isRelay;
} | /**
* @returns `true` if the the IP address belongs to a relay service.
*/ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/protocol/index.ts#L652-L655 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | noOpDetect | function noOpDetect(_tokens: string[]): Array<SensitiveInfoEntity | undefined> {
return [];
} | /* c8 ignore start */ | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/redact/index.ts#L94-L96 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | tryStringify | function tryStringify(o: unknown) {
try {
return JSON.stringify(o, bigintReplacer);
} catch (e) {
return `"[Circular]"`;
}
} | // TODO: Deduplicate this and logger implementation | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/sprintf/index.ts#L10-L16 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
arcjet-js | github_2023 | arcjet | typescript | format | function format(str, args) {
return sprintf(str, ...args);
} | // This translates the 2nd argument to a spread | https://github.com/arcjet/arcjet-js/blob/211dbd0fe35f3a72c267fd21cfeb083214f66372/sprintf/test/quick-format-unescaped.test.ts#L6-L8 | 211dbd0fe35f3a72c267fd21cfeb083214f66372 |
doc-solver | github_2023 | ai-hermes | typescript | html | function html(params: { url: string; host: string; theme: Theme }) {
const { url, host } = params;
//由于使用
const escapedHost = host.replace(/\./g, "​.");
return `
<body>
<div style="background:#f2f5f7;display: flex;justify-content: center;align-items: center; height:200px">欢迎注册${escapedHost},点击<a href="${url}" target="_blank">登录</a></div>
</body>
`;
} | /**
*使用HTML body 代替正文内容
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/sendVerificationRequest.ts#L27-L37 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | text | function text({ url, host }: { url: string; host: string }) {
return `欢迎注册 ${host}\n点击${url}登录\n\n`;
} | /** 不支持HTML 的邮件客户端会显示下面的文本信息 */ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/sendVerificationRequest.ts#L40-L42 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | getBoundingRect | const getBoundingRect = (clientRects: Array<LTWHP>): LTWHP => {
const rects = Array.from(clientRects).map((rect) => {
const { left, top, width, height, pageNumber } = rect;
const X0 = left;
const X1 = left + width;
const Y0 = top;
const Y1 = top + height;
return { X0, X1, Y0, Y1, pageNumber };
});
// reduce 得到最小的页码
let firstPageNumber = Number.MAX_SAFE_INTEGER;
rects.forEach((rect) => {
firstPageNumber = Math.min(
firstPageNumber,
rect.pageNumber ?? firstPageNumber
);
});
// 过滤出页码为第一页且宽高合法的rect
const rectsWithSizeOnFirstPage = rects.filter(
(rect) =>
(rect.X0 > 0 || rect.X1 > 0 || rect.Y0 > 0 || rect.Y1 > 0) &&
rect.pageNumber === firstPageNumber
);
// 对过滤出来的rects进行reduce,得到最小的X0,最大的X1,最小的Y0,最大的Y1
const optimal = rectsWithSizeOnFirstPage.reduce((res, rect) => {
return {
X0: Math.min(res.X0, rect.X0),
X1: Math.max(res.X1, rect.X1),
Y0: Math.min(res.Y0, rect.Y0),
Y1: Math.max(res.Y1, rect.Y1),
pageNumber: firstPageNumber,
};
}, rectsWithSizeOnFirstPage[0]);
const { X0, X1, Y0, Y1, pageNumber } = optimal;
// 坐标重新返回成LTWHP
return {
left: X0,
top: Y0,
width: X1 - X0,
height: Y1 - Y0,
pageNumber,
};
}; | /**
* 遍历所有的rect得到第一页(指的是rects列表的第一页),reduce出区域最大的rect
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/ui/lib/get-bounding-rect.ts#L6-L57 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | isClientRectInsidePageRect | const isClientRectInsidePageRect = (clientRect: DOMRect, pageRect: DOMRect) => {
if (clientRect.top < pageRect.top) {
return false;
}
if (clientRect.bottom > pageRect.bottom) {
return false;
}
if (clientRect.right > pageRect.right) {
return false;
}
if (clientRect.left < pageRect.left) {
return false;
}
return true;
}; | /**
* 判断 clientRect 是否在 pageRect 内部
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/ui/lib/get-client-rects.ts#L8-L23 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | getBoundingRect | const getBoundingRect = (clientRects: Array<LTWHP>): LTWHP => {
const rects = Array.from(clientRects).map((rect) => {
const { left, top, width, height, pageNumber } = rect;
const X0 = left;
const X1 = left + width;
const Y0 = top;
const Y1 = top + height;
return { X0, X1, Y0, Y1, pageNumber };
});
// reduce 得到最小的页码
let firstPageNumber = Number.MAX_SAFE_INTEGER;
rects.forEach((rect) => {
firstPageNumber = Math.min(
firstPageNumber,
rect.pageNumber ?? firstPageNumber
);
});
// 过滤出页码为第一页且宽高合法的rect
const rectsWithSizeOnFirstPage = rects.filter(
(rect) =>
(rect.X0 > 0 || rect.X1 > 0 || rect.Y0 > 0 || rect.Y1 > 0) &&
rect.pageNumber === firstPageNumber
);
// 对过滤出来的rects进行reduce,得到最小的X0,最大的X1,最小的Y0,最大的Y1
const optimal = rectsWithSizeOnFirstPage.reduce((res, rect) => {
return {
X0: Math.min(res.X0, rect.X0),
X1: Math.max(res.X1, rect.X1),
Y0: Math.min(res.Y0, rect.Y0),
Y1: Math.max(res.Y1, rect.Y1),
pageNumber: firstPageNumber,
};
}, rectsWithSizeOnFirstPage[0]);
const { X0, X1, Y0, Y1, pageNumber } = optimal;
// 坐标重新返回成LTWHP
return {
left: X0,
top: Y0,
width: X1 - X0,
height: Y1 - Y0,
pageNumber,
};
}; | /**
* 遍历所有的rect得到第一页(指的是rects列表的第一页),reduce出区域最大的rect
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/ui/react-pdf-highlighter/lib/get-bounding-rect.ts#L6-L57 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | isClientRectInsidePageRect | const isClientRectInsidePageRect = (clientRect: DOMRect, pageRect: DOMRect) => {
if (clientRect.top < pageRect.top) {
return false;
}
if (clientRect.bottom > pageRect.bottom) {
return false;
}
if (clientRect.right > pageRect.right) {
return false;
}
if (clientRect.left < pageRect.left) {
return false;
}
return true;
}; | /**
* 判断 clientRect 是否在 pageRect 内部
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/components/ui/react-pdf-highlighter/lib/get-client-rects.ts#L8-L23 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | PDFLoader.parse | public async parse(
raw: Buffer,
metadata: Document["metadata"]
): Promise<Document[]> {
const { getDocument, version } = await this.pdfjs();
const doc = await getDocument({
data: new Uint8Array(raw.buffer),
useWorkerFetch: false,
isEvalSupported: false,
useSystemFonts: true,
}).promise;
this.doc = doc;
const lines = await this.getPdfItems();
const chunks = this.generateChunks(lines);
// mark relationship of chunk and lines
// a chunk contains many lines, and a line belongs to many chuncks
this.chunks = chunks.map((chunk, chunkIndex) => {
chunk.id = uuidv4();
chunk.lines = chunk.lines.map((line, lineIndex) => {
return {
...line,
id: uuidv4(),
chunk_id: chunk.id,
attribute: {
...this.metaData,
innerChunkNo: lineIndex,
}
}
})
chunk.attribute = {
...this.metaData,
innerChunkNo: chunkIndex,
};
return chunk;
})
this.lines = this.chunks.reduce((p, c) => {
return p.concat(c.lines);
}, this.lines)
return chunks.map((chunk, index) => {
return new Document({
pageContent: chunk.str,
metadata: {
...metadata,
...this.metaData,
libVersion: version,
chunkId: chunk.id,
innerChunkNo: index,
pageNums: chunk.page_nums
}
})
});
} | /**
* A method that takes a `raw` buffer and `metadata` as parameters and
* returns a promise that resolves to an array of `Document` instances. It
* uses the `getDocument` function from the PDF.js library to load the PDF
* from the buffer. It then iterates over each page of the PDF, retrieves
* the text content using the `getTextContent` method, and joins the text
* items to form the page content. It creates a new `Document` instance
* for each page with the extracted text content and metadata, and adds it
* to the `documents` array. If `splitPages` is `true`, it returns the
* array of `Document` instances. Otherwise, if there are no documents, it
* returns an empty array. Otherwise, it concatenates the page content of
* all documents and creates a single `Document` instance with the
* concatenated content.
* @param raw The buffer to be parsed.
* @param metadata The metadata of the document.
* @returns A promise that resolves to an array of `Document` instances.
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/lib/pdfLoader.ts#L59-L114 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | PDFLoader.parse | public async parse(
raw: Buffer,
metadata: Document["metadata"]
): Promise<Document[]> {
const { getDocument, version } = await this.pdfjs();
const doc = await getDocument({
data: new Uint8Array(raw.buffer),
useWorkerFetch: false,
isEvalSupported: false,
useSystemFonts: true,
}).promise;
this.doc = doc;
const lines = await this.getPdfItems();
const chunks = this.generateChunks(lines);
// mark relationship of chunk and lines
// a chunk contains many lines, and a line belongs to many chuncks
this.chunks = chunks.map((chunk, chunkIndex) => {
chunk.id = uuidv4();
chunk.lines = chunk.lines.map((line, lineIndex) => {
return {
...line,
id: uuidv4(),
chunk_id: chunk.id,
attribute: {
...this.metaData,
innerChunkNo: lineIndex,
}
}
})
chunk.attribute = {
...this.metaData,
innerChunkNo: chunkIndex,
};
return chunk;
})
this.lines = this.chunks.reduce((p, c) => {
return p.concat(c.lines);
}, this.lines)
return chunks.map((chunk, index) => {
return new Document({
pageContent: chunk.str,
metadata: {
...metadata,
...this.metaData,
libVersion: version,
chunkId: chunk.id,
innerChunkNo: index,
pageNums: chunk.page_nums
}
})
});
} | /**
* A method that takes a `raw` buffer and `metadata` as parameters and
* returns a promise that resolves to an array of `Document` instances. It
* uses the `getDocument` function from the PDF.js library to load the PDF
* from the buffer. It then iterates over each page of the PDF, retrieves
* the text content using the `getTextContent` method, and joins the text
* items to form the page content. It creates a new `Document` instance
* for each page with the extracted text content and metadata, and adds it
* to the `documents` array. If `splitPages` is `true`, it returns the
* array of `Document` instances. Otherwise, if there are no documents, it
* returns an empty array. Otherwise, it concatenates the page content of
* all documents and creates a single `Document` instance with the
* concatenated content.
* @param raw The buffer to be parsed.
* @param metadata The metadata of the document.
* @returns A promise that resolves to an array of `Document` instances.
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/pdfLoader.ts#L59-L114 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
doc-solver | github_2023 | ai-hermes | typescript | Typewriter.dynamicSpeed | dynamicSpeed() {
const speed = 2000 / this.queue.length
if (speed > 200) {
return 200
} else {
return speed
}
} | /**
* return a speed that is inversely proportional to the length of the queue
*/ | https://github.com/ai-hermes/doc-solver/blob/8f7752e36df3c1f333ec8edb42eb1755a914af34/utils/typewriter.ts#L12-L19 | 8f7752e36df3c1f333ec8edb42eb1755a914af34 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.