Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support witness coinselect #2

Merged
merged 13 commits into from
Dec 5, 2024
Merged

feat: Support witness coinselect #2

merged 13 commits into from
Dec 5, 2024

Conversation

originalix
Copy link

@originalix originalix commented Dec 5, 2024

Summary by CodeRabbit

发布说明

  • 新功能

    • 引入了新的 GitHub Actions 工作流以自动发布 NPM 包。
    • 更新了 package.json,包括包名、文件、依赖项和测试脚本的修改。
    • 新增多个实用函数,如 addDashesToSpaces, arrayDistinct, capitalizeFirstLetter 等,增强了字符串和数组的处理能力。
    • 引入了 coinselect 函数以支持更灵活的交易选择。
    • 增强了对地址派生的支持,新增了 getXpubOrDescriptorInfoderiveAddresses 函数。
    • 引入了多个新的排序策略,如 bip69SortingStrategyrandomSortingStrategy,以支持更复杂的输出排序。
    • 引入了多个加密哈希函数,如 sha256, ripemd160, 和 hmacSHA512,增强了加密能力。
  • 修复

    • 修复了多个功能的类型定义和实现,确保更好的类型安全性和错误处理。
  • 文档

    • 更新了文档以反映新的功能和改进的类型定义。

请根据您的需求查看具体的功能和修复内容。

Copy link

codesandbox bot commented Dec 5, 2024

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

本次变更引入了多个新功能和文件,主要集中在自动化、加密、地址处理和交易构建等方面。新增的 GitHub Actions 工作流 package-publish.yml 用于自动发布 NPM 包。package.json 文件更新了包名和依赖项。多个工具函数和类型定义被添加到 third-party/utilsthird-party/utxo-lib 模块中,以增强库的功能,包括地址派生、加密操作和交易构建。整体结构更为模块化,便于使用和维护。

Changes

文件路径 变更摘要
.github/workflows/package-publish.yml 新增工作流文件,用于自动发布 NPM 包。
package.json 更新包名,增加新依赖项,添加新脚本。
test/fixtures/witness.js 新增测试用例,包含比特币测试网的交易场景。
test/witness.js 新增单元测试,针对 coinSelect 函数进行验证。
third-party/utils/*.d.ts 新增多个工具函数和类型定义,如 addDashesToSpacesarrayDistinctbytesToHumanReadable 等。
third-party/utils/*.js 实现多个工具函数,增强字符串和数组处理功能。
third-party/utxo-lib/*.d.ts 引入 BIP32、地址处理、加密和交易构建相关的类型定义。
third-party/utxo-lib/*.js 实现与上述类型定义相对应的功能,如地址派生、交易构建等。

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant GitHub Actions
    participant NPM Registry

    User->>GitHub Actions: Trigger publish
    GitHub Actions->>GitHub Actions: Checkout code
    GitHub Actions->>GitHub Actions: Setup Node.js
    GitHub Actions->>GitHub Actions: Install dependencies
    GitHub Actions->>NPM Registry: Publish package
    NPM Registry-->>GitHub Actions: Confirmation
    GitHub Actions-->>User: Publish successful
Loading

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

socket-security bot commented Dec 5, 2024

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

🛑 Comments failed to post (205)
third-party/utxo-lib/global.js (1)

1-1: 🛠️ Refactor suggestion

建议移除多余的 'use strict' 声明

由于 JavaScript 模块默认就是严格模式,这个声明是多余的。建议移除以保持代码简洁。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/address.d.ts (1)

11-16: 🧹 Nitpick (assertive)

建议增加参数验证说明

函数声明看起来不错,但建议添加以下改进:

  • 为每个函数添加参数验证的说明注释
  • 明确说明当传入无效参数时的错误处理方式

示例注释格式:

/**
 * 从Base58Check格式解码地址
 * @param address - 需要解码的地址字符串
 * @param network - 可选的网络参数
 * @throws {Error} 当地址格式无效时抛出错误
 * @returns {Base58CheckResult} 解码后的结果
 */
third-party/utxo-lib/global.d.ts (2)

1-40: 🧹 Nitpick (assertive)

typeforce 模块类型定义完善

类型定义覆盖了所有常用的验证方法,结构清晰。建议考虑:

  • 为复杂的验证方法添加使用示例
  • 补充泛型约束以提高类型安全性

示例改进:

interface Typeforce {
    // 添加泛型支持
    arrayOf<T>(type: T): (value: any) => value is T[];
    // 其他方法类似
}

41-61: 🛠️ Refactor suggestion

补充模块类型信息

对于 bitcoin-opsminimaldatatiny-secp256k1blake-hash 模块,建议:

  • 添加完整的类型定义
  • 包含导出的常量和函数签名
  • 补充必要的文档注释

示例格式:

declare module 'bitcoin-ops' {
    export const OP_RETURN: number;
    export const OP_CHECKSIG: number;
    // 其他操作码...
}
third-party/utxo-lib/bufferutils.js (3)

1-1: ⚠️ Potential issue

删除多余的 'use strict' 指令

JavaScript 模块默认启用严格模式,无需显式添加 'use strict'。请移除这行代码以保持代码简洁。

应用以下修改来修复问题:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


74-80: 🧹 Nitpick (assertive)

简化 writeInt64LE 函数的实现

可以直接使用 v.toBuffer().copy(buffer, offset),避免手动循环写入字节。

建议修改如下:

function writeInt64LE(buffer, value, offset) {
    const v = new Int64LE(value);
-    const a = v.toArray();
-    for (let i = 0; i < 8; i++) {
-        buffer.writeUInt8(a[i], offset + i);
-    }
+    v.toBuffer().copy(buffer, offset);
    return offset + 8;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    const v = new int64_buffer_1.Int64LE(value);
    v.toBuffer().copy(buffer, offset);
    return offset + 8;
}

94-98: 🧹 Nitpick (assertive)

使用 Buffer.from 简化 cloneBuffer 函数

可以使用内置的 Buffer.from(buffer) 方法来复制缓冲区,无需自定义实现。

建议修改如下:

-function cloneBuffer(buffer) {
-    const clone = Buffer.allocUnsafe(buffer.length);
-    buffer.copy(clone);
-    return clone;
-}
+function cloneBuffer(buffer) {
+    return Buffer.from(buffer);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function cloneBuffer(buffer) {
    return Buffer.from(buffer);
}
third-party/utxo-lib/bip32.js (5)

1-1: 🧹 Nitpick (assertive)

移除多余的 "use strict" 指令。

在 ES6 模块中,严格模式是默认启用的,无需手动添加 "use strict"

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


35-35: 🛠️ Refactor suggestion

避免修改函数参数,使用局部变量代替。

重新赋值函数参数可能导致混淆,建议使用局部变量。比如,将 network = network || networks_1.bitcoin; 修改为 const net = network || networks_1.bitcoin;

Also applies to: 45-45, 208-208, 247-247

🧰 Tools
🪛 Biome (1.9.4)

[error] 35-35: Reassigning a function parameter is confusing.

The parameter is declared here:

Use a local variable instead.

(lint/style/noParameterAssign)


184-184: 🛠️ Refactor suggestion

避免修改函数参数 'lowR',使用局部变量代替。

修改函数参数可能引起混淆,建议使用局部变量。将 lowR = this.lowR; 修改为 const useLowR = lowR !== undefined ? lowR : this.lowR;

🧰 Tools
🪛 Biome (1.9.4)

[error] 184-184: Reassigning a function parameter is confusing.

The parameter is declared here:

Use a local variable instead.

(lint/style/noParameterAssign)


173-173: 🧹 Nitpick (assertive)

使用 Number.parseInt 替代全局 parseInt

为了一致性,建议使用 ES2015 引入的 Number.parseInt

Also applies to: 176-176

🧰 Tools
🪛 Biome (1.9.4)

[error] 173-173: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)


191-195: 🛠️ Refactor suggestion

添加最大尝试次数以避免可能的无限循环。

在计算低 R 签名时,循环可能在极端情况下无限执行。建议设置最大尝试次数,例如:

 let counter = 0;
+const maxCounter = 1000;
 while (sig[0] > 0x7f) {
     counter++;
+    if (counter > maxCounter) {
+        throw new Error('无法生成低 R 签名');
+    }
     extraData.writeUIntLE(counter, 0, 6);
     sig = tiny_secp256k1_1.default.signWithEntropy(hash, this.privateKey, extraData);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        const maxCounter = 1000;
        while (sig[0] > 0x7f) {
            counter++;
            if (counter > maxCounter) {
                throw new Error('无法生成低 R 签名');
            }
            extraData.writeUIntLE(counter, 0, 6);
            sig = tiny_secp256k1_1.default.signWithEntropy(hash, this.privateKey, extraData);
        }
third-party/utils/mergeDeepObject.d.ts (1)

25-25: 🛠️ Refactor suggestion

移除无用的空导出

第25行的 export {}; 是多余的,因为文件已经有其他导出。建议删除它。

应用以下diff来移除无用的空导出:

- export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 24-25: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/typedEventEmitter.d.ts (2)

1-1: 🛠️ Refactor suggestion

使用 node: 协议导入 Node.js 内置模块

第1行的 events 模块是 Node.js 的内置模块,建议使用 node: 协议导入,以提高明确性。

应用以下diff来修改导入语句:

- import { EventEmitter } from 'events';
+ import { EventEmitter } from 'node:events';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import { EventEmitter } from 'node:events';
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


22-22: 🛠️ Refactor suggestion

移除无用的空导出

第22行的 export {}; 是多余的,因为文件已经有其他导出。建议删除它。

应用以下diff来移除无用的空导出:

- export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 21-22: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utxo-lib/coinselect/outputs/split.js (1)

1-1: 🛠️ Refactor suggestion

移除冗余的 "use strict" 指令

JavaScript 模块默认在严格模式下运行,因此第1行的 "use strict"; 是多余的。建议删除。

应用以下diff来移除冗余的指令:

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/coinselect/tryconfirmed.js (1)

1-1: 🛠️ Refactor suggestion

移除冗余的 "use strict" 指令

JavaScript 模块默认在严格模式下运行,因此第1行的 "use strict"; 是多余的。建议删除。

应用以下diff来移除冗余的指令:

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/coinselect/inputs/accumulative.js (1)

1-1: 🛠️ Refactor suggestion

移除冗余的 "use strict" 指令

JavaScript 模块默认在严格模式下运行,因此第1行的 "use strict"; 是多余的。建议删除。

应用以下diff来移除冗余的指令:

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/bufferutils.d.ts (1)

57-58: 🧹 Nitpick (assertive)

删除无用的空导出

第57-58行的export {};没有作用,可以安全删除。

建议应用以下修改:

- export {};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

}
🧰 Tools
🪛 Biome (1.9.4)

[error] 57-58: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/mergeDeepObject.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,"use strict";是多余的,因为模块默认采用严格模式。

建议删除第一行的"use strict";

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/compose/result.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

模块默认是严格模式,无需显式声明。

建议删除第一行的"use strict";

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/coinselect/coinselectUtils.d.ts (1)

51-52: 🧹 Nitpick (assertive)

删除无用的空导出

第51-52行的export {};没有作用,可以删除。

建议应用以下修改:

- export {};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare function filterCoinbase(utxos: CoinSelectInput[], minConfCoinbase: number): CoinSelectInput[];
🧰 Tools
🪛 Biome (1.9.4)

[error] 51-52: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/createDeferredManager.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

模块默认启用严格模式,无需额外声明。

建议删除第一行的"use strict";

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/bs58check.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,默认就是严格模式,无需添加"use strict"。

建议删除以下代码:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/derivation.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,默认就是严格模式,无需添加"use strict"。

建议删除以下代码:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/coinselect/inputs/branchAndBound.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,默认就是严格模式,无需添加"use strict"。

建议删除以下代码:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/scheduleAction.js (3)

98-98: 🧹 Nitpick (assertive)

使用 'Number.POSITIVE_INFINITY' 替代 'Infinity'

为与 ES2015 标准保持一致,建议使用 Number.POSITIVE_INFINITY

建议修改如下:

-: attempts !== null && attempts !== void 0 ? attempts : (deadline ? Infinity : 1);
+: attempts !== null && attempts !== void 0 ? attempts : (deadline ? Number.POSITIVE_INFINITY : 1);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        : attempts !== null && attempts !== void 0 ? attempts : (deadline ? Number.POSITIVE_INFINITY : 1);
🧰 Tools
🪛 Biome (1.9.4)

[error] 98-98: Use Number.POSITIVE_INFINITY instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.POSITIVE_INFINITY instead.

(lint/style/useNumberNamespace)


1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,默认就是严格模式,无需添加"use strict"。

建议删除以下代码:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


112-112: 🧹 Nitpick (assertive)

使用 'let' 或 'const' 代替 'var'

var 具有函数作用域,可能导致意外行为。建议使用块级作用域的 letconst

建议修改如下:

-var _a;
+let _a;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

                let _a;
🧰 Tools
🪛 Biome (1.9.4)

[error] 112-112: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utxo-lib/compose/request.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的"use strict"声明

在ES6模块中,默认就是严格模式,无需添加"use strict"。

建议删除以下代码:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/address.js (1)

1-1: 🧹 Nitpick (assertive)

删除多余的 'use strict';

在 ES6 模块中,'use strict'; 是多余的。建议删除它。

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utxo-lib/coinselect/coinselectUtils.js (3)

1-1: 🧹 Nitpick (assertive)

删除多余的 'use strict';

在 ES6 模块中,'use strict'; 是多余的。建议删除它。

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


166-166: 🛠️ Refactor suggestion

使用 const 并分开声明变量

建议使用 const 而不是 var,并将变量单独声明。

- var { feePolicy } = _a, options = tslib_1.__rest(_a, ["feePolicy"]);
+ const { feePolicy } = _a;
+ const options = tslib_1.__rest(_a, ["feePolicy"]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    const { feePolicy } = _a;
    const options = tslib_1.__rest(_a, ["feePolicy"]);
🧰 Tools
🪛 Biome (1.9.4)

[error] 166-166: Declare variables separately

Unsafe fix: Break out into multiple declarations

(lint/style/useSingleVarDeclarator)


[error] 166-166: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


148-148: 🛠️ Refactor suggestion

使用 const 并分开声明变量

建议使用 const 而不是 var,并将变量单独声明。

- var { dustThreshold = 0 } = _a, options = tslib_1.__rest(_a, ["dustThreshold"]);
+ const { dustThreshold = 0 } = _a;
+ const options = tslib_1.__rest(_a, ["dustThreshold"]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    const { dustThreshold = 0 } = _a;
    const options = tslib_1.__rest(_a, ["dustThreshold"]);
🧰 Tools
🪛 Biome (1.9.4)

[error] 148-148: Declare variables separately

Unsafe fix: Break out into multiple declarations

(lint/style/useSingleVarDeclarator)


[error] 148-148: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)

third-party/utils/isNotUndefined.d.ts (1)

1-1: 🧹 Nitpick (assertive)

类型守卫实现准确,建议添加文档注释!

泛型类型守卫的实现非常规范。建议添加 JSDoc 注释来说明函数用途和用法示例。

+/**
+ * 检查值是否未定义
+ * @param item - 要检查的值
+ * @returns 如果值不是 undefined 则返回 true
+ * @example
+ * const value: string | undefined = "test";
+ * if (isNotUndefined(value)) {
+ *   // value 在这里被类型收窄为 string
+ *   console.log(value.length);
+ * }
+ */
 export declare const isNotUndefined: <T>(item?: T) => item is T;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 检查值是否未定义
 * @param item - 要检查的值
 * @returns 如果值不是 undefined 则返回 true
 * @example
 * const value: string | undefined = "test";
 * if (isNotUndefined(value)) {
 *   // value 在这里被类型收窄为 string
 *   console.log(value.length);
 * }
 */
export declare const isNotUndefined: <T>(item?: T) => item is T;
third-party/utils/getRandomInt.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议添加参数约束和文档注释

建议添加以下改进:

  1. 为函数添加 JSDoc 文档注释,说明参数含义和返回值范围
  2. 考虑使用更严格的类型约束,确保输入参数为整数
+ /**
+  * 生成一个位于指定范围内的随机整数
+  * @param min 范围下限(包含)
+  * @param max 范围上限(包含)
+  * @returns 返回区间 [min, max] 内的随机整数
+  */
export declare const getRandomInt: (min: number, max: number) => number;

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/parseHostname.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议补充函数文档和输入验证

函数返回类型包含 undefined,说明已考虑异常情况处理,这很好。建议添加详细文档:

+ /**
+  * 从 URL 中解析出主机名
+  * @param url 完整的 URL 字符串(例如:https://example.com/path)
+  * @returns 返回小写的主机名,如果解析失败则返回 undefined
+  * @example
+  * parseHostname('https://example.com/path') // 返回 'example.com'
+  * parseHostname('invalid-url') // 返回 undefined
+  */
export declare const parseHostname: (url: string) => string | undefined;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 从 URL 中解析出主机名
 * @param url 完整的 URL 字符串(例如:https://example.com/path)
 * @returns 返回小写的主机名,如果解析失败则返回 undefined
 * @example
 * parseHostname('https://example.com/path') // 返回 'example.com'
 * parseHostname('invalid-url') // 返回 undefined
 */
export declare const parseHostname: (url: string) => string | undefined;
third-party/utils/createCooldown.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议添加类型文档注释

虽然类型定义正确,但建议添加以下改进:

  • 为函数添加 JSDoc 注释,说明冷却时间的具体行为
  • 考虑使用更具描述性的参数名,如 durationMs 而不是 cooldownMs
+/**
+ * 创建一个具有冷却时间的函数
+ * @param durationMs 冷却持续时间(毫秒)
+ * @returns 返回一个函数,当冷却时间未到时返回 false,否则返回 true
+ */
-export declare const createCooldown: (cooldownMs: number) => () => boolean;
+export declare const createCooldown: (durationMs: number) => () => boolean;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 创建一个具有冷却时间的函数
 * @param durationMs 冷却持续时间(毫秒)
 * @returns 返回一个函数,当冷却时间未到时返回 false,否则返回 true
 */
export declare const createCooldown: (durationMs: number) => () => boolean;
third-party/utils/getMutex.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议优化类型定义和文档

当前类型定义可以进行以下改进:

  • 使用更具体的类型替代 keyof any
  • 添加错误处理的类型信息
  • 补充互斥锁行为的文档说明
+/**
+ * 创建一个互斥锁实例
+ * @returns 返回一个加锁函数,可选择性地指定锁ID
+ * @throws {MutexError} 当获取锁失败时抛出
+ */
-export declare const getMutex: () => (lockId?: keyof any) => Promise<() => void>;
+export declare type LockId = string | number | symbol;
+export declare class MutexError extends Error {
+    readonly code: string;
+}
+export declare const getMutex: () => (lockId?: LockId) => Promise<() => void>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 创建一个互斥锁实例
 * @returns 返回一个加锁函数,可选择性地指定锁ID
 * @throws {MutexError} 当获取锁失败时抛出
 */
export declare type LockId = string | number | symbol;
export declare class MutexError extends Error {
    readonly code: string;
}
export declare const getMutex: () => (lockId?: LockId) => Promise<() => void>;
third-party/utils/addDashesToSpaces.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议添加 JSDoc 文档注释

为了提高代码可读性和可维护性,建议添加函数说明文档。

建议修改如下:

+/**
+ * 将字符串中的空格替换为破折号
+ * @param inputString - 需要处理的输入字符串
+ * @returns 处理后的字符串
+ */
export declare const addDashesToSpaces: (inputString: string) => string;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 将字符串中的空格替换为破折号
 * @param inputString - 需要处理的输入字符串
 * @returns 处理后的字符串
 */
export declare const addDashesToSpaces: (inputString: string) => string;
third-party/utils/bytesToHumanReadable.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议增加输入验证和文档说明

函数类型声明可以更严谨,同时需要添加使用说明文档。

建议修改如下:

+/**
+ * 将字节数转换为人类可读的格式(如:1024 -> "1 KB")
+ * @param bytes - 非负字节数
+ * @returns 格式化后的字符串
+ * @throws 当输入为负数时抛出错误
+ */
-export declare const bytesToHumanReadable: (bytes: number) => string;
+export declare const bytesToHumanReadable: (bytes: NonNegativeNumber) => string;
+
+type NonNegativeNumber = number & { __brand: 'NonNegativeNumber' };

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/cloneObject.d.ts (1)

1-1: 🛠️ Refactor suggestion

建议完善类型约束和添加文档

当前的类型声明可以更具体,同时需要详细的文档说明。

建议修改如下:

+/**
+ * 深度克隆对象,支持处理循环引用
+ * @param obj - 要克隆的对象
+ * @param seen - 用于跟踪已见对象的 WeakMap,防止循环引用
+ * @returns 克隆后的对象
+ * @template T - 输入对象的类型
+ */
-export declare const cloneObject: <T>(obj: T, seen?: WeakMap<object, any>) => T;
+export declare const cloneObject: <T extends object | null | undefined>(
+  obj: T,
+  seen?: WeakMap<object, unknown>
+) => T;

这样的修改有以下优点:

  1. 使用 unknown 替代 any,提高类型安全性
  2. 明确了输入类型的约束
  3. 添加了详细的文档说明
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 深度克隆对象,支持处理循环引用
 * @param obj - 要克隆的对象
 * @param seen - 用于跟踪已见对象的 WeakMap,防止循环引用
 * @returns 克隆后的对象
 * @template T - 输入对象的类型
 */
export declare const cloneObject: <T extends object | null | undefined>(
  obj: T,
  seen?: WeakMap<object, unknown>
) => T;
third-party/utxo-lib/compose/sorting/sortingStrategy.js (1)

1-1: 🛠️ Refactor suggestion

移除多余的 "use strict" 声明

在 ES 模块中,"use strict" 声明是多余的,因为模块代码默认就在严格模式下运行。

建议应用以下修改:

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/getNumberFromPixelString.d.ts (1)

1-1: 🧹 Nitpick (assertive)

建议优化参数命名

虽然类型声明本身没有问题,但建议将参数名 size 改为更具描述性的名称,比如 pixelValuepixelString,以更好地表达参数的预期格式。

建议修改为:

-export declare const getNumberFromPixelString: (size: string) => number;
+export declare const getNumberFromPixelString: (pixelString: string) => number;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare const getNumberFromPixelString: (pixelString: string) => number;
third-party/utils/arrayDistinct.d.ts (1)

1-1: 🧹 Nitpick (assertive)

类型定义清晰,建议添加文档注释

类型签名符合标准的 Array.filter 用法,泛型参数确保了类型安全。建议添加 JSDoc 注释说明函数用途和参数含义。

添加如下文档注释:

+/**
+ * 数组去重函数,用于 Array.filter
+ * @param item - 当前元素
+ * @param index - 当前索引
+ * @param self - 原数组
+ * @returns 是否保留该元素
+ */
export declare const arrayDistinct: <T>(item: T, index: number, self: T[]) => boolean;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 数组去重函数,用于 Array.filter
 * @param item - 当前元素
 * @param index - 当前索引
 * @param self - 原数组
 * @returns 是否保留该元素
 */
export declare const arrayDistinct: <T>(item: T, index: number, self: T[]) => boolean;
third-party/utils/createTimeoutPromise.d.ts (1)

1-1: 🛠️ Refactor suggestion

建议优化 Promise 返回类型

当前返回类型 Promise<unknown> 过于宽泛,建议使用更具体的类型。

建议修改为:

-export declare const createTimeoutPromise: (timeout: number) => Promise<unknown>;
+export declare const createTimeoutPromise: (timeout: number) => Promise<void>;

这样可以:

  • 更准确地表达函数的返回值
  • 避免使用者需要额外的类型检查
  • 提高代码的类型安全性
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare const createTimeoutPromise: (timeout: number) => Promise<void>;
third-party/utils/getWeakRandomNumberInRange.d.ts (1)

1-1: 💡 Codebase verification

🛠️ Refactor suggestion

建议添加参数验证和使用说明文档

代码库中已有 getRandomInt 作为安全的随机数生成器。getWeakRandomNumberInRange 确实需要添加参数验证和清晰的文档说明。

建议修改为:

/**
 * 生成指定范围内的非加密安全随机数
 * @warning 仅用于非安全场景,安全敏感操作请使用 getRandomInt
 * @param min - 最小值(包含)
 * @param max - 最大值(包含)
 * @throws {RangeError} 当 min >= max 时抛出异常
 */
export declare const getWeakRandomNumberInRange: (min: number, max: number) => number;
🔗 Analysis chain

注意安全性并添加参数约束

函数名中的 "Weak" 表明这不是密码学安全的随机数生成器。

建议:

  1. 添加参数约束以确保 min <= max
  2. 为安全敏感场景添加警告注释
+/**
+ * 生成指定范围内的非加密安全随机数
+ * @warning 不要用于加密或安全敏感场景
+ * @param min - 最小值(包含)
+ * @param max - 最大值(包含),必须大于等于 min
+ */
-export declare const getWeakRandomNumberInRange: (min: number, max: number) => number;
+export declare const getWeakRandomNumberInRange: (min: number, max: number) => asserts max >= min => number;

验证使用场景是否涉及安全敏感操作:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 搜索可能的安全敏感使用场景
rg -i "getWeakRandomNumberInRange.*(?:secret|password|key|token|auth)"

Length of output: 72


Script:

#!/bin/bash
# 搜索函数的所有使用场景
rg "getWeakRandomNumberInRange" -A 3 -B 3

# 查找函数实现
fd "getWeakRandomNumberInRange" --exec cat {}

Length of output: 3711


Script:

#!/bin/bash
# 查找使用此函数的其他文件
rg -l "getWeakRandomId.*getWeakRandomNumberInRange" 

# 检查是否有其他随机数生成器
fd -e ts -e js "getRandom" --exec cat {}

Length of output: 1649

third-party/utils/truncateMiddle.d.ts (1)

1-1: 🧹 Nitpick (assertive)

类型定义清晰简洁!

建议添加参数约束以提高类型安全性:

  • startCharsendChars 应为非负数
  • text 不应为空字符串
-export declare const truncateMiddle: (text: string, startChars: number, endChars: number) => string;
+export declare const truncateMiddle: (
+  text: NonEmptyString,
+  startChars: NonNegativeNumber,
+  endChars: NonNegativeNumber
+) => string;
+
+type NonEmptyString = string & {}
+type NonNegativeNumber = number & {}

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/splitStringEveryNCharacters.d.ts (1)

1-1: 🧹 Nitpick (assertive)

函数声明结构合理!

为了防止意外输入,建议:

  1. 确保 n 为正整数
  2. 处理空字符串情况
-export declare function splitStringEveryNCharacters(value: string, n: number): string[];
+export declare function splitStringEveryNCharacters(
+  value: string,
+  n: PositiveInteger
+): readonly string[];
+
+type PositiveInteger = number & { readonly brand: unique symbol }

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/capitalizeFirstLetter.d.ts (1)

1-1: 🧹 Nitpick (assertive)

泛型实现非常优雅!

代码利用了 TypeScript 的 Capitalize 工具类型,保证了类型安全。建议添加空字符串处理:

-export declare const capitalizeFirstLetter: <T extends string = string>(str: T) => Capitalize<T>;
+export declare const capitalizeFirstLetter: <T extends string = string>(
+  str: T & (T extends '' ? never : unknown)
+) => Capitalize<T>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare const capitalizeFirstLetter: <T extends string = string>(
  str: T & (T extends '' ? never : unknown)
) => Capitalize<T>;
third-party/utils/bufferUtils.d.ts (1)

1-2: 🧹 Nitpick (assertive)

建议添加函数说明文档!

类型声明本身没有问题,但建议添加以下改进:

  • 为每个函数添加 JSDoc 注释,说明用途和参数含义
  • 考虑使用更具描述性的参数名称(如 src 改为 sourceBuffer

建议修改为:

+/** 反转缓冲区内容
+ * @param sourceBuffer - 源缓冲区
+ * @returns 反转后的新缓冲区
+ */
-export declare const reverseBuffer: (src: Buffer) => Buffer;
+export declare const reverseBuffer: (sourceBuffer: Buffer) => Buffer;

+/** 获取指定大小的单字节缓冲区
+ * @param size - 大小值
+ * @returns 包含大小信息的缓冲区
+ */
-export declare const getChunkSize: (n: number) => Buffer;
+export declare const getChunkSize: (size: number) => Buffer;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/** 反转缓冲区内容
 * @param sourceBuffer - 源缓冲区
 * @returns 反转后的新缓冲区
 */
export declare const reverseBuffer: (sourceBuffer: Buffer) => Buffer;

/** 获取指定大小的单字节缓冲区
 * @param size - 大小值
 * @returns 包含大小信息的缓冲区
 */
export declare const getChunkSize: (size: number) => Buffer;
third-party/utils/urlToOnion.d.ts (1)

1-3: 🧹 Nitpick (assertive)

建议添加 JSDoc 文档注释

为了提高代码可维护性,建议添加函数说明、参数描述和返回值说明的文档注释。

建议添加如下文档:

+/**
+ * 将普通 URL 转换为 onion 地址
+ * @param url - 需要转换的 URL
+ * @param onionDomains - 域名到 onion 地址的映射
+ * @returns 转换后的 onion URL,如果找不到对应映射则返回 undefined
+ */
export declare const urlToOnion: (url: string, onionDomains: {
    [domain: string]: string;
}) => string | undefined;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 将普通 URL 转换为 onion 地址
 * @param url - 需要转换的 URL
 * @param onionDomains - 域名到 onion 地址的映射
 * @returns 转换后的 onion URL,如果找不到对应映射则返回 undefined
 */
export declare const urlToOnion: (url: string, onionDomains: {
    [domain: string]: string;
}) => string | undefined;
third-party/utxo-lib/compose/sorting/randomSortingStrategy.d.ts (1)

1-2: 🧹 Nitpick (assertive)

类型声明看起来不错,建议添加文档注释

类型声明正确且符合 TypeScript 规范。不过建议为 randomSortingStrategy 添加 JSDoc 注释,说明其用途和行为。

建议添加如下文档:

+/**
+ * 随机排序策略实现
+ * 用于对交易输出进行随机排序,提高交易隐私性
+ */
export declare const randomSortingStrategy: SortingStrategy;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import { SortingStrategy } from './sortingStrategy';
/**
 * 随机排序策略实现
 * 用于对交易输出进行随机排序,提高交易隐私性
 */
export declare const randomSortingStrategy: SortingStrategy;
third-party/utils/extractUrlsFromText.d.ts (1)

1-4: 🧹 Nitpick (assertive)

建议增强 URL 的类型安全性

函数声明基本正确,但可以通过自定义类型来提高 URL 的类型安全性。

建议如下改进:

+/** 表示有效的 URL 字符串 */
+type ValidUrl = string & { readonly _brand: unique symbol };

export declare const extractUrlsFromText: (text: string) => {
    textParts: string[];
-    urls: string[];
+    urls: ValidUrl[];
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/** 表示有效的 URL 字符串 */
type ValidUrl = string & { readonly _brand: unique symbol };

export declare const extractUrlsFromText: (text: string) => {
    textParts: string[];
    urls: ValidUrl[];
};
third-party/utils/asciiUtils.d.ts (1)

1-2: 🧹 Nitpick (assertive)

函数签名清晰,建议添加文档注释!

函数签名设计合理,可选参数处理了边缘情况。建议添加JSDoc注释来说明函数的具体行为和参数含义。

建议添加如下文档注释:

+/**
+ * 检查字符串是否只包含ASCII字符
+ * @param value - 要检查的字符串
+ * @returns 如果字符串只包含ASCII字符或为空则返回true
+ */
 export declare function isAscii(value?: string): boolean;
+/**
+ * 获取字符串中的非ASCII字符
+ * @param value - 要检查的字符串
+ * @returns 非ASCII字符数组,如果没有则返回null
+ */
 export declare function getNonAsciiChars(value?: string): RegExpMatchArray | null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 检查字符串是否只包含ASCII字符
 * @param value - 要检查的字符串
 * @returns 如果字符串只包含ASCII字符或为空则返回true
 */
export declare function isAscii(value?: string): boolean;
/**
 * 获取字符串中的非ASCII字符
 * @param value - 要检查的字符串
 * @returns 非ASCII字符数组,如果没有则返回null
 */
export declare function getNonAsciiChars(value?: string): RegExpMatchArray | null;
third-party/utils/promiseAllSequence.d.ts (1)

1-1: 🧹 Nitpick (assertive)

类型定义清晰完整!

类型定义准确地描述了函数的功能和返回值。建议添加 JSDoc 注释来说明函数的具体用途和使用示例。

+ /**
+  * 按顺序执行一系列异步操作
+  * @param actions - 异步函数数组
+  * @returns 按顺序执行的结果数组
+  * @example
+  * const actions = [
+  *   async () => await fetch('/api/1'),
+  *   async () => await fetch('/api/2')
+  * ];
+  * const results = await promiseAllSequence(actions);
+  */
export declare const promiseAllSequence: <Fn extends () => PromiseLike<any>, R = Awaited<ReturnType<Fn>>>(actions: Fn[]) => Promise<R[]>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 按顺序执行一系列异步操作
 * @param actions - 异步函数数组
 * @returns 按顺序执行的结果数组
 * @example
 * const actions = [
 *   async () => await fetch('/api/1'),
 *   async () => await fetch('/api/2')
 * ];
 * const results = await promiseAllSequence(actions);
 */
export declare const promiseAllSequence: <Fn extends () => PromiseLike<any>, R = Awaited<ReturnType<Fn>>>(actions: Fn[]) => Promise<R[]>;
third-party/utils/parseElectrumUrl.d.ts (1)

1-5: 🧹 Nitpick (assertive)

建议优化类型定义的严谨性

当前实现可以改进以下几点:

  1. 建议将 protocol 类型提取为常量联合类型
  2. 可以明确指定什么情况下会返回 undefined

建议修改为:

type Protocol = "t" | "s";
type ElectrumUrlResult = {
    host: string;
    port: number;
    protocol: Protocol;
};
export declare const parseElectrumUrl: (url: string) => ElectrumUrlResult | undefined;
third-party/utils/getLocaleSeparators.native.d.ts (1)

1-4: 🧹 Nitpick (assertive)

建议增强区域设置参数的类型安全性

函数声明基本正确,但可以通过以下方式增强类型安全:

  1. 使用 BCP 47 语言标签类型限制 locale 参数
  2. 为返回值类型创建独立的接口定义

建议修改为:

interface LocaleSeparators {
    decimalSeparator: string;
    thousandsSeparator: string;
}

export declare function getLocaleSeparators(locale: Intl.BCP47LanguageTag): LocaleSeparators;
third-party/utils/objectPartition.d.ts (1)

5-5: 🛠️ Refactor suggestion

移除多余的空导出语句

由于文件中已经有其他导出内容,这个空的导出声明是多余的。

- export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-5: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/xssFilters.d.ts (2)

1-3: 🧹 Nitpick (assertive)

建议添加详细的 JSDoc 文档

这些是安全相关的函数,建议添加:

  • 函数的具体用途
  • 输入值的要求
  • 返回值的格式
  • 使用示例

这样可以帮助开发者正确使用这些函数。

示例格式:

/**
 * 转义 HTML 内容中的特殊字符以防止 XSS 攻击
 * @param value - 需要转义的字符串
 * @returns 转义后的安全字符串
 * @example
 * inHTML('<script>alert(1)</script>') // &lt;script&gt;alert(1)&lt;/script&gt;
 */
export declare const inHTML: (value: string) => string;

1-3: 💡 Codebase verification

XSS 过滤器实现存在安全隐患

当前的 XSS 过滤实现过于简单,存在以下问题:

  • 仅替换了 <'" 字符,未考虑其他潜在的 XSS 攻击向量
  • 缺少对 > 字符的转义
  • 没有处理 Unicode 编码绕过
  • 未对 JavaScript 事件处理程序进行过滤

建议:

  • 使用成熟的 XSS 防护库如 DOMPurify 或 xss
  • 增加对更多特殊字符的转义处理
  • 实现上下文感知的过滤机制
🔗 Analysis chain

验证 XSS 过滤实现的安全性

这些函数对于安全性至关重要,需要确保实现正确。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查 XSS 过滤器的具体实现

# 查找过滤器的实现文件
echo "查找 XSS 过滤器实现:"
fd "xssFilters.js" --type f

# 检查是否使用了推荐的 XSS 防护库
echo "检查依赖项:"
rg "xss|sanitize|escape" package.json

Length of output: 262


Script:

#!/bin/bash
# 检查 XSS 过滤器的具体实现
echo "XSS 过滤器实现内容:"
cat third-party/utils/xssFilters.js

# 检查使用这些过滤器的地方
echo -e "\n使用这些过滤器的位置:"
rg "inHTML|inSingleQuotes|inDoubleQuotes" -l

Length of output: 760

third-party/utils/throwError.js (2)

1-1: 🛠️ Refactor suggestion

移除多余的 'use strict' 声明

由于使用了 ES 模块系统,'use strict' 声明是多余的,模块代码默认就是严格模式。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-6: 🧹 Nitpick (assertive)

建议添加参数验证

为了提高代码的健壮性,建议添加对 reason 参数的类型检查。

 const throwError = (reason) => {
+    if (typeof reason !== 'string') {
+        reason = String(reason);
+    }
     throw new Error(reason);
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const throwError = (reason) => {
    if (typeof reason !== 'string') {
        reason = String(reason);
    }
    throw new Error(reason);
};
third-party/utils/isArrayMember.js (2)

4-4: 🧹 Nitpick (assertive)

建议增加参数验证和空值处理

当前实现没有处理 arrnullundefined 的情况,可能会导致运行时错误。

-const isArrayMember = (value, arr) => arr.some(v => v === value);
+const isArrayMember = (value, arr) => {
+    if (!Array.isArray(arr)) {
+        return false;
+    }
+    return arr.some(v => v === value);
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const isArrayMember = (value, arr) => {
    if (!Array.isArray(arr)) {
        return false;
    }
    return arr.some(v => v === value);
};

1-1: 🛠️ Refactor suggestion

移除多余的 'use strict' 声明

ES 模块系统下不需要显式声明严格模式。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/isNotUndefined.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

由于使用了 ES 模块系统,'use strict' 声明是多余的。模块代码默认就在严格模式下运行。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-5: 🧹 Nitpick (assertive)

建议增强类型检查功能

当前实现仅检查 undefined,建议同时处理 null 的情况,使函数更加健壮。

-const isNotUndefined = (item) => typeof item !== 'undefined';
+const isNotUndefined = (item) => item != null;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const isNotUndefined = (item) => item != null;
exports.isNotUndefined = isNotUndefined;
third-party/utils/arrayDistinct.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块系统下不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-5: 🛠️ Refactor suggestion

建议优化性能

当前实现使用 indexOf 进行去重,时间复杂度为 O(n²)。建议使用 Set 优化性能。

-const arrayDistinct = (item, index, self) => self.indexOf(item) === index;
+const arrayDistinct = (arr) => [...new Set(arr)];

这样修改后:

  1. 时间复杂度降为 O(n)
  2. 使用方式更简单直观
  3. 性能显著提升

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/isHex.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块中无需使用 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-7: 🛠️ Refactor suggestion

优化正则表达式并添加输入验证

当前实现存在以下问题:

  1. 正则表达式使用了多余的全局标志 'g'
  2. 缺少输入类型验证
  3. 空字符串处理不当
 const isHex = (str) => {
+    if (typeof str !== 'string') return false;
+    if (str.length === 0) return false;
-    const regExp = /^(0x|0X)?[0-9A-Fa-f]+$/g;
+    const regExp = /^(0x|0X)?[0-9A-Fa-f]+$/;
     return regExp.test(str);
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const isHex = (str) => {
    if (typeof str !== 'string') return false;
    if (str.length === 0) return false;
    const regExp = /^(0x|0X)?[0-9A-Fa-f]+$/;
    return regExp.test(str);
};
third-party/utils/addDashesToSpaces.js (1)

1-1: 🧹 Nitpick (assertive)

建议移除多余的 "use strict" 声明

在 ES 模块中,"use strict" 声明是多余的,因为模块代码默认就是严格模式。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/countBytesInString.js (2)

1-1: 🧹 Nitpick (assertive)

建议移除多余的 "use strict" 声明

在 ES 模块中,"use strict" 声明是多余的,因为模块代码默认就是严格模式。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-4: 🛠️ Refactor suggestion

建议使用 TextEncoder 来提高准确性

当前实现使用 encodeURI 和正则表达式可能在处理某些特殊字符时不够准确。建议使用更可靠的 TextEncoder API。

-const countBytesInString = (input) => encodeURI(input).split(/%..|./).length - 1;
+const countBytesInString = (input) => new TextEncoder().encode(input).length;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const countBytesInString = (input) => new TextEncoder().encode(input).length;
third-party/utils/arrayPartition.d.ts (1)

6-6: 🛠️ Refactor suggestion

移除多余的空导出

第6行的空导出语句是多余的,因为文件中已经有其他导出。

建议应用以下修改:

- export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 5-6: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/getSynchronize.d.ts (1)

1-3: 🧹 Nitpick (assertive)

类型定义准确,建议添加文档注释

类型定义很好地处理了同步和异步操作,但建议添加JSDoc注释来说明参数和返回值的用途。

建议添加如下文档注释:

+ /**
+  * 创建一个同步函数包装器
+  * @param mutex - 可选的互斥锁实例
+  * @returns 返回一个接受action和lockId的高阶函数
+  */
export declare const getSynchronize: (mutex?: ReturnType<typeof getMutex>) => <T>(action: () => T, lockId?: keyof any) => T extends Promise<unknown> ? T : Promise<T>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 创建一个同步函数包装器
 * @param mutex - 可选的互斥锁实例
 * @returns 返回一个接受action和lockId的高阶函数
 */
export declare const getSynchronize: (mutex?: ReturnType<typeof getMutex>) => <T>(action: () => T, lockId?: keyof any) => T extends Promise<unknown> ? T : Promise<T>;
export type Synchronize = ReturnType<typeof getSynchronize>;
third-party/utils/capitalizeFirstLetter.js (2)

1-1: 🛠️ Refactor suggestion

移除多余的严格模式声明

在ES模块中,"use strict" 声明是多余的,因为模块代码默认就在严格模式下运行。

建议应用以下修改:

- "use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-4: 🛠️ Refactor suggestion

增强函数的健壮性

当前实现没有处理空字符串和非字符串输入的情况。

建议改进实现:

- const capitalizeFirstLetter = (str) => (str.charAt(0).toUpperCase() + str.slice(1));
+ const capitalizeFirstLetter = (str) => {
+   if (typeof str !== 'string' || !str) return str;
+   return str.charAt(0).toUpperCase() + str.slice(1);
+ };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const capitalizeFirstLetter = (str) => {
   if (typeof str !== 'string' || !str) return str;
   return str.charAt(0).toUpperCase() + str.slice(1);
};
third-party/utils/isFullPath.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

由于 ES 模块默认使用严格模式,不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-7: 🛠️ Refactor suggestion

需要添加输入验证和改进正则表达式

代码需要以下改进:

  1. 缺少对 path 参数的类型检查
  2. 正则表达式可以更精确地匹配路径格式

建议按如下方式修改代码:

 const isFullPath = (path) => {
+    if (typeof path !== 'string') {
+        return false;
+    }
-    const fullPathPattern = /^(\/|([a-zA-Z]:\\))/;
+    const fullPathPattern = /^(\/|[a-zA-Z]:[\\\/])/;
     return fullPathPattern.test(path);
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const isFullPath = (path) => {
    if (typeof path !== 'string') {
        return false;
    }
    const fullPathPattern = /^(\/|[a-zA-Z]:[\\\/])/;
    return fullPathPattern.test(path);
};
third-party/utils/createTimeoutPromise.js (1)

4-4: 🛠️ Refactor suggestion

需要增加参数验证和清理机制

当前实现存在以下问题:

  1. 缺少对 timeout 参数的验证
  2. 没有处理 setTimeout 的清理机制
  3. 应该支持取消超时操作

建议改进实现如下:

-const createTimeoutPromise = (timeout) => new Promise(resolve => setTimeout(resolve, timeout));
+const createTimeoutPromise = (timeout) => {
+    if (typeof timeout !== 'number' || timeout < 0) {
+        throw new Error('Timeout must be a positive number');
+    }
+    let timeoutId;
+    return {
+        promise: new Promise(resolve => {
+            timeoutId = setTimeout(resolve, timeout);
+        }),
+        cancel: () => clearTimeout(timeoutId)
+    };
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const createTimeoutPromise = (timeout) => {
    if (typeof timeout !== 'number' || timeout < 0) {
        throw new Error('Timeout must be a positive number');
    }
    let timeoutId;
    return {
        promise: new Promise(resolve => {
            timeoutId = setTimeout(resolve, timeout);
        }),
        cancel: () => clearTimeout(timeoutId)
    };
};
third-party/utils/getNumberFromPixelString.js (1)

4-4: 🛠️ Refactor suggestion

需要增强输入验证和错误处理

当前实现存在以下问题:

  1. 缺少输入验证
  2. 使用全局 parseInt 而不是 Number.parseInt
  3. 没有处理无效输入的情况
  4. 只支持 'px' 单位

建议按如下方式改进代码:

-const getNumberFromPixelString = (size) => parseInt(size.replace('px', ''), 10);
+const getNumberFromPixelString = (size) => {
+    if (typeof size !== 'string') {
+        throw new TypeError('Input must be a string');
+    }
+    const match = size.match(/^(-?\d+(?:\.\d+)?)(px|rem|em|pt)?$/);
+    if (!match) {
+        throw new Error('Invalid pixel string format');
+    }
+    return Number.parseInt(match[1], 10);
+};

这个改进版本:

  • 添加了类型检查
  • 使用了更安全的 Number.parseInt
  • 支持更多单位类型
  • 增加了错误处理
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getNumberFromPixelString = (size) => {
    if (typeof size !== 'string') {
        throw new TypeError('Input must be a string');
    }
    const match = size.match(/^(-?\d+(?:\.\d+)?)(px|rem|em|pt)?$/);
    if (!match) {
        throw new Error('Invalid pixel string format');
    }
    return Number.parseInt(match[1], 10);
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-4: Use Number.parseInt instead of the equivalent global.

ES2015 moved some globals into the Number namespace for consistency.
Safe fix: Use Number.parseInt instead.

(lint/style/useNumberNamespace)

third-party/utils/isUrl.js (3)

5-5: 🧹 Nitpick (assertive)

建议添加 JSDoc 文档

为了提高代码的可维护性,建议添加函数文档:

+/**
+ * 检查字符串是否为有效的 URL
+ * @param {string} value - 要检查的字符串
+ * @returns {boolean} 如果是有效的 URL 则返回 true
+ */
const isUrl = (value) => URL_REGEXP.test(value);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 检查字符串是否为有效的 URL
 * @param {string} value - 要检查的字符串
 * @returns {boolean} 如果是有效的 URL 则返回 true
 */
const isUrl = (value) => URL_REGEXP.test(value);

1-1: 🛠️ Refactor suggestion

移除多余的 'use strict' 声明

在 ES 模块中,'use strict' 是默认的,不需要显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-4: 🧹 Nitpick (assertive)

正则表达式可以改进以提供更好的 URL 验证

当前的正则表达式可能会错过一些有效的 URL 格式。建议使用更完整的正则表达式来处理:

  • 国际化域名(IDN)
  • IPv4 和 IPv6 地址
  • URL 编码字符
-const URL_REGEXP = /^(http|ws)s?:\/\/[a-z0-9]([a-z0-9.-]+)?(:[0-9]{1,5})?((\/)?(([a-z0-9-_])+(\/)?)+)$/i;
+const URL_REGEXP = /^(http|ws)s?:\/\/(?:[a-zA-Z0-9\u00a1-\uffff](?:[a-zA-Z0-9\u00a1-\uffff-]{0,61}[a-zA-Z0-9\u00a1-\uffff])?\.)+[a-zA-Z\u00a1-\uffff]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/i;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const URL_REGEXP = /^(http|ws)s?:\/\/(?:[a-zA-Z0-9\u00a1-\uffff](?:[a-zA-Z0-9\u00a1-\uffff-]{0,61}[a-zA-Z0-9\u00a1-\uffff])?\.)+[a-zA-Z\u00a1-\uffff]{2,}(?::\d{1,5})?(?:\/[^\s]*)?$/i;
third-party/utils/createLazy.d.ts (1)

1-6: 🧹 Nitpick (assertive)

建议添加详细的类型文档

为了提高 API 的可用性,建议添加更详细的类型文档:

+/**
+ * 创建一个懒加载值的包装器
+ * @template T - 懒加载值的类型
+ * @template TArgs - 初始化函数参数的类型数组
+ * @param {(...args: TArgs) => Promise<T>} initLazy - 初始化函数
+ * @param {(t: T) => void} [disposeLazy] - 可选的资源释放函数
+ * @returns 懒加载值的控制对象
+ */
export declare const createLazy: <T, TArgs extends Array<any>>(
    initLazy: (...args: TArgs) => Promise<T>,
    disposeLazy?: (t: T) => void
) => {
+    /** 获取当前值,如果未初始化则返回 undefined */
    get: () => T | undefined;
+    /** 获取当前待处理的 Promise,如果没有则返回 undefined */
    getPending: () => Promise<T> | undefined;
+    /** 获取或初始化值 */
    getOrInit: (...args: TArgs) => Promise<T>;
+    /** 释放资源 */
    dispose: () => void;
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 创建一个懒加载值的包装器
 * @template T - 懒加载值的类型
 * @template TArgs - 初始化函数参数的类型数组
 * @param {(...args: TArgs) => Promise<T>} initLazy - 初始化函数
 * @param {(t: T) => void} [disposeLazy] - 可选的资源释放函数
 * @returns 懒加载值的控制对象
 */
export declare const createLazy: <T, TArgs extends Array<any>>(
    initLazy: (...args: TArgs) => Promise<T>,
    disposeLazy?: (t: T) => void
) => {
    /** 获取当前值,如果未初始化则返回 undefined */
    get: () => T | undefined;
    /** 获取当前待处理的 Promise,如果没有则返回 undefined */
    getPending: () => Promise<T> | undefined;
    /** 获取或初始化值 */
    getOrInit: (...args: TArgs) => Promise<T>;
    /** 释放资源 */
    dispose: () => void;
};
third-party/utils/throttler.d.ts (2)

2-4: 🧹 Nitpick (assertive)

建议使用更具体的类型

对于内部存储的映射,建议使用更明确的类型定义:

-    private readonly intervals;
-    private readonly callbacks;
+    private readonly intervals: Map<string, NodeJS.Timeout>;
+    private readonly callbacks: Map<string, () => void>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    private readonly delay;
    private readonly intervals: Map<string, NodeJS.Timeout>;
    private readonly callbacks: Map<string, () => void>;

1-10: 🧹 Nitpick (assertive)

建议改进类型定义和添加文档

类型定义可以更严格,同时添加完整的文档说明:

+/**
+ * 用于控制回调函数执行频率的节流器
+ */
 export declare class Throttler {
-    private readonly delay;
+    /** 节流延迟时间(毫秒) */
+    private readonly delay: number;
+    /** 存储定时器ID的映射 */
     private readonly intervals;
+    /** 存储回调函数的映射 */
     private readonly callbacks;
 
-    constructor(delay: number);
+    /**
+     * @param delay - 节流延迟时间(毫秒),必须大于 0
+     * @throws {Error} 当 delay 小于或等于 0 时抛出错误
+     */
+    constructor(delay: number);
 
+    /**
+     * 注册一个需要节流的回调函数
+     * @param id - 唯一标识符
+     * @param callback - 要执行的回调函数
+     */
     throttle(id: string, callback: () => void): void;
 
+    /** 内部定时器触发函数 */
     private tick;
 
+    /**
+     * 取消指定 ID 的节流回调
+     * @param id - 要取消的回调的唯一标识符
+     */
     cancel(id: string): void;
 
+    /** 释放所有资源 */
     dispose(): void;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 用于控制回调函数执行频率的节流器
 */
export declare class Throttler {
    /** 节流延迟时间(毫秒) */
    private readonly delay: number;
    /** 存储定时器ID的映射 */
    private readonly intervals;
    /** 存储回调函数的映射 */
    private readonly callbacks;

    /**
     * @param delay - 节流延迟时间(毫秒),必须大于 0
     * @throws {Error} 当 delay 小于或等于 0 时抛出错误
     */
    constructor(delay: number);

    /**
     * 注册一个需要节流的回调函数
     * @param id - 唯一标识符
     * @param callback - 要执行的回调函数
     */
    throttle(id: string, callback: () => void): void;

    /** 内部定时器触发函数 */
    private tick;

    /**
     * 取消指定 ID 的节流回调
     * @param id - 要取消的回调的唯一标识符
     */
    cancel(id: string): void;

    /** 释放所有资源 */
    dispose(): void;
}
third-party/utils/bigNumber.js (1)

1-1: 🧹 Nitpick (assertive)

移除多余的 "use strict" 声明

由于 ES 模块默认启用严格模式,这里不需要显式声明 "use strict"。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/getWeakRandomNumberInRange.js (1)

4-4: 🛠️ Refactor suggestion

建议添加参数验证

当前实现缺少必要的参数验证,建议添加以下检查:

  • 确保 min 和 max 都是有效数字
  • 验证 max 大于 min
  • 处理参数为空的情况
-const getWeakRandomNumberInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
+const getWeakRandomNumberInRange = (min, max) => {
+  if (typeof min !== 'number' || typeof max !== 'number') {
+    throw new Error('参数必须是数字类型');
+  }
+  if (max <= min) {
+    throw new Error('max 必须大于 min');
+  }
+  return Math.floor(Math.random() * (max - min + 1)) + min;
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getWeakRandomNumberInRange = (min, max) => {
  if (typeof min !== 'number' || typeof max !== 'number') {
    throw new Error('参数必须是数字类型');
  }
  if (max <= min) {
    throw new Error('max 必须大于 min');
  }
  return Math.floor(Math.random() * (max - min + 1)) + min;
};
third-party/utils/enumUtils.d.ts (1)

5-5: 🧹 Nitpick (assertive)

删除多余的空导出语句

由于文件中已有其他导出内容,这个空的导出声明是多余的。

-export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-5: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/hasUppercaseLetter.js (2)

4-4: 🛠️ Refactor suggestion

优化正则表达式实现

建议使用正则表达式字面量来提高代码可读性和性能。同时,可以简化正则表达式模式。

-const HAS_UPPERCASE_LATER_REGEXP = new RegExp('^(.*[A-Z].*)$');
+const HAS_UPPERCASE_LATER_REGEXP = /[A-Z]/;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const HAS_UPPERCASE_LATER_REGEXP = /[A-Z]/;
🧰 Tools
🪛 Biome (1.9.4)

[error] 4-4: Use a regular expression literal instead of the RegExp constructor.

Regular expression literals avoid some escaping required in a string literal, and are easier to analyze statically.
Safe fix: Use a literal notation instead.

(lint/complexity/useRegexLiterals)


1-1: 🛠️ Refactor suggestion

移除多余的 'use strict' 声明

在 ES 模块中,'use strict' 是默认行为,无需显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/arrayPartition.js (2)

1-1: 🛠️ Refactor suggestion

移除多余的 'use strict' 声明

在 ES 模块中,'use strict' 是默认行为,无需显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-4: 🛠️ Refactor suggestion

建议重构以提高可读性和性能

当前实现使用了单行复杂的 reduce 操作,建议重构为更易读和性能更好的版本。

-const arrayPartition = (array, condition) => array.reduce(([pass, fail], elem) => condition(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]], [[], []]);
+const arrayPartition = (array, condition) => {
+  const pass = [];
+  const fail = [];
+  
+  for (const elem of array) {
+    if (condition(elem)) {
+      pass.push(elem);
+    } else {
+      fail.push(elem);
+    }
+  }
+  
+  return [pass, fail];
+};

优化说明:

  1. 提高了代码可读性
  2. 通过使用 push 而不是展开运算符提升了性能
  3. 减少了内存分配
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const arrayPartition = (array, condition) => {
  const pass = [];
  const fail = [];
  
  for (const elem of array) {
    if (condition(elem)) {
      pass.push(elem);
    } else {
      fail.push(elem);
    }
  }
  
  return [pass, fail];
};
third-party/utxo-lib/compose/request.d.ts (1)

4-4: 🛠️ Refactor suggestion

移除多余的空导出语句

由于文件中已经有其他导出内容,这个空导出语句是多余的。

- export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 3-4: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/typedEventEmitter.js (2)

1-4: 🧹 Nitpick (assertive)

优化模块导入和指令

有两处可以改进的地方:

  1. 移除多余的 "use strict" 指令,因为模块默认就是严格模式
  2. 使用 node: 协议导入 Node.js 内置模块
- "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypedEmitter = void 0;
- const events_1 = require("events");
+ const events_1 = require("node:events");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Object.defineProperty(exports, "__esModule", { value: true });
exports.TypedEmitter = void 0;
const events_1 = require("node:events");
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


[error] 4-4: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)


5-9: 🧹 Nitpick (assertive)

简化 listenerCount 方法实现

当前的 listenerCount 方法只是简单调用父类方法,没有添加任何新功能。如果没有计划在将来扩展此方法,建议移除它。

class TypedEmitter extends events_1.EventEmitter {
-    listenerCount(eventName) {
-        return super.listenerCount(eventName);
-    }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

class TypedEmitter extends events_1.EventEmitter {
}
third-party/utils/redactUserPath.js (2)

5-5: 🛠️ Refactor suggestion

缺少输入验证

函数应该检查输入参数是否为字符串类型,以防止运行时错误。

-const redactUserPathFromString = (text) => text.replace(exports.startOfUserPathRegex, '$1[*]');
+const redactUserPathFromString = (text) => {
+  if (typeof text !== 'string') return '';
+  return text.replace(exports.startOfUserPathRegex, '$1[*]');
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const redactUserPathFromString = (text) => {
  if (typeof text !== 'string') return '';
  return text.replace(exports.startOfUserPathRegex, '$1[*]');
};

4-4: 🧹 Nitpick (assertive)

正则表达式可以更严格

当前的正则表达式可能会匹配到不必要的路径。建议增加更严格的边界检查。

-exports.startOfUserPathRegex = /([/\\][Uu]sers[/\\]{1,4})([^"^'^[^\]^/^\\]*)/g;
+exports.startOfUserPathRegex = /(?:^|[/\\])([Uu]sers[/\\]{1,2})([^"'^[\]/\\]+)/g;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

exports.startOfUserPathRegex = /(?:^|[/\\])([Uu]sers[/\\]{1,2})([^"'^[\]/\\]+)/g;
third-party/utils/splitStringEveryNCharacters.js (1)

4-11: 🛠️ Refactor suggestion

需要改进代码质量和安全性

代码存在以下问题:

  1. 使用了 var 声明变量
  2. 缺少对 value 参数的类型检查
  3. 表达式中的赋值操作可读性较差

建议按如下方式重构:

 function splitStringEveryNCharacters(value, n) {
-    var _a;
+    if (typeof value !== 'string') {
+        return [];
+    }
     if (n === 0) {
         return [];
     }
     const regex = new RegExp(`.{1,${n}}`, 'g');
-    return (_a = value.match(regex)) !== null && _a !== void 0 ? _a : [];
+    const matches = value.match(regex);
+    return matches ?? [];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function splitStringEveryNCharacters(value, n) {
    if (typeof value !== 'string') {
        return [];
    }
    if (n === 0) {
        return [];
    }
    const regex = new RegExp(`.{1,${n}}`, 'g');
    const matches = value.match(regex);
    return matches ?? [];
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 10-10: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 5-5: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utils/enumUtils.js (2)

8-11: 🛠️ Refactor suggestion

getValueByKey 函数可以优化

当前实现存在以下问题:

  1. 重复调用 Object.keys()
  2. 缺少参数验证
  3. 查找效率不高
 function getValueByKey(obj, enumKey) {
-    const key = obj && Object.keys(obj).find(x => x === enumKey);
-    return key && obj[key];
+    if (obj == null || typeof obj !== 'object') {
+        return undefined;
+    }
+    return obj[enumKey];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function getValueByKey(obj, enumKey) {
    if (obj == null || typeof obj !== 'object') {
        return undefined;
    }
    return obj[enumKey];
}

5-7: 🛠️ Refactor suggestion

getKeyByValue 函数需要增强健壮性

函数缺少必要的类型检查,且在大型对象上可能性能不佳。

 function getKeyByValue(obj, value) {
+    if (obj == null || typeof obj !== 'object') {
+        return undefined;
+    }
     return obj && Object.keys(obj).find(x => obj[x] === value);
 }

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/parseHostname.js (2)

4-4: 🧹 Nitpick (assertive)

建议为正则表达式添加注释说明

正则表达式 HOSTNAME_REGEX 较为复杂,建议添加注释说明各个匹配组的作用,以提高代码可读性。

-const HOSTNAME_REGEX = /^([a-z0-9.+-]+:\/\/)?([a-z0-9.-]+)([:/][^:/]+)*\/?$/i;
+// 正则表达式解析:
+// 1. ([a-z0-9.+-]+:\/\/)? - 可选的协议部分 (例如 "http://")
+// 2. ([a-z0-9.-]+) - 主机名部分
+// 3. ([:/][^:/]+)* - 可选的路径或端口
+// 4. \/? - 可选的结尾斜杠
+const HOSTNAME_REGEX = /^([a-z0-9.+-]+:\/\/)?([a-z0-9.-]+)([:/][^:/]+)*\/?$/i;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// 正则表达式解析:
// 1. ([a-z0-9.+-]+:\/\/)? - 可选的协议部分 (例如 "http://")
// 2. ([a-z0-9.-]+) - 主机名部分
// 3. ([:/][^:/]+)* - 可选的路径或端口
// 4. \/? - 可选的结尾斜杠
const HOSTNAME_REGEX = /^([a-z0-9.+-]+:\/\/)?([a-z0-9.-]+)([:/][^:/]+)*\/?$/i;

5-5: 🧹 Nitpick (assertive)

建议重构链式表达式以提高可读性

当前的链式表达式较难理解,建议拆分成多个步骤以提高代码的可读性和可维护性。

-const parseHostname = (url) => { var _a, _b; return (_b = (_a = url.match(HOSTNAME_REGEX)) === null || _a === void 0 ? void 0 : _a[2]) === null || _b === void 0 ? void 0 : _b.toLowerCase(); };
+const parseHostname = (url) => {
+    const matches = url.match(HOSTNAME_REGEX);
+    if (!matches) return undefined;
+    const hostname = matches[2];
+    return hostname?.toLowerCase();
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const parseHostname = (url) => {
    const matches = url.match(HOSTNAME_REGEX);
    if (!matches) return undefined;
    const hostname = matches[2];
    return hostname?.toLowerCase();
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 5-5: Declare variables separately

Unsafe fix: Break out into multiple declarations

(lint/style/useSingleVarDeclarator)


[error] 5-5: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 5-5: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 5-5: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utils/createCooldown.js (1)

4-14: 🧹 Nitpick (assertive)

建议添加参数验证和边界条件处理

当前实现没有对 cooldownMs 参数进行验证,可能导致意外行为。建议添加参数验证并处理边界情况。

 const createCooldown = (cooldownMs) => {
+    if (typeof cooldownMs !== 'number' || cooldownMs < 0) {
+        throw new Error('cooldownMs 必须是一个非负数');
+    }
     let last = 0;
     return () => {
         const now = Date.now();
         if (now - last >= cooldownMs) {
             last = now;
             return true;
         }
         return false;
     };
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const createCooldown = (cooldownMs) => {
    if (typeof cooldownMs !== 'number' || cooldownMs < 0) {
        throw new Error('cooldownMs 必须是一个非负数');
    }
    let last = 0;
    return () => {
        const now = Date.now();
        if (now - last >= cooldownMs) {
            last = now;
            return true;
        }
        return false;
    };
};
third-party/utils/arrayShuffle.js (1)

4-11: 🛠️ Refactor suggestion

建议增加输入验证和算法说明

当前实现使用了 Fisher-Yates 洗牌算法,但缺少必要的输入验证和算法说明。同时,对于大数组,slice() 操作可能会影响性能。

+/**
+ * 使用 Fisher-Yates 算法对数组进行随机洗牌
+ * @param {Array} array - 输入数组
+ * @param {Object} options - 配置选项
+ * @param {Function} options.randomInt - 生成指定范围内随机整数的函数
+ * @returns {Array} 洗牌后的新数组
+ */
 const arrayShuffle = (array, { randomInt }) => {
+    if (!Array.isArray(array)) {
+        throw new TypeError('第一个参数必须是数组');
+    }
+    if (typeof randomInt !== 'function') {
+        throw new TypeError('randomInt 必须是一个函数');
+    }
     const shuffled = array.slice();
     for (let i = shuffled.length - 1; i > 0; i--) {
         const j = randomInt(0, i + 1);
         [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
     }
     return shuffled;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 使用 Fisher-Yates 算法对数组进行随机洗牌
 * @param {Array} array - 输入数组
 * @param {Object} options - 配置选项
 * @param {Function} options.randomInt - 生成指定范围内随机整数的函数
 * @returns {Array} 洗牌后的新数组
 */
const arrayShuffle = (array, { randomInt }) => {
    if (!Array.isArray(array)) {
        throw new TypeError('第一个参数必须是数组');
    }
    if (typeof randomInt !== 'function') {
        throw new TypeError('randomInt 必须是一个函数');
    }
    const shuffled = array.slice();
    for (let i = shuffled.length - 1; i > 0; i--) {
        const j = randomInt(0, i + 1);
        [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
};
third-party/utils/getSynchronize.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块默认启用严格模式,不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


5-8: 🧹 Nitpick (assertive)

建议增加错误处理机制

当前实现没有处理 action 执行失败的具体错误信息,建议添加 try-catch 来更好地处理异常情况。

 const getSynchronize = (mutex) => {
     const lock = mutex !== null && mutex !== void 0 ? mutex : (0, getMutex_1.getMutex)();
-    return (action, lockId) => lock(lockId).then(unlock => Promise.resolve().then(action).finally(unlock));
+    return (action, lockId) => lock(lockId).then(unlock => 
+        Promise.resolve()
+            .then(action)
+            .catch(error => {
+                console.error(`Action execution failed: ${error.message}`);
+                throw error;
+            })
+            .finally(unlock)
+    );
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getSynchronize = (mutex) => {
    const lock = mutex !== null && mutex !== void 0 ? mutex : (0, getMutex_1.getMutex)();
    return (action, lockId) => lock(lockId).then(unlock => 
        Promise.resolve()
            .then(action)
            .catch(error => {
                console.error(`Action execution failed: ${error.message}`);
                throw error;
            })
            .finally(unlock)
    );
};
third-party/utils/getWeakRandomInt.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块默认启用严格模式,不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-9: ⚠️ Potential issue

安全警告:Math.random() 不适用于安全敏感场景

当前实现使用 Math.random() 生成随机数,这个方法不适合用于加密或安全敏感的场景。如果需要更安全的随机数生成,建议使用 crypto.randomBytes()。

另外,建议增加对输入参数的类型检查:

 const getWeakRandomInt = (min, max) => {
+    if (typeof min !== 'number' || typeof max !== 'number') {
+        throw new TypeError('min 和 max 必须是数字类型');
+    }
     if (min >= max) {
         throw new RangeError(`The value of "max" is out of range. It must be greater than the value of "min" (${min}). Received ${max}`);
     }
     return Math.floor(Math.random() * (max - min) + min);
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getWeakRandomInt = (min, max) => {
    if (typeof min !== 'number' || typeof max !== 'number') {
        throw new TypeError('min 和 max 必须是数字类型');
    }
    if (min >= max) {
        throw new RangeError(`The value of "max" is out of range. It must be greater than the value of "min" (${min}). Received ${max}`);
    }
    return Math.floor(Math.random() * (max - min) + min);
};
third-party/utils/asciiUtils.js (3)

5-5: 🧹 Nitpick (assertive)

优化正则表达式性能

建议将正则表达式对象缓存并添加适当的注释说明匹配范围。

-const nonAsciiPattern = /[^\x20-\x7E]/g;
+// 匹配范围:空格 (0x20) 到波浪号 (0x7E) 之外的所有字符
+const nonAsciiPattern = Object.freeze(/[^\x20-\x7E]/g);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// 匹配范围:空格 (0x20) 到波浪号 (0x7E) 之外的所有字符
const nonAsciiPattern = Object.freeze(/[^\x20-\x7E]/g);

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块默认启用严格模式,不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


6-15: 🛠️ Refactor suggestion

增强输入验证和类型检查

建议添加更严格的类型检查,并优化返回值的一致性。

 function isAscii(value) {
+    if (typeof value !== 'string' && value != null) {
+        throw new TypeError('输入必须是字符串类型');
+    }
     if (!value)
         return true;
     return !nonAsciiPattern.test(value);
 }
 
 function getNonAsciiChars(value) {
+    if (typeof value !== 'string' && value != null) {
+        throw new TypeError('输入必须是字符串类型');
+    }
     if (!value)
-        return null;
+        return [];
     return value.match(nonAsciiPattern) || [];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function isAscii(value) {
    if (typeof value !== 'string' && value != null) {
        throw new TypeError('输入必须是字符串类型');
    }
    if (!value)
        return true;
    return !nonAsciiPattern.test(value);
}

function getNonAsciiChars(value) {
    if (typeof value !== 'string' && value != null) {
        throw new TypeError('输入必须是字符串类型');
    }
    if (!value)
        return [];
    return value.match(nonAsciiPattern) || [];
}
third-party/utils/truncateMiddle.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

由于 JavaScript 模块默认启用严格模式,此声明是多余的。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-10: 🧹 Nitpick (assertive)

建议添加参数验证

函数实现逻辑正确,但缺少必要的参数验证。

建议添加以下验证:

 const truncateMiddle = (text, startChars, endChars) => {
+    if (typeof text !== 'string') return '';
+    if (startChars < 0 || endChars < 0) return text;
     if (text.length <= startChars + endChars)
         return text;
     const start = text.substring(0, startChars);
     const end = text.substring(text.length - endChars, text.length);
     return `${start}…${end}`;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const truncateMiddle = (text, startChars, endChars) => {
    if (typeof text !== 'string') return '';
    if (startChars < 0 || endChars < 0) return text;
    if (text.length <= startChars + endChars)
        return text;
    const start = text.substring(0, startChars);
    const end = text.substring(text.length - endChars, text.length);
    return `${start}…${end}`;
};
third-party/utils/getWeakRandomId.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

由于 JavaScript 模块默认启用严格模式,此声明是多余的。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-11: ⚠️ Potential issue

安全性警告:使用更安全的随机数生成方法

当前实现使用 Math.random() 生成随机 ID,这在安全性要求高的场景下可能存在风险。建议使用 crypto.getRandomValues() 替代。

建议修改实现如下:

 const getWeakRandomId = (length) => {
+    if (typeof length !== 'number' || length <= 0) return '';
     let id = '';
     const list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
-    for (let i = 0; i < length; i++) {
-        id += list.charAt(Math.floor(Math.random() * list.length));
-    }
+    const array = new Uint8Array(length);
+    crypto.getRandomValues(array);
+    for (let i = 0; i < length; i++) {
+        id += list.charAt(array[i] % list.length);
+    }
     return id;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getWeakRandomId = (length) => {
    if (typeof length !== 'number' || length <= 0) return '';
    let id = '';
    const list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const array = new Uint8Array(length);
    crypto.getRandomValues(array);
    for (let i = 0; i < length; i++) {
        id += list.charAt(array[i] % list.length);
    }
    return id;
};
third-party/utxo-lib/compose/sorting/convertOutput.d.ts (1)

2-12: 🧹 Nitpick (assertive)

建议优化类型定义结构

当前类型定义可读性较差,建议使用类型别名(type alias)来提高可维护性。

建议重构为:

+type ChangeOutput = {
+    amount: string;
+    type: "change";
+    address: string;
+};
+
+type PaymentOutput = {
+    type: "payment";
+    amount: string;
+    address: string;
+};
+
+type OutputType = import("../../types").ComposeOutputOpreturn | ChangeOutput | PaymentOutput;
+
-export declare const convertOutput: (selectedOutput: CoinSelectOutputFinal, composeOutput: ComposeFinalOutput | ({
-    type: "change";
-} & ComposeChangeAddress)) => import("../../types").ComposeOutputOpreturn | {
-    amount: string;
-    type: "change";
-    address: string;
-} | {
-    type: "payment";
-    amount: string;
-    address: string;
-};
+export declare const convertOutput: (
+    selectedOutput: CoinSelectOutputFinal,
+    composeOutput: ComposeFinalOutput | ({ type: "change"; } & ComposeChangeAddress)
+) => OutputType;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

type ChangeOutput = {
    amount: string;
    type: "change";
    address: string;
};

type PaymentOutput = {
    type: "payment";
    amount: string;
    address: string;
};

type OutputType = import("../../types").ComposeOutputOpreturn | ChangeOutput | PaymentOutput;

export declare const convertOutput: (
    selectedOutput: CoinSelectOutputFinal,
    composeOutput: ComposeFinalOutput | ({ type: "change"; } & ComposeChangeAddress)
) => OutputType;
third-party/utils/arrayToDictionary.d.ts (1)

8-9: 🧹 Nitpick (assertive)

移除多余的空导出

第9行的空导出语句是多余的,因为第8行已经有了具体的导出。

建议应用以下修改:

export declare const arrayToDictionary: ArrayToDictionary;
-export {};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare const arrayToDictionary: ArrayToDictionary;
🧰 Tools
🪛 Biome (1.9.4)

[error] 8-9: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/bytesToHumanReadable.js (2)

1-3: 🧹 Nitpick (assertive)

移除多余的严格模式声明

在ES模块中,严格模式是默认开启的,不需要显式声明 "use strict"。

建议移除第1行的 "use strict" 声明。

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


8-11: ⚠️ Potential issue

修复循环条件逻辑错误

当前的while循环条件存在两个问题:

  1. i >= units.length 可能导致访问 units 数组越界
  2. 条件的顺序可能导致无限循环

建议修改为:

-    while (size >= 1024 || i >= units.length) {
+    while (size >= 1024 && i < units.length - 1) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    while (size >= 1024 && i < units.length - 1) {
        size /= 1024;
        i++;
    }
third-party/utxo-lib/crypto.d.ts (1)

1-8: 🧹 Nitpick (assertive)

建议添加函数文档注释

类型定义本身没有问题,但建议为每个加密函数添加JSDoc注释,说明:

  • 函数的用途
  • 参数的要求
  • 返回值的格式
  • 可能的异常情况

示例格式:

/**
 * 计算输入数据的RIPEMD160哈希值
 * @param buffer - 要计算哈希的输入数据
 * @returns 返回32字节的哈希值
 * @throws 如果输入buffer为空或无效
 */
export declare function ripemd160(buffer: Buffer): Buffer;
third-party/utils/promiseAllSequence.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块默认启用严格模式,无需显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


5-12: 🧹 Nitpick (assertive)

建议优化 Promise 序列执行的实现

当前实现正确但可以更简洁。建议使用 reduce 方法来优化顺序执行。

-const promiseAllSequence = (actions) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
-    const results = [];
-    for (let i = 0; i < actions.length; ++i) {
-        const result = yield actions[i]();
-        results.push(result);
-    }
-    return results;
-});
+const promiseAllSequence = (actions) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
+    return actions.reduce(async (promise, action) => {
+        const results = await promise;
+        const result = await action();
+        return [...results, result];
+    }, Promise.resolve([]));
+});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const promiseAllSequence = (actions) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    return actions.reduce(async (promise, action) => {
        const results = await promise;
        const result = await action();
        return [...results, result];
    }, Promise.resolve([]));
});
third-party/utxo-lib/compose/result.d.ts (1)

1-3: 🧹 Nitpick (assertive)

类型定义清晰完整

泛型约束和类型定义设计合理,确保了类型安全性。建议添加类型文档注释以提升代码可维护性。

/**
 * 生成错误结果对象
 * @param error - 错误信息
 * @returns ComposeResultError 类型的错误结果
 */
export declare function getErrorResult(error: unknown): ComposeResultError;

/**
 * 生成交易组合结果
 * @param request - 交易组合请求
 * @param param1 - 币种选择请求参数
 * @param result - 币种选择结果
 * @returns 交易组合结果
 */
export declare function getResult<
  Input extends ComposeInput,
  Output extends ComposeOutput,
  Change extends ComposeChangeAddress
>(
  request: ComposeRequest<Input, Output, Change>,
  { sendMaxOutputIndex }: CoinSelectRequest,
  result: CoinSelectResult
): ComposeResult<Input, Output, Change>;
third-party/utils/xssFilters.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

ES 模块默认启用严格模式,无需显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-12: 💡 Codebase verification

⚠️ Potential issue

XSS 防护需要立即升级

基于代码分析结果:

  • 这是项目中唯一的 XSS 防护实现
  • 没有使用任何第三方安全库
  • 没有相关的测试用例
  • 当前实现过于简单,存在严重安全隐患

建议:

  • 立即引入 DOMPurify 等成熟的 XSS 防护库
  • 如继续使用自研方案,必须:
    1. 完善字符转义实现
    2. 添加完整的测试用例
    3. 进行安全审计
    4. 添加安全文档说明
🔗 Analysis chain

XSS 过滤器实现需要加强

当前实现只处理了基本的 XSS 向量,存在安全风险:

  1. 缺少对其他危险字符的转义(如 >, & 等)
  2. 没有处理 JavaScript 事件属性
  3. 没有处理 URL 编码的攻击向量

建议:

  1. 使用成熟的 XSS 防护库如 DOMPurify
  2. 或完善当前实现:
 const LT = /</g;
+const GT = />/g;
+const AMP = /&/g;
 const SQUOT = /'/g;
 const QUOT = /"/g;
+const BSLASH = /\\/g;
+const CR = /\r/g;
+const LF = /\n/g;
+const TAB = /\t/g;
+const NBSP = /\x0A/g;
+const QUOT_ENTITY = /&quot;/g;

-const inHTML = (value) => value.replace(LT, '&lt;');
+const inHTML = (value) => {
+    return value
+        .replace(AMP, '&amp;')
+        .replace(LT, '&lt;')
+        .replace(GT, '&gt;');
+};

-const inSingleQuotes = (value) => value.replace(SQUOT, '&#39;');
+const inSingleQuotes = (value) => {
+    return value
+        .replace(BSLASH, '\\\\')
+        .replace(SQUOT, '\\\'')
+        .replace(CR, '\\r')
+        .replace(LF, '\\n');
+};

-const inDoubleQuotes = (value) => value.replace(QUOT, '&quot;');
+const inDoubleQuotes = (value) => {
+    return value
+        .replace(BSLASH, '\\\\')
+        .replace(QUOT, '\\"')
+        .replace(CR, '\\r')
+        .replace(LF, '\\n');
+};
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查是否有其他文件依赖这些 XSS 过滤函数

# 搜索使用这些函数的地方
echo "Searching for xssFilters usage..."
rg -l "inHTML|inSingleQuotes|inDoubleQuotes"

Length of output: 189


Script:

#!/bin/bash
# 检查 xssFilters.d.ts 的内容
echo "检查类型定义文件内容:"
cat third-party/utils/xssFilters.d.ts

# 搜索项目中是否有测试文件
echo -e "\n搜索相关测试文件:"
fd -g "*test*" | grep -i "xss"

# 检查是否有其他安全相关的实现
echo -e "\n搜索其他安全相关实现:"
rg -l "sanitize|purify|escape|xss" --type js

Length of output: 629


Script:

#!/bin/bash
# 检查 index.js 中是否有其他安全相关实现
echo "检查 index.js 中的安全相关代码:"
cat third-party/utils/index.js

# 检查项目中是否有使用其他安全库
echo -e "\n检查依赖项:"
fd -g "package*.json" -x cat {} \; | grep -i "purify\|sanitize\|xss"

# 检查是否有安全配置文件
echo -e "\n检查安全配置:"
fd -g "*security*" -g "*csp*" -g "*content-security*"

Length of output: 3790

third-party/utils/scheduleAction.d.ts (2)

1-5: 🧹 Nitpick (assertive)

建议添加类型文档注释

为了提高代码可维护性,建议为每个类型定义添加 JSDoc 注释,说明其用途和参数含义。

示例:

+/**
+ * 表示一个可调度的异步操作
+ * @param signal 可选的中止信号
+ * @returns 异步操作的结果
+ */
export type ScheduledAction<T> = (signal?: AbortSignal) => Promise<T>;

+/**
+ * 尝试参数配置
+ */
type AttemptParams = {
    timeout?: number;  // 超时时间
    gap?: number;      // 重试间隔
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 表示一个可调度的异步操作
 * @param signal 可选的中止信号
 * @returns 异步操作的结果
 */
export type ScheduledAction<T> = (signal?: AbortSignal) => Promise<T>;

/**
 * 尝试参数配置
 */
type AttemptParams = {
    timeout?: number;  // 超时时间
    gap?: number;      // 重试间隔
};

11-11: 🧹 Nitpick (assertive)

建议改进类型定义

在联合类型中使用 void 可能会导致混淆,建议使用 undefined 替代。

-    attemptFailureHandler?: (error: Error) => Error | void;
+    attemptFailureHandler?: (error: Error) => Error | undefined;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    attemptFailureHandler?: (error: Error) => Error | undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 11-11: void is confusing inside a union type.

Unsafe fix: Use undefined instead.

(lint/suspicious/noConfusingVoidType)

third-party/utils/versionUtils.d.ts (1)

1-2: 🧹 Nitpick (assertive)

建议增强类型定义和文档

版本类型定义可以更严格,并且需要添加文档说明。

+/**
+ * 表示版本号的数组类型 [主版本号, 次版本号, 修订号]
+ */
-type VersionArray = [number, number, number];
+type VersionArray = [major: number, minor: number, patch: number];

+/**
+ * 版本输入类型,支持数组或字符串格式
+ * @example [1, 0, 0] 或 "1.0.0"
+ */
type VersionInput = VersionArray | string;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 表示版本号的数组类型 [主版本号, 次版本号, 修订号]
 */
type VersionArray = [major: number, minor: number, patch: number];

/**
 * 版本输入类型,支持数组或字符串格式
 * @example [1, 0, 0] 或 "1.0.0"
 */
type VersionInput = VersionArray | string;
third-party/utils/createDeferred.js (1)

5-6: 🧹 Nitpick (assertive)

建议改进函数初始化

空函数初始化可以使用更明确的方式。

-    let localResolve = () => { };
-    let localReject = () => { };
+    let localResolve: (value: any) => void;
+    let localReject: (error: any) => void;

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/createDeferred.d.ts (1)

13-13: 🛠️ Refactor suggestion

移除多余的空导出声明

这行空导出声明是多余的,因为文件中已经有其他导出。

-export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 12-13: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utxo-lib/discovery.d.ts (1)

8-8: 🧹 Nitpick (assertive)

建议优化函数参数的可读性

discovery 函数的参数较多,建议考虑使用对象参数模式来提高可读性。

-export declare const discovery: <T>(discover: (addr: AddressInfo) => Promise<AddressResult<T>>, xpub: string, type: "receive" | "change", network?: Network, lookout?: number) => Promise<AddressResult<T>[]>;
+export declare const discovery: <T>(params: {
+    discover: (addr: AddressInfo) => Promise<AddressResult<T>>;
+    xpub: string;
+    type: "receive" | "change";
+    network?: Network;
+    lookout?: number;
+}) => Promise<AddressResult<T>[]>;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

export declare const discovery: <T>(params: {
    discover: (addr: AddressInfo) => Promise<AddressResult<T>>;
    xpub: string;
    type: "receive" | "change";
    network?: Network;
    lookout?: number;
}) => Promise<AddressResult<T>[]>;
third-party/utils/objectPartition.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的严格模式声明

在 ES 模块中,严格模式是默认开启的,不需要显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


5-10: 🧹 Nitpick (assertive)

建议改进代码可读性

当前实现虽然功能正确,但可读性有待提高:

  1. 变量命名 _a_b 不够清晰
  2. 解构操作可以更直观
-const objectPartition = (obj, keys) => keys.reduce(([included, excluded], key) => {
-    const _a = excluded, _b = key, value = _a[_b], rest = tslib_1.__rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
-    return typeof value !== 'undefined'
-        ? [Object.assign(Object.assign({}, included), { [key]: value }), rest]
-        : [included, excluded];
-}, [{}, obj]);
+const objectPartition = (obj, keys) => keys.reduce(([included, excluded], key) => {
+    const value = excluded[key];
+    const { [key]: _, ...rest } = excluded;
+    
+    return typeof value !== 'undefined'
+        ? [{ ...included, [key]: value }, rest]
+        : [included, excluded];
+}, [{}, obj]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const objectPartition = (obj, keys) => keys.reduce(([included, excluded], key) => {
    const value = excluded[key];
    const { [key]: _, ...rest } = excluded;
    
    return typeof value !== 'undefined'
        ? [{ ...included, [key]: value }, rest]
        : [included, excluded];
}, [{}, obj]);
🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: Declare variables separately

Unsafe fix: Break out into multiple declarations

(lint/style/useSingleVarDeclarator)


[error] 6-6: Template literals are preferred over string concatenation.

Unsafe fix: Use a template literal.

(lint/style/useTemplate)

.github/workflows/package-publish.yml (2)

1-7: 🛠️ Refactor suggestion

工作流触发器配置需要更严格的安全控制

建议限制手动触发权限,并添加发布版本的标签过滤器,以增强发布流程的安全性。

 on: 
   workflow_dispatch:
+    permissions:
+      contents: read
+      packages: write
   release:
     types: [created]
+    tags:
+      - 'v*.*.*'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

name: NPM Package Publish

on: 
  workflow_dispatch:
    permissions:
      contents: read
      packages: write
  release:
    types: [created]
    tags:
      - 'v*.*.*'
🧰 Tools
🪛 yamllint (1.35.1)

[warning] 3-3: truthy value should be one of [false, true]

(truthy)


[error] 3-3: trailing spaces

(trailing-spaces)


20-26: ⚠️ Potential issue

npm 发布步骤需要增加安全检查

建议在发布前添加以下步骤:

  1. 运行测试
  2. 检查依赖安全性
  3. 验证包内容
       - name: Install dependencies
         run: npm ci
         
+      - name: Run tests
+        run: npm test
+        
+      - name: Security audit
+        run: npm audit
+        
+      - name: Verify package contents
+        run: npm pack && tar -tzf *.tgz
+        
       - name: Publish to NPM
         env:
           NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
         run: npm publish --access public
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      - name: Install dependencies
        run: npm ci
        
      - name: Run tests
        run: npm test
        
      - name: Security audit
        run: npm audit
        
      - name: Verify package contents
        run: npm pack && tar -tzf *.tgz
        
      - name: Publish to NPM
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: npm publish --access public
🧰 Tools
🪛 yamllint (1.35.1)

[error] 22-22: trailing spaces

(trailing-spaces)

third-party/utxo-lib/compose/sorting/sortingStrategy.d.ts (2)

8-8: 🛠️ Refactor suggestion

移除无用的空导出语句

由于文件中已有其他导出,这个空导出语句是多余的。

-export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 7-8: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)


1-7: 🧹 Nitpick (assertive)

建议添加类型文档注释

为了提高代码可维护性,建议为类型定义添加 JSDoc 注释,说明每个参数的用途和约束条件。

+/**
+ * 排序策略的参数类型
+ * @template Input - 输入类型,必须扩展自 ComposeInput
+ * @template Change - 找零地址类型,必须扩展自 ComposeChangeAddress
+ */
 type SortingStrategyParams<Input extends ComposeInput, Change extends ComposeChangeAddress> = {
     request: ComposeRequest<Input, ComposeFinalOutput, Change>;
     result: CoinSelectSuccess;
     convertedInputs: Input[];
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

import { CoinSelectSuccess, ComposeChangeAddress, ComposedTransaction, ComposeFinalOutput, ComposeInput, ComposeRequest } from '../../types';
/**
 * 排序策略的参数类型
 * @template Input - 输入类型,必须扩展自 ComposeInput
 * @template Change - 找零地址类型,必须扩展自 ComposeChangeAddress
 */
type SortingStrategyParams<Input extends ComposeInput, Change extends ComposeChangeAddress> = {
    request: ComposeRequest<Input, ComposeFinalOutput, Change>;
    result: CoinSelectSuccess;
    convertedInputs: Input[];
};
export type SortingStrategy = <Input extends ComposeInput, Change extends ComposeChangeAddress>(params: SortingStrategyParams<Input, Change>) => ComposedTransaction<Input, ComposeFinalOutput, Change>;
third-party/utils/urlToOnion.js (3)

1-3: 🛠️ Refactor suggestion

移除冗余的严格模式声明

在 ES 模块中,严格模式是默认开启的,不需要显式声明。

-"use strict";
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.urlToOnion = void 0;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Object.defineProperty(exports, "__esModule", { value: true });
exports.urlToOnion = void 0;
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


6-6: 🧹 Nitpick (assertive)

简化正则表达式并添加注释

当前的正则表达式较为复杂,建议拆分并添加注释说明各个捕获组的作用。

+    // 正则表达式组件说明:
+    // 1. (http|ws)s? - 协议(http/https/ws/wss)
+    // 2. ([^:/]+\.)? - 可选的子域名
+    // 3. ([^/.]+\.[^/.]+) - 主域名
+    // 4. (\/.*)?$ - 可选的路径
     const [, protocol, subdomain, domain, rest] = url.match(/^(http|ws)s?:\/\/([^:/]+\.)?([^/.]+\.[^/.]+)(\/.*)?$/i) ?? [];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    // 正则表达式组件说明:
    // 1. (http|ws)s? - 协议(http/https/ws/wss)
    // 2. ([^:/]+\.)? - 可选的子域名
    // 3. ([^/.]+\.[^/.]+) - 主域名
    // 4. (\/.*)?$ - 可选的路径
    const [, protocol, subdomain, domain, rest] = url.match(/^(http|ws)s?:\/\/([^:/]+\.)?([^/.]+\.[^/.]+)(\/.*)?$/i) ?? [];
🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


4-10: 🛠️ Refactor suggestion

优化代码结构并增强输入验证

代码需要以下改进:

  1. 使用 const/let 替代 var
  2. 添加输入参数验证
  3. 提供更好的错误处理
 const urlToOnion = (url, onionDomains) => {
-    var _a;
+    if (!url || typeof url !== 'string') {
+        return undefined;
+    }
+    if (!onionDomains || typeof onionDomains !== 'object') {
+        return undefined;
+    }
+
+    let match;
     const [, protocol, subdomain, domain, rest] = (_a = url.match(/^(http|ws)s?:\/\/([^:/]+\.)?([^/.]+\.[^/.]+)(\/.*)?$/i)) !== null && _a !== void 0 ? _a : [];
     if (!domain || !onionDomains[domain])
         return;
     return `${protocol}://${subdomain !== null && subdomain !== void 0 ? subdomain : ''}${onionDomains[domain]}${rest !== null && rest !== void 0 ? rest : ''}`;
 };

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 5-5: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utils/parseElectrumUrl.js (3)

4-4: 🧹 Nitpick (assertive)

建议添加正则表达式注释

正则表达式 ELECTRUM_URL_REGEX 虽然功能完整,但可读性不高。建议添加注释说明各个捕获组的作用。

-const ELECTRUM_URL_REGEX = /^(?:([a-zA-Z0-9.-]+)|\[([a-f0-9:]+)\]):([0-9]{1,5}):([ts])$/;
+// 匹配 Electrum URL 格式:
+// 组1: 域名 (如 example.com)
+// 组2: IPv6 地址 (如 [2001:db8::1])
+// 组3: 端口号 (1-65535)
+// 组4: 协议类型 (t 或 s)
+const ELECTRUM_URL_REGEX = /^(?:([a-zA-Z0-9.-]+)|\[([a-f0-9:]+)\]):([0-9]{1,5}):([ts])$/;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// 匹配 Electrum URL 格式:
// 组1: 域名 (如 example.com)
// 组2: IPv6 地址 (如 [2001:db8::1])
// 组3: 端口号 (1-65535)
// 组4: 协议类型 (t 或 s)
const ELECTRUM_URL_REGEX = /^(?:([a-zA-Z0-9.-]+)|\[([a-f0-9:]+)\]):([0-9]{1,5}):([ts])$/;

6-6: 🛠️ Refactor suggestion

使用 const 替代 var

使用 const 声明变量可以提高代码的可维护性和安全性。

-    var _a;
+    const _a;

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 6-6: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)


11-14: 🧹 Nitpick (assertive)

代码逻辑正确,建议优化类型检查

返回对象的构造逻辑正确,但建议增加端口号的范围验证。

     return {
         host: (_a = match[1]) !== null && _a !== void 0 ? _a : match[2],
-        port: Number.parseInt(match[3], 10),
+        port: validatePort(Number.parseInt(match[3], 10)),
         protocol: match[4],
     };

+function validatePort(port) {
+    if (port < 1 || port > 65535) {
+        throw new Error('端口号必须在 1-65535 范围内');
+    }
+    return port;
+}

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 Biome (1.9.4)

[error] 11-11: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)

third-party/utxo-lib/compose/sorting/convertOutput.js (1)

4-12: 🛠️ Refactor suggestion

建议优化对象合并逻辑和类型检查

当前实现有以下几点可以改进:

  1. 使用双重 Object.assign 是多余的
  2. 缺少输入参数验证
  3. 类型检查可以更严格
 const convertOutput = (selectedOutput, composeOutput) => {
+    if (!selectedOutput?.value || !composeOutput?.type) {
+        throw new Error('无效的输入参数');
+    }
+
     if (composeOutput.type === 'change') {
-        return Object.assign(Object.assign({}, composeOutput), { amount: selectedOutput.value.toString() });
+        return { ...composeOutput, amount: selectedOutput.value.toString() };
     }
 
     if (composeOutput.type === 'opreturn') {
         return composeOutput;
     }
 
-    return Object.assign(Object.assign({}, composeOutput), { type: 'payment', amount: selectedOutput.value.toString() });
+    return { ...composeOutput, type: 'payment', amount: selectedOutput.value.toString() };
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const convertOutput = (selectedOutput, composeOutput) => {
    if (!selectedOutput?.value || !composeOutput?.type) {
        throw new Error('无效的输入参数');
    }

    if (composeOutput.type === 'change') {
        return { ...composeOutput, amount: selectedOutput.value.toString() };
    }

    if (composeOutput.type === 'opreturn') {
        return composeOutput;
    }

    return { ...composeOutput, type: 'payment', amount: selectedOutput.value.toString() };
};
third-party/utils/logsManager.d.ts (1)

2-16: 🧹 Nitpick (assertive)

建议添加 JSDoc 文档和完善类型定义

类定义清晰,但缺少必要的文档说明和一些具体的类型约束。

+/**
+ * 日志管理器类
+ * @class LogsManager
+ */
 export declare class LogsManager {
     logs: {
         [k: string]: Log;
     };
     writer: LogWriter | undefined;
-    colors?: Record<string, string>;
+    colors?: Record<'error' | 'warn' | 'info' | 'debug', string>;
 
     constructor({ colors }: {
-        colors?: Record<string, string>;
+        colors?: Record<'error' | 'warn' | 'info' | 'debug', string>;
     });
 
+    /**
+     * 初始化日志实例
+     * @param prefix - 日志前缀
+     * @param enabled - 是否启用日志
+     * @param logWriter - 自定义日志写入器
+     * @returns Log 实例
+     */
     initLog(prefix: string, enabled?: boolean, logWriter?: LogWriter): Log;
 
+    /**
+     * 设置日志写入器
+     * @param logWriterFactory - 日志写入器工厂函数
+     */
     setLogWriter(logWriterFactory: () => LogWriter | undefined): void;
 
+    /**
+     * 启用或禁用所有日志
+     * @param enabled - 是否启用
+     */
     enableLog(enabled?: boolean): void;
 
+    /**
+     * 根据前缀启用或禁用日志
+     * @param prefix - 日志前缀
+     * @param enabled - 是否启用
+     */
     enableLogByPrefix(prefix: string, enabled: boolean): void;
 
+    /**
+     * 获取所有日志消息
+     * @returns 日志消息数组
+     */
     getLog(): LogMessage[];
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

/**
 * 日志管理器类
 * @class LogsManager
 */
export declare class LogsManager {
    logs: {
        [k: string]: Log;
    };
    writer: LogWriter | undefined;
    colors?: Record<'error' | 'warn' | 'info' | 'debug', string>;
    constructor({ colors }: {
        colors?: Record<'error' | 'warn' | 'info' | 'debug', string>;
    });

    /**
     * 初始化日志实例
     * @param prefix - 日志前缀
     * @param enabled - 是否启用日志
     * @param logWriter - 自定义日志写入器
     * @returns Log 实例
     */
    initLog(prefix: string, enabled?: boolean, logWriter?: LogWriter): Log;

    /**
     * 设置日志写入器
     * @param logWriterFactory - 日志写入器工厂函数
     */
    setLogWriter(logWriterFactory: () => LogWriter | undefined): void;

    /**
     * 启用或禁用所有日志
     * @param enabled - 是否启用
     */
    enableLog(enabled?: boolean): void;

    /**
     * 根据前缀启用或禁用日志
     * @param prefix - 日志前缀
     * @param enabled - 是否启用
     */
    enableLogByPrefix(prefix: string, enabled: boolean): void;

    /**
     * 获取所有日志消息
     * @returns 日志消息数组
     */
    getLog(): LogMessage[];
}
third-party/utils/createDeferredManager.d.ts (1)

18-18: 🧹 Nitpick (assertive)

移除多余的空导出声明

第18行的空导出声明是多余的,因为文件中已经有其他导出。

建议应用以下修改:

-export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 17-18: This empty export is useless because there's another export or import.

This export makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)

third-party/utils/getLocaleSeparators.native.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

在 ES 模块中,'use strict' 声明是多余的,因为模块代码默认就是严格模式。

建议删除第1行的 'use strict' 声明。

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-16: ⚠️ Potential issue

建议改进数字格式解析的健壮性

当前实现存在以下潜在问题:

  1. 通过固定位置(length-3)获取小数分隔符可能不适用于所有区域设置
  2. 对数字格式的长度做出了假设
  3. 缺少错误处理机制

建议使用更可靠的 formatToParts 方法,就像 non-native 版本那样实现。

建议应用以下修改:

 function getLocaleSeparators(locale) {
-    const formattedNumber = new Intl.NumberFormat(locale).format(1234567.89);
-    let thousandsSeparator = ' ';
-    let decimalSeparator = '.';
-    for (let i = 0; i < formattedNumber.length; i++) {
-        if (!/\d/.test(formattedNumber[i])) {
-            thousandsSeparator = formattedNumber[i];
-            break;
-        }
-    }
-    decimalSeparator = formattedNumber[formattedNumber.length - 3];
+    const parts = new Intl.NumberFormat(locale).formatToParts(1234567.89);
+    const decimalSeparator = parts.find(({type}) => type === 'decimal')?.value || '.';
+    const thousandsSeparator = parts.find(({type}) => type === 'group')?.value || ' ';
     return { decimalSeparator, thousandsSeparator };
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function getLocaleSeparators(locale) {
    const parts = new Intl.NumberFormat(locale).formatToParts(1234567.89);
    const decimalSeparator = parts.find(({type}) => type === 'decimal')?.value || '.';
    const thousandsSeparator = parts.find(({type}) => type === 'group')?.value || ' ';
    return { decimalSeparator, thousandsSeparator };
}
third-party/utils/getLocaleSeparators.js (1)

1-12: 🧹 Nitpick (assertive)

优化代码风格

有几处代码风格可以改进:

  1. 移除多余的 'use strict'
  2. 使用 const 替代 var
  3. 简化变量声明

建议应用以下修改:

-"use strict";
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.getLocaleSeparators = void 0;
 const getLocaleSeparators = (locale) => {
-    var _a, _b;
     const numberFormat = new Intl.NumberFormat(locale);
     const parts = numberFormat.formatToParts(10000.1);
-    const decimalSeparator = (_a = parts.find(({ type }) => type === 'decimal')) === null || _a === void 0 ? void 0 : _a.value;
-    const thousandsSeparator = (_b = parts.find(({ type }) => type === 'group')) === null || _b === void 0 ? void 0 : _b.value;
+    const decimalPart = parts.find(({ type }) => type === 'decimal');
+    const groupPart = parts.find(({ type }) => type === 'group');
+    const decimalSeparator = decimalPart?.value;
+    const thousandsSeparator = groupPart?.value;
     return { decimalSeparator, thousandsSeparator };
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Object.defineProperty(exports, "__esModule", { value: true });
exports.getLocaleSeparators = void 0;
const getLocaleSeparators = (locale) => {
    const numberFormat = new Intl.NumberFormat(locale);
    const parts = numberFormat.formatToParts(10000.1);
    const decimalPart = parts.find(({ type }) => type === 'decimal');
    const groupPart = parts.find(({ type }) => type === 'group');
    const decimalSeparator = decimalPart?.value;
    const thousandsSeparator = groupPart?.value;
    return { decimalSeparator, thousandsSeparator };
};
exports.getLocaleSeparators = getLocaleSeparators;
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


[error] 5-5: Declare variables separately

Unsafe fix: Break out into multiple declarations

(lint/style/useSingleVarDeclarator)


[error] 8-8: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 9-9: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 5-5: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utils/bufferUtils.js (2)

4-15: 🧹 Nitpick (assertive)

建议优化 reverseBuffer 函数的实现

当前实现虽然正确,但可以通过以下方式改进:

  1. 使用 Math.floor(buffer.length / 2) 优化循环条件
  2. 考虑使用更简洁的实现方式
 const reverseBuffer = (src) => {
     if (src.length < 1)
         return src;
     const buffer = Buffer.alloc(src.length);
     let j = buffer.length - 1;
-    for (let i = 0; i < buffer.length / 2; i++) {
+    for (let i = 0; i < Math.floor(buffer.length / 2); i++) {
         buffer[i] = src[j];
         buffer[j] = src[i];
         j--;
     }
     return buffer;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const reverseBuffer = (src) => {
    if (src.length < 1)
        return src;
    const buffer = Buffer.alloc(src.length);
    let j = buffer.length - 1;
    for (let i = 0; i < Math.floor(buffer.length / 2); i++) {
        buffer[i] = src[j];
        buffer[j] = src[i];
        j--;
    }
    return buffer;
};

17-21: ⚠️ Potential issue

建议增加安全性检查

getChunkSize 函数存在以下问题:

  1. 使用了不安全的 allocUnsafe
  2. 缺少输入验证,应检查 n 是否在有效范围内 (0-255)
 const getChunkSize = (n) => {
+    if (n < 0 || n > 255) {
+        throw new Error('Input must be between 0 and 255');
+    }
-    const buf = Buffer.allocUnsafe(1);
+    const buf = Buffer.alloc(1);
     buf.writeUInt8(n);
     return buf;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const getChunkSize = (n) => {
    if (n < 0 || n > 255) {
        throw new Error('Input must be between 0 and 255');
    }
    const buf = Buffer.alloc(1);
    buf.writeUInt8(n);
    return buf;
};
third-party/utils/getMutex.js (1)

8-19: 🧹 Nitpick (assertive)

建议增加超时机制和内存保护

当前互斥锁实现存在以下潜在问题:

  1. 缺少超时机制,可能导致死锁
  2. 没有清理机制,可能导致内存泄漏
  3. 错误处理不完善

建议添加以下功能:

  1. 添加超时参数
  2. 实现自动清理机制
  3. 完善错误处理

示例实现:

-    return (...args_1) => tslib_1.__awaiter(void 0, [...args_1], void 0, function* (lockId = DEFAULT_ID) {
+    return (...args_1) => tslib_1.__awaiter(void 0, [...args_1], void 0, function* (lockId = DEFAULT_ID, timeout = 5000) {
+        const startTime = Date.now();
         while (locks[lockId]) {
+            if (Date.now() - startTime > timeout) {
+                throw new Error('Mutex timeout');
+            }
             yield locks[lockId];
         }

Committable suggestion skipped: line range outside the PR's diff.

third-party/utxo-lib/bs58check.d.ts (1)

1-11: 🧹 Nitpick (assertive)

建议添加函数文档注释

这些函数缺少 JSDoc 注释来说明:

  • 每个函数的具体用途
  • 参数的有效值范围
  • 可能抛出的异常
  • 返回值的格式说明

建议添加如下格式的文档:

+/**
+ * 使用 Blake256 算法解码地址字符串
+ * @param {string} address - 要解码的地址
+ * @returns {Buffer} 解码后的 buffer
+ * @throws {Error} 当地址格式无效时抛出异常
+ */
 export declare function decodeBlake256(address: string): Buffer;

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/topologicalSort.js (2)

11-12: 🧹 Nitpick (assertive)

改进错误处理信息

当检测到循环依赖时,错误信息过于简单。建议提供更多上下文信息,帮助调试。

-            throw new Error('Cycle detected');
+            throw new Error(`检测到循环依赖关系。处理元素: ${JSON.stringify(elem)}`);

Committable suggestion skipped: line range outside the PR's diff.


7-7: 🧹 Nitpick (assertive)

建议提取 filterRoots 为独立函数

当前 filterRoots 作为内部函数定义,但它的逻辑足够独立,可以提取出来以提高可读性。

+function filterRoots(verts, precedes) {
+    return arrayPartition_1.arrayPartition(
+        verts,
+        succ => !verts.some(pred => precedes(pred, succ))
+    );
+}

 const topologicalSort = (elements, precedes, tie) => {
     const result = [];
-    const filterRoots = (verts) => arrayPartition_1.arrayPartition(
-        verts,
-        succ => !verts.some(pred => precedes(pred, succ))
-    );

Committable suggestion skipped: line range outside the PR's diff.

third-party/utxo-lib/compose/transaction.js (1)

13-14: ⚠️ Potential issue

需要添加输入验证

当前实现缺少必要的输入验证,可能导致运行时错误。建议添加以下检查:

  • request.utxos 是否存在且为数组
  • result.inputs 中的索引是否有效
  • request.sortingStrategy 是否为有效值
 function createTransaction(request, result) {
+    if (!Array.isArray(request.utxos)) {
+        throw new Error('request.utxos 必须是数组');
+    }
+    if (!Array.isArray(result.inputs)) {
+        throw new Error('result.inputs 必须是数组');
+    }
+    if (!strategyMap[request.sortingStrategy]) {
+        throw new Error(`无效的排序策略: ${request.sortingStrategy}`);
+    }
+
     const convertedInputs = result.inputs.map(input => {
+        if (input.i >= request.utxos.length) {
+            throw new Error(`无效的 UTXO 索引: ${input.i}`);
+        }
         return request.utxos[input.i];
     });
     return strategyMap[request.sortingStrategy]({ result, request, convertedInputs });
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function createTransaction(request, result) {
    if (!Array.isArray(request.utxos)) {
        throw new Error('request.utxos 必须是数组');
    }
    if (!Array.isArray(result.inputs)) {
        throw new Error('result.inputs 必须是数组');
    }
    if (!strategyMap[request.sortingStrategy]) {
        throw new Error(`无效的排序策略: ${request.sortingStrategy}`);
    }

    const convertedInputs = result.inputs.map(input => {
        if (input.i >= request.utxos.length) {
            throw new Error(`无效的 UTXO 索引: ${input.i}`);
        }
        return request.utxos[input.i];
    });
    return strategyMap[request.sortingStrategy]({ result, request, convertedInputs });
}
third-party/utxo-lib/compose/sorting/noneSortingStrategy.js (2)

1-1: 🧹 Nitpick (assertive)

移除多余的 'use strict' 声明

由于使用了 ES 模块系统,'use strict' 声明是多余的。模块代码默认就在严格模式下运行。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


5-17: 🧹 Nitpick (assertive)

建议优化函数实现方式

当前实现虽然正确,但可以通过以下方式改进:

  1. 使用对象解构来简化参数
  2. 使用 early return 模式提高代码可读性
-const noneSortingStrategy = ({ result, request, convertedInputs }) => {
+const noneSortingStrategy = ({ result, request, convertedInputs }) => {
+    if (!result?.outputs?.length) {
+        return { inputs: convertedInputs, outputs: [], outputsPermutation: [] };
+    }
+
     const convertedOutputs = result.outputs.map((output, index) => {
-        if (request.outputs[index]) {
-            return (0, convertOutput_1.convertOutput)(output, request.outputs[index]);
-        }
-        return (0, convertOutput_1.convertOutput)(output, Object.assign({ type: 'change' }, request.changeAddress));
+        const outputConfig = request.outputs[index] || 
+            { ...request.changeAddress, type: 'change' };
+        return convertOutput_1.convertOutput(output, outputConfig);
     });

Committable suggestion skipped: line range outside the PR's diff.

third-party/utxo-lib/derivation.d.ts (2)

23-23: 🧹 Nitpick (assertive)

移除无用的空导出语句

由于文件中已有其他导出,这个空导出语句是多余的。

-export {};
🧰 Tools
🪛 Biome (1.9.4)

[error] 22-23: This empty export is useless because there's another export or import.

This import makes useless the empty export.

Safe fix: Remove this useless empty export.

(lint/complexity/noUselessEmptyExport)


2-11: 🧹 Nitpick (assertive)

建议为版本字节添加注释说明

BIP32_PAYMENT_TYPES 中包含了重复的支付类型,建议添加注释说明不同版本字节的用途和区别。

 declare const BIP32_PAYMENT_TYPES: {
+    // mainnet version bytes
     readonly 76067358: "p2pkh";
     readonly 77429938: "p2sh";
     readonly 78792518: "p2wpkh";
+    // testnet version bytes
     readonly 70617039: "p2pkh";
     readonly 71979618: "p2sh";
     readonly 73342198: "p2wpkh";
+    // other network version bytes
     readonly 27108450: "p2pkh";
     readonly 28471030: "p2sh";
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

declare const BIP32_PAYMENT_TYPES: {
    // mainnet version bytes
    readonly 76067358: "p2pkh";
    readonly 77429938: "p2sh";
    readonly 78792518: "p2wpkh";
    // testnet version bytes
    readonly 70617039: "p2pkh";
    readonly 71979618: "p2sh";
    readonly 73342198: "p2wpkh";
    // other network version bytes
    readonly 27108450: "p2pkh";
    readonly 28471030: "p2sh";
};
third-party/utils/arrayToDictionary.js (3)

1-1: 🧹 Nitpick (assertive)

修复代码风格问题

  1. 移除多余的 'use strict' 声明
  2. 使用 let 替代 var
-"use strict";
// ...
-        var _a;
+        let _a;

Also applies to: 12-12

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


4-9: 🧹 Nitpick (assertive)

简化类型验证函数

validateKey 函数可以更简洁地实现。

-const validateKey = (key) => {
-    if (['string', 'number'].includes(typeof key)) {
-        return true;
-    }
-    return false;
-};
+const validateKey = (key) => ['string', 'number'].includes(typeof key);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const validateKey = (key) => ['string', 'number'].includes(typeof key);

10-25: 🛠️ Refactor suggestion

建议改进函数实现

当前实现存在以下问题:

  1. 错误处理不够明确
  2. 代码重复度较高
  3. 类型安全性有待提高

建议重构实现:

-const arrayToDictionary = (array, getKey, multiple) => multiple
-    ? array.reduce((prev, cur) => {
-        var _a;
-        const key = getKey(cur);
-        if (validateKey(key)) {
-            return Object.assign(Object.assign({}, prev), { [key]: [...((_a = prev[key]) !== null && _a !== void 0 ? _a : []), cur] });
-        }
-        return prev;
-    }, {})
-    : array.reduce((prev, cur) => {
-        const key = getKey(cur);
-        if (validateKey(key)) {
-            return Object.assign(Object.assign({}, prev), { [key]: cur });
-        }
-        return prev;
-    }, {});
+const arrayToDictionary = (array, getKey, multiple) => {
+    return array.reduce((acc, item) => {
+        const key = getKey(item);
+        
+        if (!validateKey(key)) {
+            console.warn(`Invalid key type: ${typeof key}`);
+            return acc;
+        }
+        
+        if (multiple) {
+            const existing = acc[key] || [];
+            return { ...acc, [key]: [...existing, item] };
+        }
+        
+        return { ...acc, [key]: item };
+    }, {});
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const arrayToDictionary = (array, getKey, multiple) => {
    return array.reduce((acc, item) => {
        const key = getKey(item);
        
        if (!validateKey(key)) {
            console.warn(`Invalid key type: ${typeof key}`);
            return acc;
        }
        
        if (multiple) {
            const existing = acc[key] || [];
            return { ...acc, [key]: [...existing, item] };
        }
        
        return { ...acc, [key]: item };
    }, {});
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 15-15: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 12-12: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

third-party/utils/logs.d.ts (2)

24-24: ⚠️ Potential issue

setWriter 方法参数类型不明确

参数类型使用 any 不够严谨,应该使用已定义的 LogWriter 类型。

-    setWriter(logWriter: any): void;
+    setWriter(logWriter: LogWriter): void;

Committable suggestion skipped: line range outside the PR's diff.


4-4: 🧹 Nitpick (assertive)

建议使用更具体的类型替代 any[]

消息类型中使用 any[] 可能会导致类型安全性降低。建议定义更具体的类型来约束消息内容。

-    message: any[];
+    message: (string | number | boolean | null | undefined)[];
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    message: (string | number | boolean | null | undefined)[];
third-party/utxo-lib/coinselect/index.js (2)

1-1: 🧹 Nitpick (assertive)

代码规范优化建议

  1. 移除多余的 "use strict" 声明,因为 ES 模块默认启用严格模式
  2. 使用 const 声明解构变量,提高代码质量
-"use strict";
...
-    var { inputs, outputs, feeRate } = _a, options = tslib_1.__rest(_a, ["inputs", "outputs", "feeRate"]);
+    const { inputs, outputs, feeRate } = _a, options = tslib_1.__rest(_a, ["inputs", "outputs", "feeRate"]);

Also applies to: 11-11

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


15-17: 🛠️ Refactor suggestion

建议增加输入参数验证

在执行排序和算法选择之前,应该验证输入参数的有效性。

+    if (!Array.isArray(inputs) || !Array.isArray(outputs) || typeof feeRate !== 'number') {
+        throw new Error('Invalid parameters: inputs and outputs must be arrays, feeRate must be a number');
+    }
     const sortedInputs = options.sortingStrategy === 'none' ? inputs : inputs.sort((0, coinselectUtils_1.sortByScore)(feeRate));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    if (!Array.isArray(inputs) || !Array.isArray(outputs) || typeof feeRate !== 'number') {
        throw new Error('Invalid parameters: inputs and outputs must be arrays, feeRate must be a number');
    }
    const sortedInputs = options.sortingStrategy === 'none' ? inputs : inputs.sort((0, coinselectUtils_1.sortByScore)(feeRate));
    const algorithm = (0, tryconfirmed_1.tryConfirmed)((0, coinselectUtils_1.anyOf)([branchAndBound_1.branchAndBound, accumulative_1.accumulative]), options);
    return algorithm(sortedInputs, outputs, feeRate, options);
third-party/utils/throttler.js (3)

34-34: 🧹 Nitpick (assertive)

优化 dispose 方法的实现

使用 bind 方法替代当前的实现方式,可以提高代码可读性。

-        Object.keys(this.intervals).forEach(this.cancel, this);
+        Object.keys(this.intervals).forEach(this.cancel.bind(this));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        Object.keys(this.intervals).forEach(this.cancel.bind(this));

6-9: 🧹 Nitpick (assertive)

建议添加私有字段标记

类的内部属性应该使用私有字段标记,以防止外部直接访问。

-        this.delay = delay;
-        this.intervals = {};
-        this.callbacks = {};
+        this.#delay = delay;
+        this.#intervals = {};
+        this.#callbacks = {};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

        this.#delay = delay;
        this.#intervals = {};
        this.#callbacks = {};
    }

15-17: ⚠️ Potential issue

建议添加错误处理机制

回调执行时缺少错误处理,可能导致定时器无法正常清理。

-            callback();
+            try {
+                callback();
+            } catch (error) {
+                this.cancel(id);
+                throw error;
+            }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            try {
                callback();
            } catch (error) {
                this.cancel(id);
                throw error;
            }
            this.intervals[id] = setInterval(() => this.tick(id), this.delay);
        }
third-party/utils/extractUrlsFromText.js (2)

4-4: 🧹 Nitpick (assertive)

建议简化正则表达式并添加注释

当前的正则表达式过于复杂,难以维护。建议将其拆分成多个小的正则表达式,并添加注释说明每个部分的作用。

-const URL_REGEX = /\b(?:https?:\/\/|www\.)[a-zA-Z0-9-._~:/?#[\]@!$&'()*+,;=%]+\b|(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(?=\b|\s|$|\])/gi;
+// 匹配 http/https/www 开头的 URL
+const PROTOCOL_URL = /\b(?:https?:\/\/|www\.)[a-zA-Z0-9-._~:/?#[\]@!$&'()*+,;=%]+\b/gi;
+// 匹配域名
+const DOMAIN_URL = /(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(?=\b|\s|$|\])/gi;
+const URL_REGEX = new RegExp(`${PROTOCOL_URL.source}|${DOMAIN_URL.source}`, 'gi');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// 匹配 http/https/www 开头的 URL
const PROTOCOL_URL = /\b(?:https?:\/\/|www\.)[a-zA-Z0-9-._~:/?#[\]@!$&'()*+,;=%]+\b/gi;
// 匹配域名
const DOMAIN_URL = /(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}(?=\b|\s|$|\])/gi;
const URL_REGEX = new RegExp(`${PROTOCOL_URL.source}|${DOMAIN_URL.source}`, 'gi');

5-26: 🧹 Nitpick (assertive)

建议优化性能和可读性

函数实现逻辑清晰,但可以通过以下方式优化:

  1. 使用 reduce 替代 forEach 来减少中间变量
  2. 添加输入验证
 const extractUrlsFromText = (text) => {
+    if (typeof text !== 'string') {
+        throw new TypeError('输入必须是字符串类型');
+    }
-    const urls = [];
-    const textParts = [];
-    let lastIndex = 0;
     const matches = [...text.matchAll(URL_REGEX)];
-    matches.forEach(match => {
+    const { urls, textParts } = matches.reduce((acc, match) => {
         const url = match[0];
         const index = match.index !== undefined ? match.index : -1;
-        if (lastIndex < index) {
-            textParts.push(text.slice(lastIndex, index));
+        if (acc.lastIndex < index) {
+            acc.textParts.push(text.slice(acc.lastIndex, index));
         }
-        urls.push(url);
-        lastIndex = index + url.length;
-    });
-    if (lastIndex < text.length) {
-        textParts.push(text.slice(lastIndex));
-    }
-    if (textParts.length === 0 && urls.length > 0) {
-        textParts.push('');
-    }
+        acc.urls.push(url);
+        acc.lastIndex = index + url.length;
+        return acc;
+    }, { urls: [], textParts: [], lastIndex: 0 });
+
+    if (lastIndex < text.length) textParts.push(text.slice(lastIndex));
+    if (textParts.length === 0 && urls.length > 0) textParts.push('');
     return { textParts, urls };
 };

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/cloneObject.js (1)

4-30: 🛠️ Refactor suggestion

建议增强类型处理和性能优化

当前实现缺少一些特殊类型的处理,同时可以优化性能:

  1. 需要处理 Date、RegExp、Map、Set 等特殊对象
  2. 大型对象的克隆可以考虑使用结构化克隆算法
 const cloneObject = (obj, seen = new WeakMap()) => {
     if (obj === null || typeof obj !== 'object') {
         return obj;
     }
     if (seen.has(obj)) {
         return seen.get(obj);
     }
+    // 处理特殊对象类型
+    if (obj instanceof Date) {
+        return new Date(obj);
+    }
+    if (obj instanceof RegExp) {
+        return new RegExp(obj);
+    }
+    if (obj instanceof Map) {
+        return new Map([...obj].map(([k, v]) => [k, cloneObject(v, seen)]));
+    }
+    if (obj instanceof Set) {
+        return new Set([...obj].map(v => cloneObject(v, seen)));
+    }
     if (obj instanceof ArrayBuffer) {
         return obj.slice(0);
     }
     if (ArrayBuffer.isView(obj)) {
         const TypedArrayConstructor = obj.constructor;
         return new TypedArrayConstructor(obj);
     }
+    // 对于大型对象,考虑使用结构化克隆
+    if (Object.keys(obj).length > 1000) {
+        try {
+            return structuredClone(obj);
+        } catch {
+            // 如果结构化克隆失败,回退到普通克隆
+        }
+    }
     const clone = Array.isArray(obj) ? [] : {};
     seen.set(obj, clone);
     for (const key in obj) {

Committable suggestion skipped: line range outside the PR's diff.

third-party/utxo-lib/index.d.ts (1)

1-17: 🧹 Nitpick (assertive)

建议优化类型导出的组织结构

当前的类型定义文件结构清晰,但可以通过以下方式改进:

  1. 按功能分组导出
  2. 添加类型文档注释
+// 核心模块
 import * as address from './address';
 import * as bip32 from './bip32';
 import * as bufferutils from './bufferutils';
 import * as crypto from './crypto';
+
+// 交易相关
 import * as payments from './payments';
 import * as script from './script';
 import * as networks from './networks';
 import { composeTx } from './compose';
+
+// 地址派生
 import { deriveAddresses, getXpubOrDescriptorInfo } from './derivation';
 import { discovery } from './discovery';
+
+// 核心类型
 export { Transaction } from './transaction';
+
+// 按功能分组导出
+// 核心模块
 export { address, bip32, bufferutils, crypto };
+// 交易相关
 export { payments, script, networks, composeTx };
+// 地址派生
 export { deriveAddresses, getXpubOrDescriptorInfo, discovery };
+
+// 类型定义
+/** 支付类型定义 */
 export type { PaymentType } from './derivation';
+/** 交易组合相关类型 */
 export type {
     ComposeInput, ComposeOutput, ComposeChangeAddress,
     ComposeRequest, ComposeResult, ComposeResultNonFinal,
     ComposeResultError, ComposeResultFinal, ComposedTransaction,
     CoinSelectPaymentType,
 } from './types';
+/** 网络相关类型 */
 export type { Network } from './networks';
+/** BIP32 接口类型 */
 export type { BIP32Interface } from './bip32';
+/** 交易输入输出排序策略 */
 export type { TransactionInputOutputSortingStrategy } from './types/compose';
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

// 核心模块
import * as address from './address';
import * as bip32 from './bip32';
import * as bufferutils from './bufferutils';
import * as crypto from './crypto';

// 交易相关
import * as payments from './payments';
import * as script from './script';
import * as networks from './networks';
import { composeTx } from './compose';

// 地址派生
import { deriveAddresses, getXpubOrDescriptorInfo } from './derivation';
import { discovery } from './discovery';

// 核心类型
export { Transaction } from './transaction';

// 按功能分组导出
// 核心模块
export { address, bip32, bufferutils, crypto };
// 交易相关
export { payments, script, networks, composeTx };
// 地址派生
export { deriveAddresses, getXpubOrDescriptorInfo, discovery };

// 类型定义
/** 支付类型定义 */
export type { PaymentType } from './derivation';
/** 交易组合相关类型 */
export type {
    ComposeInput, ComposeOutput, ComposeChangeAddress,
    ComposeRequest, ComposeResult, ComposeResultNonFinal,
    ComposeResultError, ComposeResultFinal, ComposedTransaction,
    CoinSelectPaymentType,
} from './types';
/** 网络相关类型 */
export type { Network } from './networks';
/** BIP32 接口类型 */
export type { BIP32Interface } from './bip32';
/** 交易输入输出排序策略 */
export type { TransactionInputOutputSortingStrategy } from './types/compose';
third-party/utxo-lib/bip32.d.ts (1)

2-23: 🧹 Nitpick (assertive)

接口定义完整且符合规范!

接口定义完全符合 BIP32 规范,包含了所有必要的 HD 钱包操作方法。建议为每个方法添加 JSDoc 注释,以提供更详细的使用说明。

third-party/utxo-lib/discovery.js (2)

7-15: 🛠️ Refactor suggestion

建议优化边界条件处理!

countUnusedFromEnd 函数在处理空数组时可能会出现问题。建议添加边界条件检查:

 const countUnusedFromEnd = (array, isUnused, lookout) => {
+    if (!array || array.length === 0) return 0;
     const boundary = array.length > lookout ? array.length - lookout : 0;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const countUnusedFromEnd = (array, isUnused, lookout) => {
    if (!array || array.length === 0) return 0;
    const boundary = array.length > lookout ? array.length - lookout : 0;
    for (let i = array.length; i > boundary; --i) {
        if (!isUnused(array[i - 1])) {
            return array.length - i;
        }
    }
    return array.length;
};

17-28: ⚠️ Potential issue

需要增加错误处理机制!

发现以下问题:

  1. 递归实现可能导致栈溢出,建议改用迭代方式
  2. 缺少网络错误处理
  3. 没有设置最大重试次数

建议添加以下改进:

 const discovery = (discover, xpub, type, network, lookout = DISCOVERY_LOOKOUT) => {
+    const MAX_RETRIES = 3;
+    const MAX_ITERATIONS = 1000;
+    let iterations = 0;
+
     const discoverRecursive = (from, prev) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
+        if (iterations++ > MAX_ITERATIONS) {
+            throw new Error('Maximum discovery iterations reached');
+        }
         const unused = (0, exports.countUnusedFromEnd)(prev, a => a.empty, lookout);
         if (unused >= lookout)
             return prev;
         const moreCount = lookout - unused;
         const addresses = (0, derivation_1.deriveAddresses)(xpub, type, from, moreCount, network);
-        const more = yield Promise.all(addresses.map(discover));
+        const more = yield Promise.all(addresses.map(addr => 
+            retry(() => discover(addr), MAX_RETRIES)
+        ));
         return discoverRecursive(from + moreCount, prev.concat(more));
     });
     return discoverRecursive(0, []);
 };

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/getRandomInt.js (1)

24-30: 🛠️ Refactor suggestion

优化随机数生成循环逻辑

当前实现在极端情况下可能会进入长时间循环。建议添加最大重试次数限制。

 const maxRange = MAX_RANGE_32_BITS - (MAX_RANGE_32_BITS % range);
 let randomValue;
+ let attempts = 0;
+ const MAX_ATTEMPTS = 100;
 do {
     getRandomValues(array);
     randomValue = array[0];
+    attempts++;
+    if (attempts >= MAX_ATTEMPTS) {
+        throw new Error('Failed to generate random number within the specified range');
+    }
 } while (randomValue >= maxRange);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    const maxRange = MAX_RANGE_32_BITS - (MAX_RANGE_32_BITS % range);
    let randomValue;
    let attempts = 0;
    const MAX_ATTEMPTS = 100;
    do {
        getRandomValues(array);
        randomValue = array[0];
        attempts++;
        if (attempts >= MAX_ATTEMPTS) {
            throw new Error('Failed to generate random number within the specified range');
        }
    } while (randomValue >= maxRange);
    return min + (randomValue % range);
third-party/utxo-lib/crypto.js (2)

15-22: 🧹 Nitpick (assertive)

改进 ripemd160 错误处理机制

当前的错误处理过于简单,建议添加具体的错误信息和日志记录。

 function ripemd160(buffer) {
+    if (!Buffer.isBuffer(buffer)) {
+        throw new TypeError('Expected Buffer');
+    }
     try {
         return (0, crypto_1.createHash)('rmd160').update(buffer).digest();
     }
-    catch (_a) {
+    catch (error) {
+        console.warn('rmd160 hash failed, falling back to ripemd160:', error.message);
         return (0, crypto_1.createHash)('ripemd160').update(buffer).digest();
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function ripemd160(buffer) {
    if (!Buffer.isBuffer(buffer)) {
        throw new TypeError('Expected Buffer');
    }
    try {
        return (0, crypto_1.createHash)('rmd160').update(buffer).digest();
    }
    catch (error) {
        console.warn('rmd160 hash failed, falling back to ripemd160:', error.message);
        return (0, crypto_1.createHash)('ripemd160').update(buffer).digest();
    }
}

41-43: ⚠️ Potential issue

增强 HMAC 实现的安全性

hmacSHA512 函数缺少对输入参数的验证,可能导致运行时错误。

 function hmacSHA512(key, data) {
+    if (!Buffer.isBuffer(key) || !Buffer.isBuffer(data)) {
+        throw new TypeError('Key and data must be Buffers');
+    }
+    if (key.length === 0) {
+        throw new Error('Key cannot be empty');
+    }
     return (0, create_hmac_1.default)('sha512', key).update(data).digest();
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

function hmacSHA512(key, data) {
    if (!Buffer.isBuffer(key) || !Buffer.isBuffer(data)) {
        throw new TypeError('Key and data must be Buffers');
    }
    if (key.length === 0) {
        throw new Error('Key cannot be empty');
    }
    return (0, create_hmac_1.default)('sha512', key).update(data).digest();
}
third-party/utxo-lib/compose/sorting/bip69SortingStrategy.js (2)

14-30: ⚠️ Potential issue

完善 BIP69 排序策略的错误处理

当前实现缺少对输入参数的验证,建议添加必要的检查。

 const bip69SortingStrategy = ({ result, request, convertedInputs }) => {
+    if (!result?.outputs || !Array.isArray(result.outputs)) {
+        throw new Error('Invalid result: outputs must be an array');
+    }
+    if (!request?.outputs || !Array.isArray(request.outputs)) {
+        throw new Error('Invalid request: outputs must be an array');
+    }
+    if (!convertedInputs || !Array.isArray(convertedInputs)) {
+        throw new Error('Invalid convertedInputs: must be an array');
+    }
     const defaultPermutation = [];
     // ... rest of the implementation
 };

Committable suggestion skipped: line range outside the PR's diff.


5-7: 🧹 Nitpick (assertive)

优化输入排序比较器的性能

当前实现在每次比较时都创建新的 Buffer,这可能影响性能。建议缓存 Buffer 或使用更高效的比较方法。

 function inputComparator(a, b) {
-    return Buffer.from(a.txid, 'hex').compare(Buffer.from(b.txid, 'hex')) || a.vout - b.vout;
+    const comparison = a.txid.localeCompare(b.txid);
+    return comparison !== 0 ? comparison : a.vout - b.vout;
 }

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/createLazy.js (2)

10-19: 🧹 Nitpick (assertive)

建议增强 dispose 方法的错误处理

当前的 dispose 方法在执行时可能会静默失败。建议添加错误处理并返回处理结果。

 const dispose = () => {
+    try {
       if (valuePromise) {
           valuePromise.reject(new Error('Disposed during initialization'));
           valuePromise = undefined;
       }
       if (value !== undefined) {
           disposeLazy === null || disposeLazy === void 0 ? void 0 : disposeLazy(value);
           value = undefined;
       }
+        return true;
+    } catch (error) {
+        console.error('Dispose failed:', error);
+        return false;
+    }
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    const dispose = () => {
        try {
            if (valuePromise) {
                valuePromise.reject(new Error('Disposed during initialization'));
                valuePromise = undefined;
            }
            if (value !== undefined) {
                disposeLazy === null || disposeLazy === void 0 ? void 0 : disposeLazy(value);
                value = undefined;
            }
            return true;
        } catch (error) {
            console.error('Dispose failed:', error);
            return false;
        }
    };

1-1: 🧹 Nitpick (assertive)

移除多余的 "use strict" 声明

在 ES 模块中,严格模式是默认开启的,不需要显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/witness.js (3)

22-29: 🧹 Nitpick (assertive)

优化测试用例变量声明

使用 const 声明测试结果变量,并考虑添加类型注释。

-      var actual = coinSelect({
+      const actual = coinSelect({
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const actual = coinSelect({
        utxos: f.inputs,
        outputs: f.outputs,
        feeRate: f.feeRate,
        network: f.network,
        changeAddress: f.changeAddress,
        txType: f.txType
      })
🧰 Tools
🪛 Biome (1.9.4)

[error] 22-29: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


1-3: 🛠️ Refactor suggestion

使用 const 替代 var 声明

为了防止变量被意外修改,建议使用 const 声明。

-var coinSelect = require('../witness')
-var fixtures = require('./fixtures/witness')
-var tape = require('tape')
+const coinSelect = require('../witness')
+const fixtures = require('./fixtures/witness')
+const tape = require('tape')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const coinSelect = require('../witness')
const fixtures = require('./fixtures/witness')
const tape = require('tape')
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


[error] 1-2: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


[error] 2-3: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


31-37: ⚠️ Potential issue

建议添加输入验证

在重排输出顺序前,应该验证 permutation 数组的有效性。

 const reorderOutputs = (outputs, permutation) => {
+    if (!Array.isArray(permutation) || 
+        !permutation.every(i => typeof i === 'number' && 
+        i >= 0 && i < outputs.length)) {
+        throw new Error('Invalid permutation array');
+    }
     return permutation.map(index => outputs[index]);
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      // Restore the order of outputs according to outputsPermutation
      const reorderOutputs = (outputs, permutation) => {
        if (!Array.isArray(permutation) || 
            !permutation.every(i => typeof i === 'number' && 
            i >= 0 && i < outputs.length)) {
            throw new Error('Invalid permutation array');
        }
        return permutation.map(index => outputs[index]);
      };

      actual.outputs = reorderOutputs(actual.outputs, actual.outputsPermutation);
      f.expected.outputs = reorderOutputs(f.expected.outputs, f.expected.outputsPermutation);
third-party/utils/versionUtils.js (3)

26-26: 🛠️ Refactor suggestion

增强版本规范化函数

normalizeVersion 函数应该处理更多边缘情况,比如无效输入和非标准格式。

-const normalizeVersion = (version) => version.replace(/\b0+(\d)/g, '$1');
+const normalizeVersion = (version) => {
+    if (typeof version !== 'string') {
+        throw new Error('Version must be a string');
+    }
+    return version.trim().replace(/\b0+(\d)/g, '$1');
+};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const normalizeVersion = (version) => {
    if (typeof version !== 'string') {
        throw new Error('Version must be a string');
    }
    return version.trim().replace(/\b0+(\d)/g, '$1');
};

1-1: 🧹 Nitpick (assertive)

移除多余的 "use strict" 声明

ES 模块默认使用严格模式,不需要显式声明。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)


9-13: ⚠️ Potential issue

优化版本解析逻辑

当前的版本解析可能会对无效输入返回不完整结果。建议增加更严格的验证。

 const tryParse = (version) => {
-    var _a;
+    const match = version.match(/^(\d+)\.(\d+)\.(\d+)([+-].*)?$/);
+    if (!match) return null;
+    const [, major, minor, patch] = match;
+    const numbers = [major, minor, patch].map(Number);
+    return numbers.every(n => Number.isInteger(n) && n >= 0) ? numbers : null;
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

const tryParse = (version) => {
    const match = version.match(/^(\d+)\.(\d+)\.(\d+)([+-].*)?$/);
    if (!match) return null;
    const [, major, minor, patch] = match;
    const numbers = [major, minor, patch].map(Number);
    return numbers.every(n => Number.isInteger(n) && n >= 0) ? numbers : null;
};
🧰 Tools
🪛 Biome (1.9.4)

[error] 11-12: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 10-10: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)

package.json (1)

53-70: 🧹 Nitpick (assertive)

依赖项过多,建议优化

当前添加了大量新依赖项,建议:

  1. 检查是否所有依赖都被实际使用
  2. 考虑将一些依赖合并或移除
  3. 评估是否可以使用更轻量级的替代方案
third-party/utils/logsManager.js (3)

43-50: 🧹 Nitpick (assertive)

优化日志获取性能

getLog 方法在处理大量日志时可能存在性能问题,建议:

  1. 考虑使用 Map 存储日志
  2. 实现分页机制
  3. 添加日志清理策略

20-32: 🛠️ Refactor suggestion

建议改进错误处理机制

setLogWriter 方法缺少错误处理机制,建议:

  1. 添加 try-catch 块处理可能的异常
  2. 在写入失败时提供回退方案
  3. 添加日志写入状态的验证
 setLogWriter(logWriterFactory) {
+    try {
         Object.keys(this.logs).forEach(key => {
             this.writer = logWriterFactory();
             if (this.writer) {
                 this.logs[key].setWriter(this.writer);
                 const { messages } = this.logs[key];
                 messages.forEach(message => {
-                    var _a;
+                    const writer = this.writer;
-                    (_a = this.writer) === null || _a === void 0 ? void 0 : _a.add(message);
+                    writer?.add(message);
                 });
             }
         });
+    } catch (error) {
+        console.error('设置日志写入器失败:', error);
+    }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    setLogWriter(logWriterFactory) {
        try {
            Object.keys(this.logs).forEach(key => {
                this.writer = logWriterFactory();
                if (this.writer) {
                    this.logs[key].setWriter(this.writer);
                    const { messages } = this.logs[key];
                    messages.forEach(message => {
                        const writer = this.writer;
                        writer?.add(message);
                    });
                }
            });
        } catch (error) {
            console.error('设置日志写入器失败:', error);
        }
    }
🧰 Tools
🪛 Biome (1.9.4)

[error] 28-28: The assignment should not be in an expression.

The use of assignments in expressions is confusing.
Expressions are often considered as side-effect free.

(lint/suspicious/noAssignInExpressions)


[error] 27-27: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'let' instead.

(lint/style/noVar)


1-1: 🧹 Nitpick (assertive)

移除多余的 strict mode 声明

由于使用了 ES 模块系统,不需要显式声明 'use strict'。

-"use strict";
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

third-party/utils/index.d.ts (1)

1-51: 🧹 Nitpick (assertive)

建议优化工具函数的组织结构

当前导出了大量工具函数,建议:

  1. 按功能对工具函数进行分组
  2. 添加类别注释
  3. 为每个工具函数添加 JSDoc 文档

示例组织结构:

// 字符串处理
export * from './addDashesToSpaces';
export * from './capitalizeFirstLetter';

// 数组操作
export * from './arrayDistinct';
export * from './arrayPartition';

// 随机数生成
export * from './getRandomInt';
export * from './getWeakRandomId';
third-party/utils/logs.js (3)

28-34: 🧹 Nitpick (assertive)

建议:改进错误处理机制

当前的错误处理只是打印错误信息。建议:

  1. 添加重试机制
  2. 提供错误回调选项

7-7: 🧹 Nitpick (assertive)

建议:考虑使配置更灵活

建议将 MAX_ENTRIES 作为构造函数的可选参数,这样可以根据不同场景调整日志条目的限制。

- this.MAX_ENTRIES = 100;
+ constructor(prefix, enabled, logWriter, maxEntries = 100) {
+   this.MAX_ENTRIES = maxEntries;

Committable suggestion skipped: line range outside the PR's diff.


42-76: 🛠️ Refactor suggestion

建议:统一日志方法实现

各个日志级别的方法(log, error, info, warn, debug)有重复代码。建议提取共同逻辑到一个私有方法中。

+ private _log(level, args) {
+   this.addMessage({ level, prefix: this.prefix }, ...args);
+   if (this.enabled) {
+     const method = level === 'debug' ? 'log' : level;
+     if (this.css) {
+       console[method](`%c${this.prefix}`, this.css, ...args);
+     } else {
+       console[method](this.prefix, ...args);
+     }
+   }
+ }

Committable suggestion skipped: line range outside the PR's diff.

third-party/utils/index.js (1)

1-8: 🧹 Nitpick (assertive)

建议:优化导出结构

建议将相关的工具函数按功能分组导出,比如:

  • 数组操作
  • 字符串处理
  • 随机数生成
    这样可以提高代码的可维护性。
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Redundant use strict directive.

The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.

(lint/suspicious/noRedundantUseStrict)

test/fixtures/witness.js (3)

19-20: ⚠️ Potential issue

建议:统一交易ID格式

测试用例中的交易ID长度不一致:

  • 第一个用例使用截断的ID:"f4668"
  • 第二个用例使用完整的ID:"f46689066ac0493cc55920c3918163ccda6c64998d6c078c6254e1c00c36a332"

建议统一使用完整的交易ID格式。

Also applies to: 209-210


151-158: 🧹 Nitpick (assertive)

建议:增加更多边界测试用例

建议添加以下场景的测试:

  1. 最大输出数量
  2. 零值输出
  3. 无效的 OP_RETURN 数据

Also applies to: 249-260


204-232: 🛠️ Refactor suggestion

建议:完善错误测试用例

当前的错误测试用例仅覆盖了确认数缺失的情况。建议添加更多错误场景:

  1. 余额不足
  2. 无效地址
  3. 手续费过高/过低

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range comments (1)
package.json (1)

Line range hint 12-12: 更新包的链接信息

homepagebugs.urlrepository.url 仍指向旧的 bitcoinjs/coinselect 仓库。请更新为新的仓库地址以反映当前包名。

-  "homepage": "https://github.com/bitcoinjs/coinselect",
+  "homepage": "https://github.com/OneKeyHQ/coinselect",
   "bugs": {
-    "url": "https://github.com/bitcoinjs/coinselect/issues"
+    "url": "https://github.com/OneKeyHQ/coinselect/issues"
   },
   "repository": {
     "type": "git",
-    "url": "https://github.com/bitcoinjs/coinselect.git"
+    "url": "https://github.com/OneKeyHQ/coinselect.git"
   },

Also applies to: 14-14, 24-24

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between f2f3ad6 and bc25b21.

📒 Files selected for processing (3)
  • package.json (3 hunks)
  • test/fixtures/witness.js (1 hunks)
  • test/witness.js (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
test/witness.js

[error] 1-1: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


[error] 1-2: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


[error] 2-3: Use let or const instead of var.

A variable declared with var is accessible in the whole module. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)


[error] 22-29: Use let or const instead of var.

A variable declared with var is accessible in the whole body of the function. Thus, the variable can be accessed before its initialization and outside the block where it is declared.
See MDN web docs for more details.
Unsafe fix: Use 'const' instead.

(lint/style/noVar)

test/fixtures/witness.js Show resolved Hide resolved
test/fixtures/witness.js Show resolved Hide resolved
test/witness.js Show resolved Hide resolved
test/witness.js Show resolved Hide resolved
@originalix originalix enabled auto-merge (squash) December 5, 2024 03:17
weatherstar
weatherstar previously approved these changes Dec 5, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 13854cb and debfd6f.

📒 Files selected for processing (2)
  • .github/workflows/main_ci.yml (3 hunks)
  • package.json (3 hunks)
🔇 Additional comments (7)
.github/workflows/main_ci.yml (3)

17-17: Node.js 版本更新是必要的改进

将 Node.js 版本从 14 更新到 20 是很好的改进,因为:

  • Node.js 14 已于 2023 年 4 月停止支持
  • Node.js 20 是当前的长期支持版本

33-33: 覆盖率测试任务版本同步更新

coverage 任务使用相同的 Node.js 版本配置保持了一致性。


49-49: 代码检查任务版本同步更新

lint 任务使用相同的 Node.js 版本配置保持了一致性。

建议验证项目依赖是否都支持 Node.js 20。

✅ Verification successful

Node.js 20 兼容性验证通过

根据检查结果:

  • 项目没有使用实验性的 Node.js 特性
  • 代码库中使用的 JavaScript 语法特性都在 Node.js 20 中得到良好支持
  • 依赖包都是稳定版本,没有发现与 Node.js 20 不兼容的情况
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查 package.json 中的 engines 字段和依赖的版本兼容性

# 查找所有 package.json 文件
fd package.json --type f --exec cat {} \; | jq -r '.engines?.node, .dependencies, .devDependencies'

Length of output: 674


Script:

#!/bin/bash
# 检查项目中使用的 Node.js 特性和语法
# 搜索可能不兼容 Node.js 20 的语法或 API

# 1. 检查是否使用了实验性或新特性
ast-grep --pattern 'import.meta'

# 2. 检查是否使用了较新的 ES 特性
rg -l "(?:class\s+fields|private\s+fields|#\w+|\.hasOwn|\.replaceAll|\.at\()" 

# 3. 检查测试配置和脚本
fd "test|jest|mocha" --type f --exec cat {} \;

Length of output: 1604

package.json (4)

76-80: 代码规范配置合理

忽略 third-party 目录的配置是合适的,可以避免对第三方代码进行不必要的格式化。


2-2: 包名称更新提醒

包名从 coinselect 更改为 @onekeyfe/coinselect,这是一个破坏性变更。

✅ Verification successful

包名变更需要注意依赖关系

这个包名变更主要影响了内部引用,所有引用都在 third-party 目录下,这是项目内部的代码。由于:

  • 原始包名 coinselect 仅在 package.json 的包名定义和关键词中使用
  • 其他引用都在项目内部的 third-party 目录下
  • 没有发现外部依赖使用原始包名

这个变更是安全的,不会影响外部依赖。

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查是否有其他包依赖原始包名
rg -l "\"coinselect\"" -g "package.json"

Length of output: 51


Script:

#!/bin/bash
# 检查package.json中coinselect的具体引用上下文
rg "coinselect" -A 5 -B 5 package.json

# 检查是否有其他包或配置文件引用了coinselect
rg -l "coinselect" -g "!package.json"

Length of output: 1720


31-33: 新增的 witness 相关文件需要类型定义验证

确保 witness.d.ts 类型定义文件与实现完全匹配。

✅ Verification successful

类型定义文件已完整验证

witness.d.ts 类型定义文件与 witness.js 的实现完全匹配:

  • 导出函数 coinSelect 的参数类型 ICoinSelectParams 包含了所有实现中使用的参数
  • 返回值类型 ICoinSelectResult 正确定义了成功情况下的返回结构
  • 类型定义涵盖了所有相关的接口和类型
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 检查类型定义文件是否存在
fd "witness.d.ts$"

# 检查类型定义是否完整
ast-grep --pattern 'export $$$' witness.d.ts

Length of output: 80


Script:

#!/bin/bash
# 检查witness.js的导出内容
ast-grep --pattern 'export $$$' witness.js

# 检查witness.d.ts的完整内容
cat witness.d.ts

Length of output: 1539


Script:

#!/bin/bash
# 检查witness.js的具体实现
cat witness.js

Length of output: 510


73-75: 验证 tslib 依赖的必要性

作为 peer dependency 添加的 tslib 需要确认:

  1. 是否所有使用此库的项目都需要 tslib
  2. 版本范围是否合适

package.json Show resolved Hide resolved
package.json Show resolved Hide resolved
@originalix originalix merged commit 4a5219f into master Dec 5, 2024
9 checks passed
@originalix originalix deleted the feat/witness-size branch December 5, 2024 03:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants