repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
nodejs-vertexai
github_2023
googleapis
typescript
GenerativeModelPreview.generateContentStream
async generateContentStream( request: GenerateContentRequest | string ): Promise<StreamGenerateContentResult> { request = formulateRequestToGenerateContentRequest(request); const formulatedRequest = { ...formulateSystemInstructionIntoGenerateContentRequest( request, this.systemInstruction ), cachedContent: this.cachedContent?.name, }; return generateContentStream( this.location, this.resourcePath, this.fetchToken(), formulatedRequest, this.apiEndpoint, this.generationConfig, this.safetySettings, this.tools, this.toolConfig, this.requestOptions ); }
/** * Makes an async stream request to generate content. * * The response is returned chunk by chunk as it's being generated in {@link * StreamGenerateContentResult.stream}. After all chunks of the response are * returned, the aggregated response is available in * {@link StreamGenerateContentResult.response}. * * @example * ``` * const request = { * contents: [{role: 'user', parts: [{text: 'How are you doing today?'}]}], * }; * const streamingResult = await generativeModelPreview.generateContentStream(request); * for await (const item of streamingResult.stream) { * console.log('stream chunk: ', JSON.stringify(item)); * } * const aggregatedResponse = await streamingResult.response; * console.log('aggregated response: ', JSON.stringify(aggregatedResponse)); * ``` * * @param request - {@link GenerateContentRequest} * @returns Promise of {@link StreamGenerateContentResult} */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/models/generative_models.ts#L410-L433
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
GenerativeModelPreview.startChat
startChat(request?: StartChatParams): ChatSessionPreview { const startChatRequest: StartChatSessionRequest = { project: this.project, location: this.location, googleAuth: this.googleAuth, publisherModelEndpoint: this.publisherModelEndpoint, resourcePath: this.resourcePath, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: this.cachedContent?.name, }; if (request) { startChatRequest.history = request.history; startChatRequest.generationConfig = request.generationConfig ?? this.generationConfig; startChatRequest.safetySettings = request.safetySettings ?? this.safetySettings; startChatRequest.tools = request.tools ?? this.tools; startChatRequest.toolConfig = request.toolConfig ?? this.toolConfig; startChatRequest.systemInstruction = request.systemInstruction ?? this.systemInstruction; startChatRequest.cachedContent = request.cachedContent ?? this.cachedContent?.name; } return new ChatSessionPreview(startChatRequest, this.requestOptions); }
/** * Instantiates a {@link ChatSessionPreview}. * * The {@link ChatSessionPreview} class is a stateful class that holds the state of * the conversation with the model and provides methods to interact with the * model in chat mode. Calling this method doesn't make any calls to a remote * endpoint. To make remote call, use {@link ChatSessionPreview.sendMessage} or * {@link ChatSessionPreview.sendMessageStream}. * * @example * ``` * const chat = generativeModelPreview.startChat(); * const result1 = await chat.sendMessage("How can I learn more about Node.js?"); * const response1 = await result1.response; * console.log('Response: ', JSON.stringify(response1)); * * const result2 = await chat.sendMessageStream("What about python?"); * const response2 = await result2.response; * console.log('Response: ', JSON.stringify(await response2)); * ``` * * @param request - {@link StartChatParams} * @returns {@link ChatSessionPreview} */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/models/generative_models.ts#L488-L515
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
CachedContents.create
create(cachedContent: CachedContent): Promise<CachedContent> { const curatedCachedContent = { ...cachedContent, systemInstruction: cachedContent.systemInstruction ? formulateSystemInstructionIntoContent(cachedContent.systemInstruction) : undefined, model: inferModelName( this.client.apiClient.project, this.client.apiClient.location, cachedContent.model ), } as CachedContent; return this.client.create(curatedCachedContent); }
/** * Creates cached content, this call will initialize the cached content in the data storage, and users need to pay for the cache data storage. * @param cachedContent * @param parent - Required. The parent resource where the cached content will be created. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/cached_contents.ts#L154-L167
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
CachedContents.update
update( cachedContent: CachedContent, updateMask: string[] ): Promise<CachedContent> { if (!cachedContent.name) { throw new ClientError('Cached content name is required for update.'); } if (!updateMask || updateMask.length === 0) { throw new ClientError( 'Update mask is required for update. Fields set in cachedContent but not in updateMask will be ignored. Examples: ["ttl"] or ["expireTime"].' ); } const curatedCachedContent = { ...cachedContent, systemInstruction: cachedContent.systemInstruction ? formulateSystemInstructionIntoContent(cachedContent.systemInstruction) : undefined, name: inferFullResourceName( this.client.apiClient.project, this.client.apiClient.location, cachedContent.name ), }; return this.client.update(curatedCachedContent, updateMask); }
/** * Updates cached content configurations * * @param updateMask - Required. The list of fields to update. Format: google-fieldmask. See {@link https://cloud.google.com/docs/discovery/type-format} * @param name - Immutable. Identifier. The server-generated resource name of the cached content Format: projects/{project}/locations/{location}/cachedContents/{cached_content}. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/cached_contents.ts#L175-L199
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
CachedContents.delete
delete(name: string): Promise<void> { return this.client.delete( inferFullResourceName( this.client.apiClient.project, this.client.apiClient.location, name ) ); }
/** * Deletes cached content. * * @param name - Required. The resource name referring to the cached content. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/cached_contents.ts#L206-L214
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
CachedContents.list
list( pageSize?: number, pageToken?: string ): Promise<ListCachedContentsResponse> { return this.client.list(pageSize, pageToken); }
/** * Lists cached contents in a project. * * @param pageSize - Optional. The maximum number of cached contents to return. The service may return fewer than this value. If unspecified, some default (under maximum) number of items will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. * @param pageToken - Optional. A page token, received from a previous `ListCachedContents` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListCachedContents` must match the call that provided the page token. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/cached_contents.ts#L222-L227
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
CachedContents.get
get(name: string): Promise<CachedContent> { return this.client.get( inferFullResourceName( this.client.apiClient.project, this.client.apiClient.location, name ) ); }
/** * Gets cached content configurations. * * @param name - Required. The resource name referring to the cached content. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/cached_contents.ts#L234-L242
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
ApiClient.fetchToken
private fetchToken(): Promise<string | null | undefined> { const tokenPromise = this.googleAuth.getAccessToken().catch(e => { throw new GoogleAuthError(constants.CREDENTIAL_ERROR_MESSAGE, e); }); return tokenPromise; }
/** * Gets access token from GoogleAuth. Throws {@link GoogleAuthError} when * fails. * @returns Promise of token string. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/resources/shared/api_client.ts#L44-L49
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
nodejs-vertexai
github_2023
googleapis
typescript
GenerateContentResponseHandler.getFunctionCallsFromCandidate
static getFunctionCallsFromCandidate( candidate?: GenerateContentCandidate ): FunctionCall[] { if (!candidate) return [] as FunctionCall[]; return candidate.content.parts .filter((part: Part | undefined) => !!part && !!part.functionCall) .map((part: Part) => part.functionCall!); }
/** * Extracts function calls from a {@link GenerateContentCandidate}. * * @param candidate - The candidate to extract function calls from. * @returns the array of function calls in a {@link GenerateContentCandidate}. */
https://github.com/googleapis/nodejs-vertexai/blob/99f3ee8a4589b97f32fa14e0f3adc01163cd9846/src/types/generate_content_response_handler.ts#L30-L37
99f3ee8a4589b97f32fa14e0f3adc01163cd9846
CanvasEditor
github_2023
WindRunnerMax
typescript
Canvas.isDefaultMode
public isDefaultMode() { return !this.grab.on && !this.insert.on; }
/** * 判断是否默认模式 * @description 根据状态判断拖拽、插入状态 */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/index.ts#L120-L122
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
ElementNode.onMouseEnter
protected onMouseEnter = () => { this.isHovering = true; if (this.editor.selection.has(this.id)) { return void 0; } this.editor.canvas.mask.drawingEffect(this.range); }
/** * 触发节点的 Hover 效果 * @description Root - MouseLeave */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/element.ts
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
FrameNode.onRootMouseDown
private onRootMouseDown = (e: MouseEvent) => { this.savedRootMouseDown(e); this.unbindOpEvents(); this.bindOpEvents(); this.landing = Point.from(e.x, e.y); this.landingClient = Point.from(e.clientX, e.clientY); }
/** * 框选事件的起始 */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/frame.ts
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.parent
public get parent() { return this._parent; }
// ====== Parent ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L40-L42
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.range
public get range() { return this._range; }
// ====== Range ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L49-L51
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.z
public get z() { return this._z; }
// ====== Z-Index ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L58-L60
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.ignoreEvent
public get ignoreEvent() { return this._ignoreEvent; }
// ====== Event ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L75-L77
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.append
public append<T extends Node>(node: T | Empty) { if (!node) return void 0; // 类似希尔排序 保证`children`有序 `zIndex`升序 // 如果使用`sort`也可以 `ES`规范添加了`sort`作为稳定排序 const index = this.children.findIndex(item => item.z > node.z); if (index > -1) { this.children.splice(index, 0, node); } else { this.children.push(node); } node.setParent(this); this.clearFlatNodeOnLink(); }
// ====== DOM OP ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L84-L96
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Node.getFlatNode
public getFlatNode() { if (this.flatNodes) { return this.flatNodes; } // 右子树优先后序遍历 保证事件调用的顺序 const nodes: Node[] = []; const reverse = [...this.children].reverse(); reverse.forEach(node => { nodes.push(...node.getFlatNode()); nodes.push(node); }); this.flatNodes = nodes; return nodes; }
/** * 获取当前节点树的所有子节点 * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/node.ts#L127-L140
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
ReferNode.setRange
public setRange() {}
// COMPAT: 避免`Range`变换
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/refer.ts#L27-L27
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
ReferNode.onMouseMoveController
public onMouseMoveController = (latest: Range) => { this.clearNodes(); if (!latest || !this.editor.canvas.root.select.isDragging) return void 0; if (this.sortedX.length === 0 && this.sortedY.length === 0) { this.onMouseUpController(); // 取消所有状态 return void 0; } // 选中的节点候选`5`个点 // * * // * // * * const { startX, endX, startY, endY } = latest.flatten(); const { x: midX, y: midY } = latest.center(); // 分别找到目标图形的最近的参考线 const closestMinX = this.getClosestVal(this.sortedX, startX); const closestMidX = this.getClosestVal(this.sortedX, midX); const closestMaxX = this.getClosestVal(this.sortedX, endX); const closestMinY = this.getClosestVal(this.sortedY, startY); const closestMidY = this.getClosestVal(this.sortedY, midY); const closestMaxY = this.getClosestVal(this.sortedY, endY); // 分别计算出距离 const distMinX = Math.abs(closestMinX - startX); const distMidX = Math.abs(closestMidX - midX); const distMaxX = Math.abs(closestMaxX - endX); const distMinY = Math.abs(closestMinY - startY); const distMidY = Math.abs(closestMidY - midY); const distMaxY = Math.abs(closestMaxY - endY); // 找到最近距离 const closestXDist = Math.min(distMinX, distMidX, distMaxX); const closestYDist = Math.min(distMinY, distMidY, distMaxY); // 吸附偏移 偏移区间为`REFER_BIAS` let offsetX: number | null = null; let offsetY: number | null = null; if (closestXDist < REFER_BIAS) { if (this.isNear(closestXDist, distMinX)) { offsetX = closestMinX - startX; } else if (this.isNear(closestXDist, distMidX)) { offsetX = closestMidX - midX; } else if (this.isNear(closestXDist, distMaxX)) { offsetX = closestMaxX - endX; } } if (closestYDist < REFER_BIAS) { if (this.isNear(closestYDist, distMinY)) { offsetY = closestMinY - startY; } else if (this.isNear(closestYDist, distMidY)) { offsetY = closestMidY - midY; } else if (this.isNear(closestYDist, distMaxY)) { offsetY = closestMaxY - endY; } } if (isEmptyValue(offsetX) && isEmptyValue(offsetY)) { // 未命中参考线需要清理 this.dragged && this.editor.canvas.mask.drawingEffect(this.dragged); this.dragged = null; return void 0; } const nextSelection = latest.move(offsetX || 0, offsetY || 0).normalize(); const prevPaintRange = this.dragged || nextSelection; let nextPaintRange = nextSelection.compose(prevPaintRange); // 构建参考线节点 const createReferNode = (range: Range) => { nextPaintRange = nextPaintRange.compose(range); const node = new Node(range); node.setIgnoreEvent(true); node.drawingMask = this.drawingMaskDispatch; this.append(node); this.matched = true; }; // 吸附功能 const next = nextSelection; const nextMid = next.center(); if (!isEmptyValue(offsetX)) { // 垂直参考线 同`X` if (this.isNear(offsetX, closestMinX - startX) && this.xLineMap.has(closestMinX)) { const ys = this.xLineMap.get(closestMinX) || [-1]; const minY = Math.min(...ys, next.start.y); const maxY = Math.max(...ys, next.end.y); const range = Range.from(next.start.x, minY, next.start.x, maxY); createReferNode(range); } if (this.isNear(offsetX, closestMidX - midX) && this.xLineMap.has(closestMidX)) { const ys = this.xLineMap.get(closestMidX) || [-1]; const minY = Math.min(...ys, next.start.y); const maxY = Math.max(...ys, next.end.y); const range = Range.from(nextMid.x, minY, nextMid.x, maxY); createReferNode(range); } if (this.isNear(offsetX, closestMaxX - endX) && this.xLineMap.has(closestMaxX)) { const ys = this.xLineMap.get(closestMaxX) || [-1]; const minY = Math.min(...ys, next.start.y); const maxY = Math.max(...ys, next.end.y); const range = Range.from(next.end.x, minY, next.end.x, maxY); createReferNode(range); } } if (!isEmptyValue(offsetY)) { // 水平参考线 同`Y` if (this.isNear(offsetY, closestMinY - startY) && this.yLineMap.has(closestMinY)) { const xs = this.yLineMap.get(closestMinY) || [-1]; const minX = Math.min(...xs, next.start.x); const maxX = Math.max(...xs, next.end.x); const range = Range.from(minX, next.start.y, maxX, next.start.y); createReferNode(range); } if (this.isNear(offsetY, closestMidY - midY) && this.yLineMap.has(closestMidY)) { const xs = this.yLineMap.get(closestMidY) || [-1]; const minX = Math.min(...xs, next.start.x); const maxX = Math.max(...xs, next.end.x); const range = Range.from(minX, nextMid.y, maxX, nextMid.y); createReferNode(range); } if (this.isNear(offsetY, closestMaxY - endY) && this.yLineMap.has(closestMaxY)) { const xs = this.yLineMap.get(closestMaxY) || [-1]; const minX = Math.min(...xs, next.start.x); const maxX = Math.max(...xs, next.end.x); const range = Range.from(minX, next.end.y, maxX, next.end.y); createReferNode(range); } } this.dragged = nextPaintRange; nextPaintRange && this.editor.canvas.mask.drawingEffect(nextPaintRange); return { x: offsetX || 0, y: offsetY || 0 }; }
/** * 拖拽选区的鼠标移动事件 * @param latest 拖拽选区的最新 Range * @description 作为 SelectNode 的子元素 Node 事件 * 基于父元素的事件调用链执行当前的事件绑定 * 避免多次对父元素的 Range 修改来保证值唯一 */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/refer.ts
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
createReferNode
const createReferNode = (range: Range) => { nextPaintRange = nextPaintRange.compose(range); const node = new Node(range); node.setIgnoreEvent(true); node.drawingMask = this.drawingMaskDispatch; this.append(node); this.matched = true; };
// 构建参考线节点
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/refer.ts#L135-L142
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
SelectNode.unbindDragEvents
private bindDragEvents = () => { this.editor.event.on(EDITOR_EVENT.MOUSE_UP_GLOBAL, this.onMouseUpController); this.editor.event.on(EDITOR_EVENT.MOUSE_MOVE_GLOBAL, this.onMouseMoveController); }
/** * 绑定拖拽事件的触发器 */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/dom/select.ts
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Mask.collectEffects
private collectEffects(range: Range) { // 判定`range`范围内影响的节点 const effects = new Set<Node>(); const nodes: Node[] = this.engine.root.getFlatNode(false); // 渲染顺序和事件调用顺序相反 for (let i = nodes.length - 1; i >= 0; i--) { const node = nodes[i]; // 需要排除`root`否则必然导致全量重绘 if (node === this.engine.root) continue; if (!this.editor.canvas.isOutside(node.range) && range.intersect(node.range)) { effects.add(node); } } return effects; }
// ====== Drawing On Demand ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/paint/mask.ts#L37-L51
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Mask.setCursorState
public setCursorState(type: keyof typeof CURSOR_STATE | null) { this.canvas.style.cursor = isEmptyValue(type) ? "" : CURSOR_STATE[type]; return this; }
// ====== State ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/paint/mask.ts#L97-L100
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Mask.reset
public reset() { this.clear(); const { width, height } = this.engine.getRect(); const ratio = this.engine.devicePixelRatio; this.canvas.width = width * ratio; this.canvas.height = height * ratio; this.canvas.style.width = width + "px"; this.canvas.style.height = height + "px"; this.canvas.style.position = "absolute"; this.resetCtx(); }
// ====== Canvas Actions ======
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/paint/mask.ts#L111-L121
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Shape.rect
public static rect(ctx: CanvasRenderingContext2D, options: RectProps) { ctx.beginPath(); ctx.rect(options.x, options.y, options.width, options.height); if (options.fillColor) { ctx.fillStyle = options.fillColor; ctx.fill(); } if (options.borderColor) { ctx.strokeStyle = options.borderColor; ctx.lineWidth = options.borderWidth || 1; ctx.stroke(); } ctx.closePath(); }
/** * 绘制矩形 * @param ctx * @param options */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/utils/shape.ts#L34-L47
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Shape.arc
public static arc(ctx: CanvasRenderingContext2D, options: ArcProps) { ctx.beginPath(); ctx.arc(options.x, options.y, options.radius, 0, 2 * Math.PI); if (options.fillColor) { ctx.fillStyle = options.fillColor; ctx.fill(); } if (options.borderColor) { ctx.strokeStyle = options.borderColor; ctx.lineWidth = options.borderWidth || 1; ctx.stroke(); } ctx.closePath(); }
/** * 绘制圆形 * @param ctx * @param options */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/utils/shape.ts#L54-L67
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Shape.frame
public static frame(ctx: CanvasRenderingContext2D, options: FrameProps) { // https://stackoverflow.com/questions/36615592/canvas-inner-stroke ctx.save(); ctx.beginPath(); const frame = [options.x - 1, options.y - 1, options.width + 2, options.height + 2] as const; const inside = [options.x, options.y, options.width, options.height] as const; const region = new Path2D(); region.rect(...frame); region.rect(...inside); ctx.clip(region, "evenodd"); ctx.rect(...frame); ctx.fillStyle = options.borderColor; ctx.fill(); ctx.closePath(); ctx.restore(); }
/** * 绘制框选 * @param ctx * @param options */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/canvas/utils/shape.ts#L74-L89
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Selection.clearActiveDeltas
public clearActiveDeltas() { if (this.active.size === 0) { return void 0; } this.active.clear(); this.set(null); }
/** * 清理选区内容 * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/selection/index.ts#L69-L75
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
Selection.compose
public compose() { const active = this.active; if (active.size === 0) { this.set(null); return void 0; } let range: Range | null = null; active.forEach(key => { const delta = this.editor.deltaSet.get(key); if (!delta) return void 0; const deltaRange = Range.from(delta); range = range ? range.compose(deltaRange) : deltaRange; }); this.set(range); }
/** * 组合当前选区节点的 Range * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/selection/index.ts#L87-L101
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
dfs
const dfs = (delta: Delta) => { const state = this.getDeltaState(delta.id); if (!state) return void 0; delta.children.forEach(id => { const child = this.editor.deltaSet.get(id); if (!child) return void 0; // 按需创建`state`以及关联关系 const childState = new DeltaState(this.editor, child); this.deltas.set(id, childState); state.addChild(childState); dfs(childState.toDelta()); }); };
// 初始化构建整个`Delta`状态树
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/core/src/state/index.ts#L37-L49
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
DeltaSet.get
public get(key: string) { return this.deltas[key] || null; }
/** * 通过 key 获取 delta * @param key * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/delta/src/delta-set.ts#L33-L35
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
DeltaSet.has
public has(key: string) { return !!this.deltas[key]; }
/** * 判断是否存在目标 key * @param key * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/delta/src/delta-set.ts#L42-L44
8039ee4fdccac675dd43a1f153c36d1c3be72e86
CanvasEditor
github_2023
WindRunnerMax
typescript
DeltaSet.add
public add(delta: Delta, to?: string) { this.deltas[delta.id] = delta; delta.getDeltaSet = () => this; if (to) { const delta = this.get(to); delta && delta.insert(delta); } return this; }
/** * 添加目标 Delta 到 DeltaSet * @param delta 目标 Delta * @param to 目标 Delta 的父 Delta Id * @returns */
https://github.com/WindRunnerMax/CanvasEditor/blob/8039ee4fdccac675dd43a1f153c36d1c3be72e86/packages/delta/src/delta-set.ts#L52-L60
8039ee4fdccac675dd43a1f153c36d1c3be72e86
vnve
github_2023
vnve
typescript
Director.action
public async action(screenplay: Screenplay) { if (this.started) { return; } const now = performance.now(); try { const executors = this.parseScreenplay(screenplay); return await this.run(executors); } finally { this.reset(); log.info("action cost:", performance.now() - now); if (this.cutResolver) { this.cutResolver(true); } } }
// action!
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/director/Director.ts#L177-L194
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
Director.cut
public cut() { return new Promise((resolve) => { this.started = false; this.cutResolver = resolve; }); }
// cut!
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/director/Director.ts#L197-L202
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
Speak.fadeIn
private fadeIn(fromText: string, toText: string) { gsap.fromTo( this.target, { pixi: { alpha: 0, }, text: { value: fromText, }, }, { pixi: { alpha: 1, }, text: { value: toText, }, duration: 0.5, ease: "none", }, ); }
// TODO: 优化效果
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/director/directives/animation/Speak.ts#L118-L140
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.fromBuffer
static fromBuffer( buffer: ArrayBuffer, options?: Partial<AnimatedGIFOptions>, ) { if (!buffer || buffer.byteLength === 0) { throw new Error("Invalid buffer"); } // fix https://github.com/matt-way/gifuct-js/issues/30 const validateAndFix = (gif: any): void => { let currentGce = null; for (const frame of gif.frames) { currentGce = frame.gce ?? currentGce; // fix loosing graphic control extension for same frames if ("image" in frame && !("gce" in frame)) { frame.gce = currentGce; } } }; const gif = parseGIF(buffer); validateAndFix(gif); const gifFrames = decompressFrames(gif, true); const frames: FrameObject[] = []; // Temporary canvases required for compositing frames const canvas = document.createElement("canvas"); const context = canvas.getContext("2d", { willReadFrequently: true, }) as CanvasRenderingContext2D; const patchCanvas = document.createElement("canvas"); const patchContext = patchCanvas.getContext( "2d", ) as CanvasRenderingContext2D; canvas.width = gif.lsd.width; canvas.height = gif.lsd.height; let time = 0; let previousFrame: ImageData | null = null; // Some GIFs have a non-zero frame delay, so we need to calculate the fallback const { fps } = Object.assign({}, AnimatedGIF.defaultOptions, options); const defaultDelay = 1000 / (fps as number); // Precompute each frame and store as ImageData for (let i = 0; i < gifFrames.length; i++) { // Some GIF's omit the disposalType, so let's assume clear if missing const { disposalType = 2, delay = defaultDelay, patch, dims: { width, height, left, top }, } = gifFrames[i] as ParsedFrame; patchCanvas.width = width; patchCanvas.height = height; patchContext.clearRect(0, 0, width, height); const patchData = patchContext.createImageData(width, height); patchData.data.set(patch); patchContext.putImageData(patchData, 0, 0); if (disposalType === 3) { previousFrame = context.getImageData(0, 0, canvas.width, canvas.height); } context.drawImage(patchCanvas, left, top); const imageData = context.getImageData(0, 0, canvas.width, canvas.height); if (disposalType === 2) { context.clearRect(0, 0, canvas.width, canvas.height); } else if (disposalType === 3) { context.putImageData(previousFrame as ImageData, 0, 0); } frames.push({ start: time, end: time + delay, imageData, }); time += delay; } // clear the canvases canvas.width = canvas.height = 0; patchCanvas.width = patchCanvas.height = 0; const { width, height } = gif.lsd; return { frames, width, height, }; }
/** * Create an animated GIF animation from a GIF image's ArrayBuffer. The easiest way to get * the buffer is to use Assets. * @example * import { Assets } from 'pixi.js'; * import '@pixi/gif'; * * const gif = await Assets.load('file.gif'); * @param buffer - GIF image arraybuffer from Assets. * @param options - Options to use. * @returns */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L189-L286
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
validateAndFix
const validateAndFix = (gif: any): void => { let currentGce = null; for (const frame of gif.frames) { currentGce = frame.gce ?? currentGce; // fix loosing graphic control extension for same frames if ("image" in frame && !("gce" in frame)) { frame.gce = currentGce; } } };
// fix https://github.com/matt-way/gifuct-js/issues/30
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L198-L209
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.constructor
constructor(options: Partial<AnimatedGIFOptions>) { super(Texture.EMPTY); // TODO: perf增加自定义选项 // Get the options, apply defaults this.name = uuid(); this.label = ""; this.type = "AnimatedGIF"; this.source = options.source!; this.assetID = 0; this.assetType = ""; this._frames = []; // eslint-disable-next-line @typescript-eslint/no-explicit-any this._context = null as any; }
/** * @param options - Options for the AnimatedGIF */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L291-L306
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.stop
public stop(): void { if (!this._playing) { return; } this._playing = false; if (this._autoUpdate && this._isConnectedToTicker) { Ticker.shared.remove(this.update, this); this._isConnectedToTicker = false; } }
/** Stops the animation. */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L339-L349
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.play
public play(): void { if (this._playing) { return; } this._playing = true; if (this._autoUpdate && !this._isConnectedToTicker) { Ticker.shared.add(this.update, this, UPDATE_PRIORITY.HIGH); this._isConnectedToTicker = true; } // If were on the last frame and stopped, play should resume from beginning if (!this.loop && this.currentFrame === this._frames.length - 1) { this._currentTime = 0; } }
/** Plays the animation. */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L352-L367
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.progress
public get progress(): number { return this._currentTime / this.duration; }
/** * Get the current progress of the animation from 0 to 1. * @readonly */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L373-L375
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.playing
public get playing(): boolean { return this._playing; }
/** `true` if the current animation is playing */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L378-L380
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.update
update(deltaTime: number): void { if (!this._playing) { return; } // const elapsed = // (this.animationSpeed * deltaTime) / (settings.TARGET_FPMS as number); // const currentTime = this._currentTime + elapsed; // eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore const currentTime = Ticker.shared.time * 1000; const localTime = currentTime % this.duration; const localFrame = this._frames.findIndex( (frame) => frame.start <= localTime && frame.end > localTime, ); if (currentTime >= this.duration) { if (this.loop) { this._currentTime = localTime; this.updateFrameIndex(localFrame); this.onLoop?.(); } else { this._currentTime = this.duration; this.updateFrameIndex(this._frames.length - 1); this.onComplete?.(); this.stop(); } } else { this._currentTime = localTime; this.updateFrameIndex(localFrame); } }
/** * Updates the object transform for rendering. You only need to call this * if the `autoUpdate` property is set to `false`. * * @param deltaTime - Time since last tick. */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L388-L420
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.updateFrame
private updateFrame(): void { if (!this.dirty) { return; } // Update the current frame const { imageData } = this._frames[this._currentFrame] as FrameObject; this._context.putImageData(imageData, 0, 0); // Workaround hack for Safari & iOS // which fails to upload canvas after putImageData // See: https://bugs.webkit.org/show_bug.cgi?id=229986 this._context.fillStyle = "transparent"; this._context.fillRect(0, 0, 0, 1); this.texture.update(); // Mark as clean this.dirty = false; }
/** * Redraw the current frame, is necessary for the animation to work when */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L425-L445
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF._render
_render(renderer: Renderer): void { this.updateFrame(); super._render(renderer); }
/** * Renders the object using the WebGL renderer * * @param {PIXI.Renderer} renderer - The renderer * @private */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L453-L457
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF._renderCanvas
_renderCanvas(renderer: any): void { this.updateFrame(); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore super._renderCanvas(renderer); }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L466-L472
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.autoUpdate
get autoUpdate(): boolean { return this._autoUpdate; }
/** * Whether to use PIXI.Ticker.shared to auto update animation time. * @default true */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L478-L480
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.currentFrame
get currentFrame(): number { return this._currentFrame; }
/** Set the current frame number */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L501-L503
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.updateFrameIndex
private updateFrameIndex(value: number): void { if (value < 0 || value >= this._frames.length) { throw new Error( `Frame index out of range, expecting 0 to ${this.totalFrames}, got ${value}`, ); } if (this._currentFrame !== value) { this._currentFrame = value; this.dirty = true; this.onFrameChange?.(value); } }
/** Internally handle updating the frame index */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L510-L521
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.totalFrames
get totalFrames(): number { return this._frames.length; }
/** * Get the total number of frame in the GIF. */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L526-L528
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
AnimatedGIF.destroy
destroy(): void { this.stop(); super.destroy(true); // eslint-disable-next-line @typescript-eslint/no-explicit-any const forceClear = null as any; this._context = forceClear; this._frames = forceClear; this.onComplete = forceClear; this.onFrameChange = forceClear; this.onLoop = forceClear; }
/** Destroy and don't use after this. */
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/AnimatedGIF.ts#L531-L543
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
Graphics.load
public async load() { // noop }
// 用于存储颜色值,仅给选择器展示使用
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/core/src/scene/child/Graphics.ts#L11-L13
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
vnve
github_2023
vnve
typescript
onInsert
const onInsert = (value: TDirectiveValue) => { tf.insert.directive({ value }); // move the selection after the element moveSelection(editor, { unit: "offset" }); api.floatingDirective.hide(); // ?? setTimeout(() => { focusEditor(editor, editor.selection!); }, 0); };
// TODO: hotkeys
https://github.com/vnve/vnve/blob/f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0/packages/editor/src/components/plugin/directive/useFloatingDirective.ts#L99-L110
f6f15c317886d8b422fca2b0efeb0fc90b2eb1a0
LawKnowledge
github_2023
foxminchan
typescript
CaseInsensitiveFilterPlugin
function CaseInsensitiveFilterPlugin(): { fn: { opsFilter: ( taggedOps: { filter: ( argument: (_tagObject: unknown, tag: string) => boolean, ) => unknown; }, phrase: string, ) => { filter: ( argument: (_tagObject: unknown, tag: string) => boolean, ) => unknown; }; }; } { return { fn: { opsFilter: ( taggedOps: { filter: ( argument: (_tagObject: unknown, tag: string) => boolean, ) => unknown; }, phrase: string, ) => { return taggedOps.filter((_tagObject: unknown, tag: string): boolean => tag.toLowerCase().includes(phrase.toLowerCase()), ) as { filter: ( argument: (_tagObject: unknown, tag: string) => boolean, ) => unknown; }; }, }, }; }
/* * Copyright (c) 2023-present Hutech University. All rights reserved * Licensed under the MIT License */
https://github.com/foxminchan/LawKnowledge/blob/f7f1dc8ab7b1dc71ecb356e3a2de0b1b2a035be9/libs/building-block/src/frameworks/swagger/swagger.plugin.ts#L6-L42
f7f1dc8ab7b1dc71ecb356e3a2de0b1b2a035be9
goldrush-kit
github_2023
covalenthq
typescript
Some.constructor
constructor(private value: A) {}
// eslint-disable-next-line no-empty-function
https://github.com/covalenthq/goldrush-kit/blob/e85ca98d815149f2ba32d7ae5b89f4b9eaa1e6e1/src/utils/option.ts#L56-L56
e85ca98d815149f2ba32d7ae5b89f4b9eaa1e6e1
clash-verge-rev
github_2023
clash-verge-rev
typescript
filterProxies
function filterProxies( proxies: IProxyItem[], groupName: string, filterText: string ) { if (!filterText) return proxies; const res1 = regex1.exec(filterText); if (res1) { const symbol = res1[1]; const symbol2 = res1[2].toLowerCase(); const value = symbol2 === "error" ? 1e5 : symbol2 === "timeout" ? 3000 : +symbol2; return proxies.filter((p) => { const delay = delayManager.getDelayFix(p, groupName); if (delay < 0) return false; if (symbol === "=" && symbol2 === "error") return delay >= 1e5; if (symbol === "=" && symbol2 === "timeout") return delay < 1e5 && delay >= 3000; if (symbol === "=") return delay == value; if (symbol === "<") return delay <= value; if (symbol === ">") return delay >= value; return false; }); } const res2 = regex2.exec(filterText); if (res2) { const type = res2[1].toLowerCase(); return proxies.filter((p) => p.type.toLowerCase().includes(type)); } return proxies.filter((p) => p.name.includes(filterText.trim())); }
/** * filter the proxy * according to the regular conditions */
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/components/proxy/use-filter-sort.ts#L60-L95
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
clash-verge-rev
github_2023
clash-verge-rev
typescript
sortProxies
function sortProxies( proxies: IProxyItem[], groupName: string, sortType: ProxySortType ) { if (!proxies) return []; if (sortType === 0) return proxies; const list = proxies.slice(); if (sortType === 1) { list.sort((a, b) => { const ad = delayManager.getDelayFix(a, groupName); const bd = delayManager.getDelayFix(b, groupName); if (ad === -1 || ad === -2) return 1; if (bd === -1 || bd === -2) return -1; return ad - bd; }); } else { list.sort((a, b) => a.name.localeCompare(b.name)); } return list; }
/** * sort the proxy */
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/components/proxy/use-filter-sort.ts#L100-L125
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
clash-verge-rev
github_2023
clash-verge-rev
typescript
activateSelected
const activateSelected = async () => { const proxiesData = await getProxies(); const profileData = await getProfiles(); if (!profileData || !proxiesData) return; const current = profileData.items?.find( (e) => e && e.uid === profileData.current ); if (!current) return; // init selected array const { selected = [] } = current; const selectedMap = Object.fromEntries( selected.map((each) => [each.name!, each.now!]) ); let hasChange = false; const newSelected: typeof selected = []; const { global, groups } = proxiesData; [global, ...groups].forEach(({ type, name, now }) => { if (!now || type !== "Selector") return; if (selectedMap[name] != null && selectedMap[name] !== now) { hasChange = true; updateProxy(name, selectedMap[name]); } newSelected.push({ name, now: selectedMap[name] }); }); if (hasChange) { patchProfile(profileData.current!, { selected: newSelected }); mutate("getProxies", getProxies()); } };
// 根据selected的节点选择
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/hooks/use-profiles.ts#L28-L64
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
clash-verge-rev
github_2023
clash-verge-rev
typescript
generateItem
const generateItem = (name: string) => { if (proxyRecord[name]) return proxyRecord[name]; if (providerMap[name]) return providerMap[name]; return { name, type: "unknown", udp: false, xudp: false, tfo: false, mptcp: false, smux: false, history: [], }; };
// compatible with proxy-providers
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/services/api.ts#L116-L129
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
clash-verge-rev
github_2023
clash-verge-rev
typescript
DelayManager.getDelayFix
getDelayFix(proxy: IProxyItem, group: string) { if (!proxy.provider) { const delay = this.getDelay(proxy.name, group); if (delay >= 0 || delay === -2) return delay; } if (proxy.history.length > 0) { // 0ms以error显示 return proxy.history[proxy.history.length - 1].delay || 1e6; } return -1; }
/// 暂时修复provider的节点延迟排序的问题
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/services/delay.ts#L59-L70
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
clash-verge-rev
github_2023
clash-verge-rev
typescript
URI_VLESS
function URI_VLESS(line: string): IProxyVlessConfig { line = line.split("vless://")[1]; let isShadowrocket; let parsed = /^(.*?)@(.*?):(\d+)\/?(\?(.*?))?(?:#(.*?))?$/.exec(line)!; if (!parsed) { let [_, base64, other] = /^(.*?)(\?.*?$)/.exec(line)!; line = `${atob(base64)}${other}`; parsed = /^(.*?)@(.*?):(\d+)\/?(\?(.*?))?(?:#(.*?))?$/.exec(line)!; isShadowrocket = true; } let [__, uuid, server, portStr, ___, addons = "", name] = parsed; if (isShadowrocket) { uuid = uuid.replace(/^.*?:/g, ""); } const port = parseInt(portStr, 10); uuid = decodeURIComponent(uuid); name = decodeURIComponent(name); const proxy: IProxyVlessConfig = { type: "vless", name: "", server, port, uuid, }; const params: Record<string, string> = {}; for (const addon of addons.split("&")) { const [key, valueRaw] = addon.split("="); const value = decodeURIComponent(valueRaw); params[key] = value; } proxy.name = trimStr(name) ?? trimStr(params.remarks) ?? trimStr(params.remark) ?? `VLESS ${server}:${port}`; proxy.tls = (params.security && params.security !== "none") || undefined; if (isShadowrocket && /TRUE|1/i.test(params.tls)) { proxy.tls = true; params.security = params.security ?? "reality"; } proxy.servername = params.sni || params.peer; proxy.flow = params.flow ? "xtls-rprx-vision" : undefined; proxy["client-fingerprint"] = params.fp as ClientFingerprint; proxy.alpn = params.alpn ? params.alpn.split(",") : undefined; proxy["skip-cert-verify"] = /(TRUE)|1/i.test(params.allowInsecure); if (["reality"].includes(params.security)) { const opts: IProxyVlessConfig["reality-opts"] = {}; if (params.pbk) { opts["public-key"] = params.pbk; } if (params.sid) { opts["short-id"] = params.sid; } if (Object.keys(opts).length > 0) { proxy["reality-opts"] = opts; } } let httpupgrade = false; proxy["ws-opts"] = { headers: undefined, path: undefined, }; proxy["http-opts"] = { headers: undefined, path: undefined, }; proxy["grpc-opts"] = {}; if (params.headerType === "http") { proxy.network = "http"; } else if (params.type === "ws") { proxy.network = "ws"; httpupgrade = true; } else { proxy.network = "tcp"; } if (!proxy.network && isShadowrocket && params.obfs) { switch (params.type) { case "sw": proxy.network = "ws"; break; case "http": proxy.network = "http"; break; case "h2": proxy.network = "h2"; break; case "grpc": proxy.network = "grpc"; break; default: { } } } if (["websocket"].includes(proxy.network)) { proxy.network = "ws"; } if (proxy.network && !["tcp", "none"].includes(proxy.network)) { const opts: Record<string, any> = {}; const host = params.host ?? params.obfsParam; if (host) { if (params.obfsParam) { try { const parsed = JSON.parse(host); opts.headers = parsed; } catch (e) { opts.headers = { Host: host }; } } else { opts.headers = { Host: host }; } } if (params.path) { opts.path = params.path; } if (httpupgrade) { opts["v2ray-http-upgrade"] = true; opts["v2ray-http-upgrade-fast-open"] = true; } if (Object.keys(opts).length > 0) { proxy[`ws-opts`] = opts; } } if (proxy.tls && !proxy.servername) { if (proxy.network === "ws") { proxy.servername = proxy["ws-opts"]?.headers?.Host; } else if (proxy.network === "http") { let httpHost = proxy["http-opts"]?.headers?.Host; proxy.servername = Array.isArray(httpHost) ? httpHost[0] : httpHost; } } return proxy; }
/** * VLess URL Decode. */
https://github.com/clash-verge-rev/clash-verge-rev/blob/3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224/src/utils/uri-parser.ts#L498-L640
3ea0d20e2cf7cf08c7e8e8c098ff725c4ea92224
meditron
github_2023
epfLLM
typescript
PuppeteerRun.setup
static async setup(headless_b:boolean):Promise<PuppeteerRun>{ const headless= headless_b ? "new":headless_b; const browser=await puppeteer.launch({ headless: headless }); const page = await browser.newPage(); page.setViewport({ width: 800, height: 600 }); const cursor = createCursor(page); await page.goto(TOC_URL); await page.waitForTimeout(TIMEOUT); if (VERBOSE){console.log("Reached table of contents at URL: ",TOC_URL,"\n");} return new PuppeteerRun(page,browser,cursor); }
/* ==================== HELPER FUNCTIONS ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/mayo/src/index.ts#L60-L70
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.getSectionContent
async getSectionContent(section_url:string){ await this.page.goto(section_url); this.page.waitForTimeout(TIMEOUT); // Select content on page (try two different formats) let base_sel = ''; if (await this.check_sel('div.content')){ base_sel = 'div.content'; } else { base_sel = 'div.aem-GridColumn section'; } let selectors = []; for (let subsel of CONTENT_SUBSELECTORS){ selectors.push(base_sel+' '+subsel); } if (selectors.length == 0){ console.log("Couldn't find content selector for page") return ''; } let content_selector = selectors.join(', '); //console.log('\tContent selector: ', content_selector) const sections = await this.page.$$(content_selector); // Construct section content let section_content = ''; for (let [index, el] of sections.entries()) { const tag = await this.page.evaluate(el => el.tagName, el); const text = await this.page.evaluate(el => el.textContent?.trim(), el); // Filtering out ads and other stuff if (text == ''){continue;} const parentPath = await this.page.evaluate(el => { let path = ''; let parent = el.parentElement; while (parent != null){ path += parent.tagName+'.'+parent.className+' '; parent = parent.parentElement; } return path; }, el); if (parentPath.match(/DIV\.content.*DIV\.content/)){continue;} const toAvoid = ['references', 'acces-list-container', 'tableofcontents'] if (toAvoid.some(x=>parentPath.match(x))){continue;} // Formatting text depending on tag //console.log('Tag: ',tag,'\nParent path: ', parentPath, '\nText: ', text,'\n') if (tag == 'H2'){ section_content += '\n ' + text; } else if (tag == 'LI'){ section_content += '\n- ' + text; } else if (tag == 'P'){ section_content += '\n' + text; } } return section_content; }
/* ==================== GUIDELINE EXTRACTOR ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/mayo/src/index.ts#L93-L151
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.scrape
async scrape(){ var all_good = true; try { // Iterate over each letter for (let letter='A'; letter<='Z'; letter=String.fromCharCode(letter.charCodeAt(0)+1)){ const letter_URL = TOC_URL+'?letter='+letter; await this.page.goto(letter_URL); await this.page.waitForTimeout(TIMEOUT); console.log(`\nLetter: ${letter}\nURL: ${letter_URL}\n`) // For each letter, get all links to guidelines starting with that letter if (await this.check_sel(TOC_RESULT_ITEM_SELECTOR)){ let toc_links = await this.get_links(TOC_RESULT_ITEM_SELECTOR); for (let [toc_index, el] of toc_links.entries()) { const page_name = el[0]!; const page_url = el[1]!; console.log(`\nGuideline ${toc_index} of ${toc_links.length}:\nName: ${page_name}\nURL: ${page_url}\n`); // For each guideline, try to scrape it 3 times before giving up for (let i=0; i<3; i++){ try { await this.page.goto(page_url); const guideline = await this.getGuideline(page_name, page_url); this.save_guideline(guideline, OUTPUT_PATH); console.log('\tSaved guideline!\n') break; } catch(e) { console.log('\tError while scraping guideline, retrying...\n', e) this.page.waitForTimeout(10000); } } } } } } catch(e) { console.log(e); all_good=false; } return all_good; }
/* ==================== SCRAPING FUNCTION ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/mayo/src/index.ts#L175-L216
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
run
async function run(){ const run = await PuppeteerRun.setup(HEADLESS); let all_good = await run.scrape(); if (all_good){ try { await run.browser.close(); } catch(e) { console.log("Error while closing",e); } } }
/* ==================== MAIN ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/mayo/src/index.ts#L221-L232
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.setup
static async setup(headless_b:boolean):Promise<PuppeteerRun>{ const headless= headless_b ? "new":headless_b; const browser=await puppeteer.launch({ headless: headless }); const page = await browser.newPage(); page.setViewport({ width: 800, height: 600 }); const cursor = createCursor(page); await page.goto(TOC_URL); await page.waitForTimeout(TIMEOUT); if (VERBOSE){console.log("Reached table of contents at URL: ",TOC_URL,"\n");} return new PuppeteerRun(page,browser,cursor); }
/* ==================== HELPER FUNCTIONS ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/nice/src/index.ts#L63-L73
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.getSectionContent
async getSectionContent(section_name:string, section_url:string){ await this.page.goto(section_url); let section_content = ''; let content_selector = CONTENT_SELECTOR; if (section_name == 'Context') { content_selector = 'div.chapter p' } const elements = (await this.page.$$(content_selector)); for (let el of elements) { const tag = await this.page.evaluate(el => el.tagName, el); let text = await this.page.evaluate(el => el.textContent, el); let formatted_text = text?.trim().replace(/^\d+(\.\d+)*\s*/, '') if (tag == 'H3'){ section_content += '\n\n# ' + formatted_text; } else if (tag == 'H4'){ section_content += '\n\n## ' + formatted_text; } else if (tag == 'P'){ section_content += '\n' + formatted_text; } } section_content = section_content.replace(/\[\d+\]/g, '').replace(/^\n+/, ''); return section_content; }
/* ==================== GUIDELINE EXTRACTOR ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/nice/src/index.ts#L100-L124
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.scrape
async scrape(){ var all_good = true; try { if (await this.check_sel(TOC_RESULT_ITEM_SELECTOR)){ let toc_links = await this.get_links(TOC_RESULT_ITEM_SELECTOR); for (let [toc_index, el] of toc_links.entries()) { const page_name = el[0]!; const page_url = el[1]!; console.log(`\nGuideline ${toc_index} of ${toc_links.length}:\nName: ${page_name}\nURL: ${page_url}\n`); const guideline = await this.getGuideline(page_name, page_url); this.save_guideline(guideline, OUTPUT_PATH); this.page.waitForTimeout(TIMEOUT); } } } catch(e) { console.log(e); all_good=false; } return all_good; }
/* ==================== SCRAPING FUNCTION ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/nice/src/index.ts#L151-L171
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
run
async function run(){ const run = await PuppeteerRun.setup(HEADLESS); let all_good = await run.scrape(); if (all_good){ try { await run.browser.close(); } catch(e) { console.log("Error while closing",e); } } }
/* ==================== MAIN ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/nice/src/index.ts#L176-L187
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.setup
static async setup(headless_b:boolean,timeout:number):Promise<PuppeteerRun>{ const headless= headless_b ? "new":headless_b; const browser=await puppeteer.launch({ headless: headless }); const page = await browser.newPage(); page.setViewport({ width: 800, height: 600 }); const cursor = createCursor(page); await page.goto(TOC_URL); await page.waitForTimeout(timeout); return new PuppeteerRun(page,browser,cursor); }
/* ==================== HELPER FUNCTIONS ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/rch/src/index.ts#L59-L68
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.getGuideline
async getGuideline(name:string,url:string){ await this.page.goto(url); await this.page.waitForTimeout(200); let content = ''; let sections = await this.page.$$(CONTENT_SELECTOR); // If there is a section with id 'key-points', start from there const key_selector = 'div.widgetBody #key-points' let skip = await this.check_sel(key_selector); for (let el of sections) { const tag = await this.page.evaluate((el:any) => el.tagName, el); let text = await this.page.evaluate((el:any) => el.innerText.trim(), el); const id = await this.page.evaluate((el:any) => el.id, el); // Skip until key-points if present if (skip && id != 'key-points'){continue;} skip = false; // Skip if sub-contained in a table const parentPath = await this.getParentPath(el); if (parentPath.match(/TABLE\.table/)){continue;} // Replace double spaces (not newlines) by single space if present text = text.replace(/ {2}/g, " "); // Remove asterisks text = text.replace(/\*/g, ''); // Skip empty text if (text == ''){continue;} // Sublists are matched twice, skip them if (parentPath.match(/LI.*LI/)){ continue; } // If we reached Last updated or References or Additional notes, stop if (text.match(/^Last updated/)){break;} if (tag == 'H2' && text.match(/References/)){break;} if (tag == 'H2' && text.match(/Additional/)){break;} if (tag == 'H2' && text.match(/Parent information/)){break;} // Formatting text depending on tag if (tag == 'H2'){ content += '\n\n# ' + text; } else if (tag == 'H3'){ content += '\n\n## ' + text; } else if (tag == 'LI'){ if (text.match(/\n/)){ text = text.replace(/\n/g, '\n\t- '); } content += '\n- '+text; } else if (tag == 'P'){ content += '\n' + text; } } content = content.trim(); //console.log('\n\n\nContent:\n',content,'\n\n\n') let guideline = new Guideline(name, url, content); await this.page.goto(TOC_URL); return guideline; }
/* ==================== GUIDELINE EXTRACTOR ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/rch/src/index.ts#L96-L163
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.scrape
async scrape(){ await this.page.waitForTimeout(500); let links = await this.get_links(TOC_SELECTOR); let num_links = links.length; for (let [idx, el] of links.entries()) { const name = el[0]!.split(' (see')[0]; const url = el[1]!; if (name in scraped){continue;} console.log(`\nGuideline ${idx} of ${num_links}:\nName: ${name}\nURL: ${url}\n`); for (let i=0; i<3; i++){ try{ let guideline = await this.getGuideline(name, url); await this.save_guideline(guideline, OUTPUT_PATH); break; } catch(e){ console.log(`Error: ${e}\nTrying again...`); } } } }
/* ==================== SCRAPING FUNCTION ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/rch/src/index.ts#L167-L189
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
run
async function run(){ const run = await PuppeteerRun.setup(HEADLESS, 200); await run.page.click(`a[href="#tab-All"]`); await run.scrape(); }
/* ==================== MAIN ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/rch/src/index.ts#L194-L199
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.setup
static async setup(headless_b:boolean):Promise<PuppeteerRun>{ const headless= headless_b ? "new":headless_b; const browser=await puppeteer.launch({ headless: headless }); const page = await browser.newPage(); page.setViewport({ width: 800, height: 600 }); const cursor = createCursor(page); await page.goto(TOC_URL); await page.waitForTimeout(TIMEOUT); if (VERBOSE){console.log("Reached table of contents at URL: ",TOC_URL,"\n");} return new PuppeteerRun(page,browser,cursor); }
/* ==================== HELPER FUNCTIONS ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/wikidoc/src/index.ts#L63-L73
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.formatContent
async formatContent(){ let elements = (await this.page.$$(CONTENT_SELECTOR)); let content = ''; // If there is a TOC, skip all elements until first h2 after 'Contents' for (let el of elements) { let tag = (await this.page.evaluate(el => el.tagName, el)); let text = (await this.page.evaluate(el => el.textContent, el))?.trim(); // Skip children of table of contents or table let parent_path = await this.page.evaluate(el => { let path = ''; let parent = el.parentElement; while (parent != null){ path += parent.tagName+'.'+parent.id + ' '; parent = parent.parentElement; } return path; }, el); if (parent_path.match(/DIV.toc/) || parent_path.match(/TABLE/)){ continue; } //console.log('Tag: '+tag+'\nPath: '+parent_path+'\nText: '+text+'\n') if (tag == 'H1' || tag == 'H2' || tag == 'H3' || tag == 'H4') { if (text === 'References' || text?.startsWith('See also')){ break; } } if (tag == 'H1'){ content += '\n\n# ' + text; } else if (tag == 'H2'){ content += '\n\n# ' + text; } else if (tag == 'H3'){ content += '\n\n## ' + text; } else if (tag == 'H4'){ content += '\n\n### ' + text; } else if (tag == 'P'){ if (parent_path.match(/LI/)){ continue; } text = text?.replace(/^\|.*$/gm, ''); text = text?.replace(/^\{\{.*$/gm, ''); text = text?.replace(/^\}\}.*$/gm, ''); text = text?.replace(/^\s*[\r\n]/gm, ''); if (text != null && text != ''){ content += '\n' + text; } } else if (tag == 'LI'){ content += '\n- ' + text; } } content = content.trim(); //console.log('\n\n=========================\n\n'+content+'\n\n=========================\n\n') return content; }
/* ==================== ARTICLE EXTRACTOR ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/wikidoc/src/index.ts#L103-L162
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
PuppeteerRun.scrape
async scrape(toc_url:string){ try { await this.page.goto(toc_url); await this.page.waitForTimeout(TIMEOUT); let article_links = await this.get_links(TOC_SELECTOR); for (let i = 0; i < article_links.length; i++) { const article_link = article_links[i]; const article_name = article_link[0]; const article_url = article_link[1]; if (article_name == null || article_url! in SCRAPED_URLs) {continue;} console.log(`\n\tArticle (${i+1} / ${article_links.length}):\n\tName: ${article_name}\n\tURL: ${article_url}`) await this.scrapeArticle(article_url!); SCRAPED_URLs.push(article_url!); await fs.appendFileSync(SCRAPED_PATH, article_url+'\n'); } } catch (e) { console.error(e); } }
/* ==================== SCRAPING FUNCTION ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/wikidoc/src/index.ts#L188-L208
a7c7cda3014e537f0df2ec58f836fbe920d6283b
meditron
github_2023
epfLLM
typescript
run
async function run(){ const run = await PuppeteerRun.setup(HEADLESS); // Get TOC pages var toc_urls:string[] = []; if (!fs.existsSync(TOC_PATH)) { console.log('Scraping all TOC pages...') toc_urls = await run.getAllPages([]); console.log('\nSaving TOC URLs to file...') for (let i = 0; i < toc_urls.length; i++) { const toc_url = toc_urls[i]; await fs.appendFileSync(TOC_PATH, toc_url+'\n'); } } else { toc_urls = fs.readFileSync(TOC_PATH, 'utf8').split('\n'); console.log(`Loaded ${toc_urls.length} TOC pages`) } // Check for already scraped pages and articles if (fs.existsSync(SCRAPED_PATH) && fs.existsSync(OUTPUT_PATH)) { SCRAPED_URLs = fs.readFileSync(SCRAPED_PATH, 'utf8').split('\n'); console.log(`Already scraped ${SCRAPED_URLs.length} articles`) } // Scrape all remaining articles console.log(`Scraping ${toc_urls.length} TOC pages.`) for (let i = 0; i < toc_urls.length; i++) { const toc_url = toc_urls[i]; console.log(`Page (${i+1} / ${toc_urls.length}):`) await run.scrape(toc_url); } }
/* ==================== MAIN ==================== */
https://github.com/epfLLM/meditron/blob/a7c7cda3014e537f0df2ec58f836fbe920d6283b/gap-replay/guidelines/scrapers/wikidoc/src/index.ts#L213-L245
a7c7cda3014e537f0df2ec58f836fbe920d6283b
bangumi
github_2023
xiaoyvyv
typescript
optContentJs
function optContentJs(content: HTMLElement | undefined | null) { if (!content) return; // 图片处理 const images = content.querySelectorAll("img"); const imageUrls: String[] = []; for (let i = 0; i < images.length; i++) { const imageEl = images[i]; const imageSrc = imageEl.src; if (imageSrc != undefined && imageSrc.length > 0 && imageSrc.indexOf("/img/smiles") == -1) { imageUrls.push(imageSrc); imageEl.onclick = () => { if (window.android) { window.android.onPreviewImage(imageSrc, imageUrls); } } } } // 遮罩交互处理 content.querySelectorAll("span.text_mask").forEach(item => { const mask = item as HTMLElement; mask.onclick = (event) => { event.preventDefault(); // 开关遮罩 toggleMask(event.currentTarget as HTMLElement); } }); }
/** * 针对特定的节点进行交互优化 * * @param content */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L16-L45
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
optReplyItemClick
const optReplyItemClick = (element: HTMLElement): boolean => { // 点击 Mask 文案 if (toggleMask(element)) { return true; } // a 标签点击 const tagName = element.tagName.toLowerCase(); if (tagName == "a") return true; // 图片标签点击 if (tagName == "img" && window.android) { const img = element as HTMLImageElement; // 表情不预览 if (img.getAttribute('smileid') == null) { window.android.onPreviewImage(img.src, [img.src]); } return true } // 其它元素点击不拦截 return false; };
/** * 优化评论条目点击事件,是否拦截 * * @param element */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L52-L74
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
optReplyContent
const optReplyContent = (userName: string, replyContent: string): string => { let reply_to_content = replyContent .replace(/<div class="quote">([^^]*?)<\/div>/, '') .replace(/<span class="text_mask" style="([^^]*?)">([^^]*?)<\/span>/, '') .replace(/<\/?[^>]+>/g, '') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/\B@([^\W_]\w*)\b/g, '@$1'); if (reply_to_content.length > 100) { reply_to_content = reply_to_content.slice(0, 100) + '...'; } return '[quote][b]' + userName + '[/b] 说: ' + reply_to_content + '[/quote]'; }
/** * 优化回复内容,剔除重复的引用,并重新添加引用 * * @param userName * @param replyContent */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L134-L147
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
optText
const optText = (text: string | null | undefined) => { return (text || '').trim() .replace(/&nbsp;/g, " ").trim() }
/** * 优化文案 * * @param text */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L154-L157
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
initComment
const initComment = (handEmojis: ((commentId: string, likeActionInfo: LikeActionEntity[]) => void) | null, comments: () => CommentTreeEntity[], onChangeSort: (sort: string) => void) => { const refreshMainComment = (mainComment: CommentReplyMainContent) => { for (const postId in mainComment) { const post = mainComment[postId]; let hasTargetMainComment = false; // 判断是否存在评论 comments().forEach((item) => { if (item.id == postId) hasTargetMainComment = true }); // 不包含待添加的主评论,直接添加到第一条 if (!hasTargetMainComment) { const mainCommentId = post.pst_id; const mainCommentUid = post.pst_uid; // 转换模型 const newMainComment = replyCommentToTreeComment(post, mainCommentId, mainCommentUid, false); // 添加到头部 comments().unshift(newMainComment); } } } const refreshSubComment = (subComment: CommentReplySubContent) => { for (const postId in subComment) { const posts = subComment[postId]; let targetMainComment: CommentTreeEntity | null = null; comments().forEach((item) => { if (item.id == postId) { targetMainComment = item; } }); // 刷新目标主评论的子评论 if (targetMainComment != null) { const comment = targetMainComment as CommentTreeEntity; const mainCommentId = comment.id; const mainCommentUid = comment.userId; const mainCommentSubReplyCommentIds = comment.topicSubReply.map(item => item.id); // 转换模型、并且过滤掉已经存在的子条目 const newComments = posts .map(post => replyCommentToTreeComment(post, mainCommentId, mainCommentUid, true)) .filter(item => !mainCommentSubReplyCommentIds.includes(item.id)); // 添加 comment.topicSubReply.push(...newComments); } } } // 添加评论 const addComment = (comment: CommentReplyEntity) => { // 主评论 const main = comment.posts?.main; if (main != undefined) { refreshMainComment(main); } // 子评论 const sub = comment.posts?.sub; if (sub != undefined) { refreshSubComment(sub); } } // 刷新贴贴 // 数据结构:Map<CommentId: List<LikeAction>> 结构 const refreshEmoji = (likeData: any) => { console.log("刷新贴贴:" + JSON.stringify(likeData, null, 2)); for (const commendId in likeData) { const likeActionInfo = likeData[commendId] as LikeActionEntity[]; // 外部处理 handEmojis && handEmojis(commendId, likeActionInfo); comments().forEach(comment => { // 主评论查询到则刷新 if (comment.id == commendId) { comment.emojis = likeActionInfo || []; } comment.topicSubReply.forEach(sub => { // 子评论查询到则刷新 if (sub.id == commendId) { sub.emojis = likeActionInfo || []; } }); }); } } window.comment = { addComment: addComment, refreshEmoji: refreshEmoji, changeSort: onChangeSort, } as Comment }
/** * 初始化评论发布填充逻辑 * * @param handEmojis * @param comments * @param onChangeSort */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L170-L270
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
addComment
const addComment = (comment: CommentReplyEntity) => { // 主评论 const main = comment.posts?.main; if (main != undefined) { refreshMainComment(main); } // 子评论 const sub = comment.posts?.sub; if (sub != undefined) { refreshSubComment(sub); } }
// 添加评论
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L225-L237
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
refreshEmoji
const refreshEmoji = (likeData: any) => { console.log("刷新贴贴:" + JSON.stringify(likeData, null, 2)); for (const commendId in likeData) { const likeActionInfo = likeData[commendId] as LikeActionEntity[]; // 外部处理 handEmojis && handEmojis(commendId, likeActionInfo); comments().forEach(comment => { // 主评论查询到则刷新 if (comment.id == commendId) { comment.emojis = likeActionInfo || []; } comment.topicSubReply.forEach(sub => { // 子评论查询到则刷新 if (sub.id == commendId) { sub.emojis = likeActionInfo || []; } }); }); } }
// 刷新贴贴
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L241-L263
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
replyCommentToTreeComment
const replyCommentToTreeComment = ( reply: Post, mainCommentId: string, mainCommentUid: string, isSub: boolean = false ): CommentTreeEntity => { const target = {} as CommentTreeEntity; const subType = isSub ? 1 : 0; const subReplyId = isSub ? reply.pst_id : 0 const subReplyUid = reply.pst_uid; const avatar = reply.avatar || ''; target.id = reply.pst_id target.time = reply.dateline; target.userAvatar = avatar.startsWith("//") ? "https:" + avatar : avatar; target.userName = reply.nickname; target.userId = reply.username; target.replyContent = reply.pst_content; target.replyJs = `subReply('${reply.model}', ${reply.pst_mid}, ${mainCommentId}, ${subReplyId}, ${subReplyUid}, ${mainCommentUid}, ${subType})`; target.topicSubReply = []; target.emojiParam = {enable: false} as EmojiParam; target.emojis = []; // target.floor: string; // target.replyQuote: string; // target.topicSubReply: CommentTreeEntity[]; return target; };
/** * 映射 * * var subReply = function ( * type, // 评论的话题或日志等主题类型 * topic_id, // 主评论的评论ID * post_id, // 评论的话题或日志等主题ID * sub_reply_id, // 发布评论者的那条评论ID * sub_reply_uid, // 发布评论者的用户ID * post_uid, // 主评论的用户ID * sub_post_type // 主评论 0、子评论 1 * ) * * @param reply * @param mainCommentId * @param mainCommentUid * @param isSub */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L290-L318
632a803548848201a33d1f0ed73e31dedf342bc8
bangumi
github_2023
xiaoyvyv
typescript
scrollToTargetComment
const scrollToTargetComment = (targetId: string) => { if (targetId.length === 0) return; const element = document.querySelector("#post_" + targetId); if (element != null) { element.scrollIntoView(); } };
/** * 滑动到指定评论处 * * @param targetId */
https://github.com/xiaoyvyv/bangumi/blob/632a803548848201a33d1f0ed73e31dedf342bc8/lib-h5/src/util/common.ts#L325-L331
632a803548848201a33d1f0ed73e31dedf342bc8
content-collections
github_2023
sdorra
typescript
tsconfigResolvePaths
function tsconfigResolvePaths(configPath: string) { let tsconfig = loadTsConfig(dirname(configPath)); if (!tsconfig) { tsconfig = loadTsConfig(); } return tsconfig?.data?.compilerOptions?.paths || {}; }
// the code to handle externals is mostly the one which is used by the awesome tsup project
https://github.com/sdorra/content-collections/blob/98af25be09a9a8fd4017a087fe74d5939458c6bf/packages/core/src/esbuild.ts#L8-L14
98af25be09a9a8fd4017a087fe74d5939458c6bf
content-collections
github_2023
sdorra
typescript
createCacheKey
function createCacheKey(document: Document): Document { const { content, _meta } = document; return { content, _meta }; }
// Remove all unnecessary keys from the document
https://github.com/sdorra/content-collections/blob/98af25be09a9a8fd4017a087fe74d5939458c6bf/packages/markdown/src/index.ts#L52-L55
98af25be09a9a8fd4017a087fe74d5939458c6bf
content-collections
github_2023
sdorra
typescript
createCacheKey
function createCacheKey(document: Document): Document { const { content, _meta } = document; return { content, _meta }; }
// Remove all unnecessary keys from the document
https://github.com/sdorra/content-collections/blob/98af25be09a9a8fd4017a087fe74d5939458c6bf/packages/mdx/src/index.ts#L112-L115
98af25be09a9a8fd4017a087fe74d5939458c6bf
learn.nuxt.com
github_2023
nuxt
typescript
WorkerHost.fsStat
async fsStat(uriString: string) { const uri = Uri.parse(uriString) const dir = withoutLeadingSlash(dirname(uri.fsPath)) const base = basename(uri.fsPath) try { // TODO: should we cache it? const files = await this.ctx.webcontainer!.fs.readdir(dir, { withFileTypes: true }) const file = files.find(item => item.name === base) if (!file) return undefined if (file.isFile()) { return { type: 1 satisfies FileType.File, size: 100, ctime: Date.now(), mtime: Date.now(), } } else { return { type: 2 satisfies FileType.Directory, size: -1, ctime: -1, mtime: -1, } } } catch { return undefined } }
// we have to use readdir to check if the file is a directory
https://github.com/nuxt/learn.nuxt.com/blob/6a9a8cb6c5e272f509a70c88b13810a7db6a794e/monaco/env.ts#L31-L62
6a9a8cb6c5e272f509a70c88b13810a7db6a794e
learn.nuxt.com
github_2023
nuxt
typescript
resolvePath
function resolvePath(path: string) { if (path.startsWith('./')) return `./.nuxt/${path.slice(2)}` if (path.startsWith('..')) return `.${path.slice(2)}` return path }
// Resolve .nuxt/tsconfig.json paths from `./.nuxt` to `./`
https://github.com/nuxt/learn.nuxt.com/blob/6a9a8cb6c5e272f509a70c88b13810a7db6a794e/monaco/env.ts#L98-L104
6a9a8cb6c5e272f509a70c88b13810a7db6a794e
learn.nuxt.com
github_2023
nuxt
typescript
mount
async function mount(map: Record<string, string>, templates = filesTemplate) { const objects = { ...templates, ...map, } await Promise.all([ // update or create files ...Object.entries(objects) .map(async ([filepath, content]) => { await _updateOrCreateFile(filepath, content) }), // remove extra files ...Array.from(files.keys()) .filter(filepath => !(filepath in objects)) .map(async (filepath) => { const file = files.get(filepath) await file?.remove() files.delete(filepath) }), ]) }
/** * Mount files to WebContainer. * This will do a diff with the current files and only update the ones that changed */
https://github.com/nuxt/learn.nuxt.com/blob/6a9a8cb6c5e272f509a70c88b13810a7db6a794e/stores/playground.ts#L200-L221
6a9a8cb6c5e272f509a70c88b13810a7db6a794e
zotero-scipdf
github_2023
syt2
typescript
onPrefsEvent
async function onPrefsEvent(type: string, data: { [key: string]: any }) { switch (type) { case "load": registerPrefsScripts(data.window); break; default: return; } }
/** * This function is just an example of dispatcher for Preference UI events. * Any operations should be placed in a function to keep this funcion clear. * @param type event type * @param data event data */
https://github.com/syt2/zotero-scipdf/blob/f9360d2e0275989d04f3dcce1cac3de082711d7d/src/hooks.ts#L67-L75
f9360d2e0275989d04f3dcce1cac3de082711d7d
zotero-scipdf
github_2023
syt2
typescript
CustomResolverManager.appendCustomResolversInZotero
appendCustomResolversInZotero(resolvers: CustomResolver[] | Readonly<CustomResolver[]>) { this.customResolversInZotero = this.customResolversInZotero.concat(resolvers.filter(value => this.customResolversInZotero.findIndex(e => isCustomResolverEqual(e, value)) < 0)) this.customResolvers = this.customResolvers.concat(resolvers.filter(value => this.customResolvers.findIndex(e => isCustomResolverEqual(e, value)) < 0)) }
// system custom resolvers
https://github.com/syt2/zotero-scipdf/blob/f9360d2e0275989d04f3dcce1cac3de082711d7d/src/modules/CustomResolverManager.ts#L25-L28
f9360d2e0275989d04f3dcce1cac3de082711d7d
zotero-scipdf
github_2023
syt2
typescript
initLocale
function initLocale() { const l10n = new ( typeof Localization === "undefined" ? ztoolkit.getGlobal("Localization") : Localization )([`${config.addonRef}-addon.ftl`], true); addon.data.locale = { current: l10n, }; }
/** * Initialize locale data */
https://github.com/syt2/zotero-scipdf/blob/f9360d2e0275989d04f3dcce1cac3de082711d7d/src/utils/locale.ts#L8-L17
f9360d2e0275989d04f3dcce1cac3de082711d7d
zotero-scipdf
github_2023
syt2
typescript
isWindowAlive
function isWindowAlive(win?: Window) { return win && !Components.utils.isDeadWrapper(win) && !win.closed; }
/** * Check if the window is alive. * Useful to prevent opening duplicate windows. * @param win */
https://github.com/syt2/zotero-scipdf/blob/f9360d2e0275989d04f3dcce1cac3de082711d7d/src/utils/window.ts#L8-L10
f9360d2e0275989d04f3dcce1cac3de082711d7d
braintrust-proxy
github_2023
braintrustdata
typescript
OpenAiRealtimeLogger.close
public async close() { // Pending client audio buffer is allowed in VAD mode. if (this.turnDetectionEnabled) { this.clientAudioBuffer = undefined; } // Check if there is a pending audio buffers. if (this.serverAudioBuffer.size || this.clientAudioBuffer) { console.warn( `Closing with ${this.serverAudioBuffer.size} pending server + ${this.clientAudioBuffer ? 1 : 0} pending client audio buffers`, ); } if (this.clientAudioBuffer && this.clientSpan) { this.closeAudio(this.clientAudioBuffer, this.clientSpan, "input"); this.clientAudioBuffer = undefined; } for (const [responseId, audioBuffer] of this.serverAudioBuffer) { const span = this.serverSpans.get(responseId); if (!span) { continue; } this.closeAudio(audioBuffer, span, "output"); } this.serverAudioBuffer.clear(); this.clientSpan?.close(); this.clientSpan = undefined; for (const span of this.serverSpans.values()) { span.close(); } this.serverSpans.clear(); for (const span of this.toolSpans.values()) { span.close(); } this.toolSpans.clear(); const rootSpan = this.rootSpan; this.rootSpan = Braintrust.NOOP_SPAN; rootSpan.close(); await rootSpan.flush(); }
/** * Close all pending spans. */
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/apis/cloudflare/src/realtime-logger.ts#L419-L463
87c174af68cfc37e884ea36f551e99b8336e5949
braintrust-proxy
github_2023
braintrustdata
typescript
cacheGet
const cacheGet = async (encryptionKey: string, key: string) => { const redis = await getRedis(); if (!redis) { return null; } return await redis.get(key); };
// Unlike the Cloudflare worker API, which supports public access, this API
https://github.com/braintrustdata/braintrust-proxy/blob/87c174af68cfc37e884ea36f551e99b8336e5949/apis/node/src/node-proxy.ts#L32-L38
87c174af68cfc37e884ea36f551e99b8336e5949