From aa8bf2a097765d2ed3fe8bee89c99239a0f753bc Mon Sep 17 00:00:00 2001 From: chad Date: Tue, 21 May 2024 20:45:37 -0500 Subject: [PATCH 01/15] chore: added initial logger --- packages/logger/CHANGELOG.md | 0 packages/logger/LICENSE | 202 ++++++++++++++++++++++++++++++ packages/logger/README.md | 34 +++++ packages/logger/package.json | 35 ++++++ packages/logger/src/index.ts | 190 ++++++++++++++++++++++++++++ packages/logger/src/utils.ts | 17 +++ packages/logger/tsconfig.dts.json | 9 ++ packages/logger/tsconfig.json | 7 ++ packages/logger/tsdoc.json | 4 + packages/logger/tsup.config.ts | 3 + pnpm-lock.yaml | 31 +++++ 11 files changed, 532 insertions(+) create mode 100644 packages/logger/CHANGELOG.md create mode 100644 packages/logger/LICENSE create mode 100644 packages/logger/README.md create mode 100644 packages/logger/package.json create mode 100644 packages/logger/src/index.ts create mode 100644 packages/logger/src/utils.ts create mode 100644 packages/logger/tsconfig.dts.json create mode 100644 packages/logger/tsconfig.json create mode 100644 packages/logger/tsdoc.json create mode 100644 packages/logger/tsup.config.ts diff --git a/packages/logger/CHANGELOG.md b/packages/logger/CHANGELOG.md new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/logger/LICENSE b/packages/logger/LICENSE new file mode 100644 index 00000000000..57bc88a15a0 --- /dev/null +++ b/packages/logger/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/packages/logger/README.md b/packages/logger/README.md new file mode 100644 index 00000000000..5fddf534f6b --- /dev/null +++ b/packages/logger/README.md @@ -0,0 +1,34 @@ +# `@fuel-ts/logger` + +**@fuel-ts/logger** is a sub-module for logging within the **Fuel** TS ecosystem. + +A logging component that can be used to log messages to the console or to a file. + +# Table of contents + +- [`@fuel-ts/logger`](#fuel-tslogger) +- [Table of contents](#table-of-contents) + - [Installation](#installation) + - [Contributing](#contributing) + - [Changelog](#changelog) + - [License](#license) + +## Installation + +```sh +pnpm add @fuel-ts/logger +# or +npm add @fuel-ts/logger +``` + +## Contributing + +In order to contribute to `@fuel-ts/logger`, please see the main [fuels-ts](https://github.com/FuelLabs/fuels-ts) monorepo. + +## Changelog + +The `@fuel-ts/logger` changelog can be found at [CHANGELOG](./CHANGELOG.md). + +## License + +The primary license for `@fuel-ts/logger` is `Apache 2.0`, see [LICENSE](./LICENSE). diff --git a/packages/logger/package.json b/packages/logger/package.json new file mode 100644 index 00000000000..71cfb693c75 --- /dev/null +++ b/packages/logger/package.json @@ -0,0 +1,35 @@ +{ + "name": "@fuel-ts/logger", + "version": "0.88.1", + "author": "Fuel Labs (https://fuel.network/)", + "description": "A logger for the Fuel-TS ecosystem", + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "bugs": { + "url": "https://github.com/FuelLabs/fuels-ts/issues" + }, + "exports": { + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs", + "types": "./dist/index.d.ts" + } + }, + "scripts": { + "build": "tsup", + "postbuild": "tsx ../../scripts/postbuild.ts" + }, + "keywords": [ + "Fuel" + ], + "dependencies": { + "debug": "^4.3.4", + "@fuel-ts/address": "workspace:*", + "@fuel-ts/interfaces": "workspace:*" + }, + "devDependencies": { + "@types/debug": "^4.1.12" + }, + "license": "Apache-2.0" +} diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts new file mode 100644 index 00000000000..657ee97a7d9 --- /dev/null +++ b/packages/logger/src/index.ts @@ -0,0 +1,190 @@ +/* eslint-disable @typescript-eslint/no-shadow */ +/** + * @packageDocumentation + * + * A logger for fuel based on the [debug](https://www.npmjs.com/package/debug) module. + * + * @example + * + * ```TypeScript + * import { logger } from '@fuel-ts/logger' + * + * const log = logger('fuel-ts:my:package:name') + * + * try { + * // an operation + * log('something happened: %s', 'it was ok') + * } catch (err) { + * log.error('something bad happened: %o', err) + * } + * + * log('with this walletAddress: %w', address) + * log('and this B256: %b', address) + * log('and this bech32 address : %n', address) + * ``` + * + * ```console + * $ DEBUG=fuel-ts:* node index.js + * something happened: it was ok + * something bad happened: + * with this walletAddress: 0xf212....3aDc + * ``` + */ + +import { toBech32 } from '@fuel-ts/address'; +import type { Address } from '@fuel-ts/address'; +import type { AbstractAddress } from '@fuel-ts/interfaces'; +import debug from 'debug'; + +import { truncateWalletAddress } from './utils'; + +function createDisabledLogger(namespace: string): debug.Debugger { + const logger = (): void => {}; + logger.enabled = false; + logger.color = ''; + logger.diff = 0; + logger.log = (): void => {}; + logger.namespace = namespace; + logger.destroy = () => true; + logger.extend = () => logger; + + return logger; +} + +/** + * Creates a logger for the passed component name. + * + * @example + * + * ```TypeScript + * import { logger } from '@fuel-ts/logger' + * + * const log = logger('my-component') + * log.info('hello world') + * // logs "my-component hello world" + * ``` + */ +export function logger(name: string): Logger { + // info logging is a no-op by default + let info: debug.Debugger = createDisabledLogger(`${name}:info`); + + // look at all the debug names and see if trace logging has explicitly been enabled + if ( + debug.enabled(`${name}:info`) && + debug.names.map((r) => r.toString()).find((n) => n.includes(':info')) != null + ) { + info = debug(`${name}:info`); + } + + return Object.assign(debug(name), { + error: debug(`${name}:error`), + warn: debug(`${name}:warn`), + info, + }); +} + +export function disable(): void { + debug.disable(); +} + +export function enable(namespaces: string): void { + debug.enable(namespaces); +} + +export function enabled(namespaces: string): boolean { + return debug.enabled(namespaces); +} + +// Add a formatter for converting to a b256 string +debug.formatters.b = (v?: AbstractAddress): string => (v == null ? 'undefined' : v.toB256()); + +// Add a formatter for outputting a bech32 address +debug.formatters.n = (v?: AbstractAddress): string => + v == null ? 'undefined' : toBech32(v.toAddress()); + +export interface Logger { + (formatter: unknown, ...args: unknown[]): void; + error(formatter: unknown, ...args: unknown[]): void; + warn(formatter: unknown, ...args: unknown[]): void; + info(formatter: unknown, ...args: unknown[]): void; + enabled: boolean; +} + +export interface ComponentLogger { + forComponent(name: string): Logger; +} + +export interface AddressLoggerOptions { + prefixLength: number; + suffixLength: number; +} + +/** + * Create a component logger that will prefix any log messages with the passed + * string. + * + * @example + * + * ```TypeScript + * import { prefixLogger } from '@fuel-ts/logger' + * + * const logger = prefixLogger('my-node') + * + * const log = logger.forComponent('my-component') + * log.info('hello world') + * // logs "my-node:my-component hello world" + * ``` + */ +export function prefixLogger(prefix: string): ComponentLogger { + return { + forComponent(name: string) { + return logger(`${prefix}:${name}`); + }, + }; +} + +/** + * Create a component logger that will prefix any log messages with a truncated + * wallet address. + * + * @example + * + * ```TypeScript + * import { walletLogger } from '@fuel-ts/logger' + * + * const walletAddress = wallet.address.toAddress() + * const logger = walletLogger(walletAddress) + * + * const log = logger.forComponent('my-component') + * log.info('hello world') + * ``` + */ +export function walletLogger( + walletAddress: Address, + options: Partial = {} +): ComponentLogger { + return prefixLogger(truncateWalletAddress(walletAddress, options)); +} + +/** + * Create a component logger + * + * @example + * + * ```TypeScript + * import { defaultLogger } from '@fuel-ts/logger' + * + * const logger = defaultLogger() + * + * const log = logger.forComponent('my-package') + * log.info('hello world') + * // logs "my-package hello world" + * ``` + */ +export function defaultLogger(): ComponentLogger { + return { + forComponent(name: string) { + return logger(name); + }, + }; +} diff --git a/packages/logger/src/utils.ts b/packages/logger/src/utils.ts new file mode 100644 index 00000000000..fdb24729cbb --- /dev/null +++ b/packages/logger/src/utils.ts @@ -0,0 +1,17 @@ +import type { Address } from '@fuel-ts/address'; + +import type { AddressLoggerOptions } from './index'; + +export function truncateWalletAddress( + walletAddress: Address, + options: Partial = {} +): string { + const prefixLength = options.prefixLength ?? 2; + const suffixLength = options.suffixLength ?? 4; + + const walletAddressString = walletAddress.toString(); + return `${walletAddressString.substring(0, prefixLength)}…${walletAddressString.substring( + walletAddressString.length, + walletAddressString.length - suffixLength + )}`; +} diff --git a/packages/logger/tsconfig.dts.json b/packages/logger/tsconfig.dts.json new file mode 100644 index 00000000000..ccca2ac1f3e --- /dev/null +++ b/packages/logger/tsconfig.dts.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src"], + "exclude": ["**/*.test.ts"] +} diff --git a/packages/logger/tsconfig.json b/packages/logger/tsconfig.json new file mode 100644 index 00000000000..b0fced27d72 --- /dev/null +++ b/packages/logger/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist" + }, + "include": ["src"] +} diff --git a/packages/logger/tsdoc.json b/packages/logger/tsdoc.json new file mode 100644 index 00000000000..4514b072727 --- /dev/null +++ b/packages/logger/tsdoc.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json", + "extends": ["../../tsdoc.base.json"] +} diff --git a/packages/logger/tsup.config.ts b/packages/logger/tsup.config.ts new file mode 100644 index 00000000000..4c7f2f0354f --- /dev/null +++ b/packages/logger/tsup.config.ts @@ -0,0 +1,3 @@ +import { index } from '@internal/tsup'; + +export default index; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 05c8783c175..5421df6707c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,7 @@ overrides: cross-fetch: 4.0.0 importers: + .: devDependencies: '@actions/core': @@ -973,6 +974,22 @@ importers: packages/interfaces: {} + packages/logger: + dependencies: + '@fuel-ts/address': + specifier: workspace:* + version: link:../address + '@fuel-ts/interfaces': + specifier: workspace:* + version: link:../interfaces + debug: + specifier: ^4.3.4 + version: 4.3.4(supports-color@5.5.0) + devDependencies: + '@types/debug': + specifier: ^4.1.12 + version: 4.1.12 + packages/math: dependencies: '@fuel-ts/errors': @@ -1179,6 +1196,7 @@ importers: version: 5.2.2 packages: + '@aashutoshrathi/word-wrap@1.2.6': resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==} engines: {node: '>=0.10.0'} @@ -4202,6 +4220,9 @@ packages: '@types/connect@3.4.35': resolution: {integrity: sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==} + '@types/debug@4.1.12': + resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==} + '@types/eslint-scope@3.7.4': resolution: {integrity: sha512-9K4zoImiZc3HlIp6AVUDE4CWYx22a+lhSZMYNpbjW04+YF0KWj4pJXnEMjdnFTiQibFFmElcsasJXDbdI/EPhA==} @@ -4310,6 +4331,9 @@ packages: '@types/mkdirp@1.0.2': resolution: {integrity: sha512-o0K1tSO0Dx5X6xlU5F1D6625FawhC3dU3iqr25lluNv/+/QIVH8RLNEiVokgIZo+mz+87w/3Mkg/VvQS+J51fQ==} + '@types/ms@0.7.34': + resolution: {integrity: sha512-nG96G3Wp6acyAgJqGasjODb+acrI7KltPiRxzHPXnP3NgI28bpQDRv53olbqGXbfcgF5aiiHmO3xpwEpS5Ld9g==} + '@types/node-fetch@2.6.2': resolution: {integrity: sha512-DHqhlq5jeESLy19TYhLakJ07kNumXWjcDdxXsLUMJZ6ue8VZJj4kLPQVE/2mdHh3xZziNF1xppu5lwmS53HR+A==} @@ -12259,6 +12283,7 @@ packages: resolution: {integrity: sha512-V50KMwwzqJV0NpZIZFwfOD5/lyny3WlSzRiXgA0G7VUnRlqttta1L6UQIHzd6EuBY/cHGfwTIck7w1yH6Q5zUw==} snapshots: + '@aashutoshrathi/word-wrap@1.2.6': {} '@actions/core@1.10.1': @@ -16026,6 +16051,10 @@ snapshots: dependencies: '@types/node': 20.11.13 + '@types/debug@4.1.12': + dependencies: + '@types/ms': 0.7.34 + '@types/eslint-scope@3.7.4': dependencies: '@types/eslint': 8.40.2 @@ -16142,6 +16171,8 @@ snapshots: dependencies: '@types/node': 20.11.13 + '@types/ms@0.7.34': {} + '@types/node-fetch@2.6.2': dependencies: '@types/node': 20.11.13 From 5dc66fb74733e49e6a918089b9bfeb4eb5c392d0 Mon Sep 17 00:00:00 2001 From: chad Date: Tue, 21 May 2024 20:46:31 -0500 Subject: [PATCH 02/15] docs: add changeset --- .changeset/stupid-steaks-count.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/stupid-steaks-count.md diff --git a/.changeset/stupid-steaks-count.md b/.changeset/stupid-steaks-count.md new file mode 100644 index 00000000000..7b4875f7727 --- /dev/null +++ b/.changeset/stupid-steaks-count.md @@ -0,0 +1,5 @@ +--- +"@fuel-ts/logger": minor +--- + +chore: add initial logger From 2ba94f7589c0fac64d13e61ef18cb81ddac60a87 Mon Sep 17 00:00:00 2001 From: chad Date: Sun, 26 May 2024 17:20:20 -0500 Subject: [PATCH 03/15] fix: added enginge to package.json --- packages/logger/package.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/logger/package.json b/packages/logger/package.json index 71cfb693c75..7063371ce42 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -9,6 +9,9 @@ "bugs": { "url": "https://github.com/FuelLabs/fuels-ts/issues" }, + "engines": { + "node": "^18.18.2 || ^20.0.0" + }, "exports": { ".": { "require": "./dist/index.js", From d7fc2a4cffa3ae847c592e3e86ff18575f8d26a1 Mon Sep 17 00:00:00 2001 From: chad Date: Sun, 26 May 2024 17:43:23 -0500 Subject: [PATCH 04/15] docs: updated changeset --- .changeset/stupid-steaks-count.md | 2 +- packages/logger/README.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.changeset/stupid-steaks-count.md b/.changeset/stupid-steaks-count.md index 7b4875f7727..aaff9944a7c 100644 --- a/.changeset/stupid-steaks-count.md +++ b/.changeset/stupid-steaks-count.md @@ -2,4 +2,4 @@ "@fuel-ts/logger": minor --- -chore: add initial logger +chore!: add debug logger for fuel-ts ecosystem \ No newline at end of file diff --git a/packages/logger/README.md b/packages/logger/README.md index 5fddf534f6b..843d96819a5 100644 --- a/packages/logger/README.md +++ b/packages/logger/README.md @@ -8,10 +8,10 @@ A logging component that can be used to log messages to the console or to a file - [`@fuel-ts/logger`](#fuel-tslogger) - [Table of contents](#table-of-contents) - - [Installation](#installation) - - [Contributing](#contributing) - - [Changelog](#changelog) - - [License](#license) + - [Installation](#installation) + - [Contributing](#contributing) + - [Changelog](#changelog) + - [License](#license) ## Installation From 778db254b0932d96bf3f5c6e9670e5e038c4bc2a Mon Sep 17 00:00:00 2001 From: chad Date: Tue, 11 Jun 2024 09:01:58 -0400 Subject: [PATCH 05/15] test: add more tests --- package.json | 8 +++--- packages/account/package.json | 1 + packages/account/src/account.test.ts | 1 + packages/account/src/account.ts | 3 ++ packages/logger/package.json | 5 +++- packages/logger/src/index.ts | 2 +- packages/logger/test/index.test.ts | 41 ++++++++++++++++++++++++++++ pnpm-lock.yaml | 13 +++++---- vitest.config.ts | 2 +- vitest.shared.config.mts | 2 +- 10 files changed, 65 insertions(+), 13 deletions(-) create mode 100644 packages/logger/test/index.test.ts diff --git a/package.json b/package.json index 2dfba33b467..1cb06094618 100644 --- a/package.json +++ b/package.json @@ -17,14 +17,14 @@ "pretest": "turbo run pretest", "depcheck": "knip --dependencies --tags=-knipignore", "knip:fix": "knip --fix", - "test": "vitest --run --coverage --config vitest.node.config.mts $(scripts/tests-find.sh --node)", - "test:filter": "vitest --run --coverage --config vitest.node.config.mts", + "test": "vitest --run --config vitest.node.config.mts $(scripts/tests-find.sh --node)", + "test:filter": "vitest --run --config vitest.node.config.mts", "test:coverage-merge": "tsx ./scripts/tests-coverage-merge.ts", "test:coverage-diff": "tsx ./scripts/tests-coverage-diff.ts", "test:watch": "vitest --watch --config vitest.node.config.mts $(scripts/tests-find.sh --node)", "test:validate": "./scripts/tests-validate.sh", - "test:browser": "vitest --run --coverage --config vitest.browser.config.mts $(scripts/tests-find.sh --browser)", - "test:browser:filter": "vitest --run --coverage --config vitest.browser.config.mts", + "test:browser": "vitest --run --config vitest.browser.config.mts $(scripts/tests-find.sh --browser)", + "test:browser:filter": "vitest --run --config vitest.browser.config.mts", "test:e2e": "vitest --run --config vitest.node.config.mts $(scripts/tests-find.sh --e2e)", "lint": "run-s lint:check prettier:check", "lint:check": "eslint . --ext .ts --max-warnings 0", diff --git a/packages/account/package.json b/packages/account/package.json index 69aaec08ad7..a4116fe0e69 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -75,6 +75,7 @@ "@fuel-ts/hasher": "workspace:*", "@fuel-ts/math": "workspace:*", "@fuel-ts/utils": "workspace:*", + "@fuel-ts/logger": "workspace:*", "@graphql-codegen/cli": "^2.13.7", "@graphql-codegen/typescript": "^2.8.0", "@graphql-codegen/typescript-generic-sdk": "^3.1.0", diff --git a/packages/account/src/account.test.ts b/packages/account/src/account.test.ts index 73b7d9f368e..019453eb75e 100644 --- a/packages/account/src/account.test.ts +++ b/packages/account/src/account.test.ts @@ -1,6 +1,7 @@ import { Address } from '@fuel-ts/address'; import { ErrorCode, FuelError } from '@fuel-ts/errors'; import { expectToThrowFuelError } from '@fuel-ts/errors/test-utils'; +import { logger } from '@fuel-ts/logger'; import { bn } from '@fuel-ts/math'; import { PolicyType } from '@fuel-ts/transactions'; import { ASSET_A, ASSET_B } from '@fuel-ts/utils/test-utils'; diff --git a/packages/account/src/account.ts b/packages/account/src/account.ts index 2da178ef222..0c9ae97fe5d 100644 --- a/packages/account/src/account.ts +++ b/packages/account/src/account.ts @@ -4,6 +4,7 @@ import { randomBytes } from '@fuel-ts/crypto'; import { ErrorCode, FuelError } from '@fuel-ts/errors'; import { AbstractAccount } from '@fuel-ts/interfaces'; import type { AbstractAddress, BytesLike } from '@fuel-ts/interfaces'; +import { logger } from '@fuel-ts/logger'; import type { BigNumberish, BN } from '@fuel-ts/math'; import { bn } from '@fuel-ts/math'; import { arrayify, hexlify, isDefined } from '@fuel-ts/utils'; @@ -87,10 +88,12 @@ export class Account extends AbstractAccount { * @param connector - A FuelConnector instance (optional). */ constructor(address: string | AbstractAddress, provider?: Provider, connector?: FuelConnector) { + const log = logger('account'); super(); this._provider = provider; this._connector = connector; this.address = Address.fromDynamicInput(address); + log('account address is: %b ', this.address); } /** diff --git a/packages/logger/package.json b/packages/logger/package.json index 7063371ce42..2f2b81099d2 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -1,6 +1,6 @@ { "name": "@fuel-ts/logger", - "version": "0.88.1", + "version": "0.89.2", "author": "Fuel Labs (https://fuel.network/)", "description": "A logger for the Fuel-TS ecosystem", "main": "dist/index.js", @@ -26,6 +26,9 @@ "keywords": [ "Fuel" ], + "files": [ + "dist" + ], "dependencies": { "debug": "^4.3.4", "@fuel-ts/address": "workspace:*", diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts index 657ee97a7d9..3ffa95414b0 100644 --- a/packages/logger/src/index.ts +++ b/packages/logger/src/index.ts @@ -68,7 +68,7 @@ export function logger(name: string): Logger { // info logging is a no-op by default let info: debug.Debugger = createDisabledLogger(`${name}:info`); - // look at all the debug names and see if trace logging has explicitly been enabled + // look at all the debug names and see if info logging has explicitly been enabled if ( debug.enabled(`${name}:info`) && debug.names.map((r) => r.toString()).find((n) => n.includes(':info')) != null diff --git a/packages/logger/test/index.test.ts b/packages/logger/test/index.test.ts new file mode 100644 index 00000000000..658e6356368 --- /dev/null +++ b/packages/logger/test/index.test.ts @@ -0,0 +1,41 @@ +import debug from 'debug'; + +import { logger } from '../src/index'; + +/** + * @group node + */ +describe('Logger Tests', () => { + let debugSpy: any; + + beforeEach(() => { + debug.enable('test'); + debugSpy = vi.spyOn(debug, 'log'); + }); + + afterEach(() => { + debugSpy.mockRestore(); + }); + + it('should log info messages correctly', () => { + const log = logger('test'); + const message = 'This is a message'; + log(message); + const callArgs = debugSpy.mock.calls[0][0]; + expect(callArgs.substring(callArgs.indexOf(' '))).toBe(` test ${message}`); + }); + + it('should format a b256 string correctly', () => { + const log = logger('test'); + const mockAddress = { + toB256: () => '0x123456789abcdef', + toAddress: () => '0x12345678abcdef', + }; + const formattedMessage = 'test: %b'; + + log(formattedMessage, mockAddress); + + const callArgs = debugSpy.mock.calls[0][0]; + expect(callArgs).toContain('0x123456789abcdef'); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8c09ce4d247..cf57a4e4b0d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -333,7 +333,7 @@ importers: version: 18.2.0(react@18.2.0) react-scripts: specifier: 5.0.1 - version: 5.0.1(@babel/plugin-syntax-flow@7.24.6(@babel/core@7.22.5))(@babel/plugin-transform-react-jsx@7.23.4(@babel/core@7.22.5))(@types/babel__core@7.20.5)(bufferutil@4.0.8)(esbuild@0.17.19)(eslint@8.57.0)(react@18.2.0)(ts-node@10.9.1(@types/node@16.18.34)(typescript@5.2.2))(type-fest@3.1.0)(typescript@5.2.2)(utf-8-validate@6.0.4) + version: 5.0.1(@babel/plugin-syntax-flow@7.24.6(@babel/core@7.22.5))(@babel/plugin-transform-react-jsx@7.23.4(@babel/core@7.22.5))(@types/babel__core@7.20.5)(bufferutil@4.0.8)(esbuild@0.17.19)(eslint@8.57.0)(react@18.2.0)(ts-node@10.9.1(@types/node@16.18.34)(typescript@5.2.2))(type-fest@4.19.0)(typescript@5.2.2)(utf-8-validate@6.0.4) typescript: specifier: ~5.2.2 version: 5.2.2 @@ -729,6 +729,9 @@ importers: specifier: ^9.0.0 version: 9.0.0 devDependencies: + '@fuel-ts/logger': + specifier: workspace:* + version: link:../logger '@graphql-codegen/cli': specifier: ^2.13.7 version: 2.13.7(@babel/core@7.22.5)(@types/node@20.11.13)(bufferutil@4.0.8)(enquirer@2.3.6)(graphql@16.8.1)(ts-node@10.9.1(@types/node@20.11.13)(typescript@5.2.2))(typescript@5.2.2)(utf-8-validate@6.0.4) @@ -18472,7 +18475,7 @@ snapshots: dependencies: playwright: 1.44.0 - '@pmmmwh/react-refresh-webpack-plugin@0.5.10(react-refresh@0.11.0)(type-fest@3.1.0)(webpack-dev-server@4.15.1(bufferutil@4.0.8)(utf-8-validate@6.0.4)(webpack@5.88.0(esbuild@0.17.19)))(webpack@5.88.0(esbuild@0.17.19))': + '@pmmmwh/react-refresh-webpack-plugin@0.5.10(react-refresh@0.11.0)(type-fest@4.19.0)(webpack-dev-server@4.15.1(bufferutil@4.0.8)(utf-8-validate@6.0.4)(webpack@5.88.0(esbuild@0.17.19)))(webpack@5.88.0(esbuild@0.17.19))': dependencies: ansi-html-community: 0.0.8 common-path-prefix: 3.0.0 @@ -18486,7 +18489,7 @@ snapshots: source-map: 0.7.4 webpack: 5.88.0(esbuild@0.17.19) optionalDependencies: - type-fest: 3.1.0 + type-fest: 4.19.0 webpack-dev-server: 4.15.1(bufferutil@4.0.8)(utf-8-validate@6.0.4)(webpack@5.88.0(esbuild@0.17.19)) '@pnpm/constants@7.1.1': {} @@ -28648,10 +28651,10 @@ snapshots: optionalDependencies: '@types/react': 18.2.9 - react-scripts@5.0.1(@babel/plugin-syntax-flow@7.24.6(@babel/core@7.22.5))(@babel/plugin-transform-react-jsx@7.23.4(@babel/core@7.22.5))(@types/babel__core@7.20.5)(bufferutil@4.0.8)(esbuild@0.17.19)(eslint@8.57.0)(react@18.2.0)(ts-node@10.9.1(@types/node@16.18.34)(typescript@5.2.2))(type-fest@3.1.0)(typescript@5.2.2)(utf-8-validate@6.0.4): + react-scripts@5.0.1(@babel/plugin-syntax-flow@7.24.6(@babel/core@7.22.5))(@babel/plugin-transform-react-jsx@7.23.4(@babel/core@7.22.5))(@types/babel__core@7.20.5)(bufferutil@4.0.8)(esbuild@0.17.19)(eslint@8.57.0)(react@18.2.0)(ts-node@10.9.1(@types/node@16.18.34)(typescript@5.2.2))(type-fest@4.19.0)(typescript@5.2.2)(utf-8-validate@6.0.4): dependencies: '@babel/core': 7.22.5 - '@pmmmwh/react-refresh-webpack-plugin': 0.5.10(react-refresh@0.11.0)(type-fest@3.1.0)(webpack-dev-server@4.15.1(bufferutil@4.0.8)(utf-8-validate@6.0.4)(webpack@5.88.0(esbuild@0.17.19)))(webpack@5.88.0(esbuild@0.17.19)) + '@pmmmwh/react-refresh-webpack-plugin': 0.5.10(react-refresh@0.11.0)(type-fest@4.19.0)(webpack-dev-server@4.15.1(bufferutil@4.0.8)(utf-8-validate@6.0.4)(webpack@5.88.0(esbuild@0.17.19)))(webpack@5.88.0(esbuild@0.17.19)) '@svgr/webpack': 5.5.0 babel-jest: 27.5.1(@babel/core@7.22.5) babel-loader: 8.3.0(@babel/core@7.22.5)(webpack@5.88.0(esbuild@0.17.19)) diff --git a/vitest.config.ts b/vitest.config.ts index 224c9b5a35d..16dc9fc38bf 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { coverage: { - enabled: true, + enabled: false, provider: 'istanbul', reporter: ['json', 'text', 'html'], include: ['packages', 'internal', 'apps'], diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index 6635fa35d93..dce5922dd9f 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -13,7 +13,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { coverage: { - enabled: true, + enabled: false, provider: "istanbul", reporter: ["json", "text", "html"], include: ["packages", "internal", "apps"], From 4a6317814e6882e84d6f61a3be48916954aa6481 Mon Sep 17 00:00:00 2001 From: chad Date: Tue, 11 Jun 2024 17:34:46 -0400 Subject: [PATCH 06/15] build: undo coverage changes --- package.json | 8 ++++---- vitest.config.ts | 2 +- vitest.shared.config.mts | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index 818b1c833c9..78aae96a9d6 100644 --- a/package.json +++ b/package.json @@ -17,14 +17,14 @@ "pretest": "turbo run pretest", "depcheck": "knip --dependencies --tags=-knipignore", "knip:fix": "knip --fix", - "test": "vitest --run --config vitest.node.config.mts $(scripts/tests-find.sh --node)", - "test:filter": "vitest --run --config vitest.node.config.mts", + "test": "vitest --run --coverage --config vitest.node.config.mts $(scripts/tests-find.sh --node)", + "test:filter": "vitest --run --coverage --config vitest.node.config.mts", "test:coverage-merge": "tsx ./scripts/tests-coverage-merge.ts", "test:coverage-diff": "tsx ./scripts/tests-coverage-diff.ts", "test:watch": "vitest --watch --config vitest.node.config.mts $(scripts/tests-find.sh --node)", "test:validate": "./scripts/tests-validate.sh", - "test:browser": "vitest --run --config vitest.browser.config.mts $(scripts/tests-find.sh --browser)", - "test:browser:filter": "vitest --run --config vitest.browser.config.mts", + "test:browser": "vitest --run --coverage --config vitest.browser.config.mts $(scripts/tests-find.sh --browser)", + "test:browser:filter": "vitest --run --coverage --config vitest.browser.config.mts", "test:e2e": "vitest --run --config vitest.node.config.mts $(scripts/tests-find.sh --e2e)", "lint": "run-s lint:check prettier:check", "lint:check": "eslint . --ext .ts --max-warnings 0", diff --git a/vitest.config.ts b/vitest.config.ts index 16dc9fc38bf..224c9b5a35d 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { coverage: { - enabled: false, + enabled: true, provider: 'istanbul', reporter: ['json', 'text', 'html'], include: ['packages', 'internal', 'apps'], diff --git a/vitest.shared.config.mts b/vitest.shared.config.mts index 102c8f0b096..72525696119 100644 --- a/vitest.shared.config.mts +++ b/vitest.shared.config.mts @@ -15,7 +15,7 @@ export default defineConfig({ esbuild: { target: "es2022" }, test: { coverage: { - enabled: false, + enabled: true, provider: "istanbul", reporter: ["json", "text", "html"], include: ["packages", "internal", "apps"], From d0e9052b5b4e1a11006666d52fd4ead426102558 Mon Sep 17 00:00:00 2001 From: chad Date: Wed, 12 Jun 2024 17:24:09 -0400 Subject: [PATCH 07/15] feat: fix build issues --- packages/account/package.json | 1 - packages/account/src/account.test.ts | 1 - packages/account/src/account.ts | 3 --- packages/logger/test/index.test.ts | 2 +- pnpm-lock.yaml | 5 +---- 5 files changed, 2 insertions(+), 10 deletions(-) diff --git a/packages/account/package.json b/packages/account/package.json index a4116fe0e69..69aaec08ad7 100644 --- a/packages/account/package.json +++ b/packages/account/package.json @@ -75,7 +75,6 @@ "@fuel-ts/hasher": "workspace:*", "@fuel-ts/math": "workspace:*", "@fuel-ts/utils": "workspace:*", - "@fuel-ts/logger": "workspace:*", "@graphql-codegen/cli": "^2.13.7", "@graphql-codegen/typescript": "^2.8.0", "@graphql-codegen/typescript-generic-sdk": "^3.1.0", diff --git a/packages/account/src/account.test.ts b/packages/account/src/account.test.ts index 019453eb75e..73b7d9f368e 100644 --- a/packages/account/src/account.test.ts +++ b/packages/account/src/account.test.ts @@ -1,7 +1,6 @@ import { Address } from '@fuel-ts/address'; import { ErrorCode, FuelError } from '@fuel-ts/errors'; import { expectToThrowFuelError } from '@fuel-ts/errors/test-utils'; -import { logger } from '@fuel-ts/logger'; import { bn } from '@fuel-ts/math'; import { PolicyType } from '@fuel-ts/transactions'; import { ASSET_A, ASSET_B } from '@fuel-ts/utils/test-utils'; diff --git a/packages/account/src/account.ts b/packages/account/src/account.ts index 0c9ae97fe5d..2da178ef222 100644 --- a/packages/account/src/account.ts +++ b/packages/account/src/account.ts @@ -4,7 +4,6 @@ import { randomBytes } from '@fuel-ts/crypto'; import { ErrorCode, FuelError } from '@fuel-ts/errors'; import { AbstractAccount } from '@fuel-ts/interfaces'; import type { AbstractAddress, BytesLike } from '@fuel-ts/interfaces'; -import { logger } from '@fuel-ts/logger'; import type { BigNumberish, BN } from '@fuel-ts/math'; import { bn } from '@fuel-ts/math'; import { arrayify, hexlify, isDefined } from '@fuel-ts/utils'; @@ -88,12 +87,10 @@ export class Account extends AbstractAccount { * @param connector - A FuelConnector instance (optional). */ constructor(address: string | AbstractAddress, provider?: Provider, connector?: FuelConnector) { - const log = logger('account'); super(); this._provider = provider; this._connector = connector; this.address = Address.fromDynamicInput(address); - log('account address is: %b ', this.address); } /** diff --git a/packages/logger/test/index.test.ts b/packages/logger/test/index.test.ts index 658e6356368..8fcba6d9e4e 100644 --- a/packages/logger/test/index.test.ts +++ b/packages/logger/test/index.test.ts @@ -6,7 +6,7 @@ import { logger } from '../src/index'; * @group node */ describe('Logger Tests', () => { - let debugSpy: any; + let debugSpy; beforeEach(() => { debug.enable('test'); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c415eb01d8a..a247dd4ca90 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -732,9 +732,6 @@ importers: specifier: ^9.0.0 version: 9.0.0 devDependencies: - '@fuel-ts/logger': - specifier: workspace:* - version: link:../logger '@graphql-codegen/cli': specifier: ^2.13.7 version: 2.13.7(@babel/core@7.22.5)(@types/node@20.11.13)(bufferutil@4.0.8)(enquirer@2.3.6)(graphql@16.8.1)(ts-node@10.9.1(@types/node@20.11.13)(typescript@5.2.2))(typescript@5.2.2)(utf-8-validate@6.0.4) @@ -20157,7 +20154,7 @@ snapshots: '@vitest/utils': 1.6.0 magic-string: 0.30.5 sirv: 2.0.4 - vitest: 1.6.0(@types/node@18.15.3)(@vitest/browser@1.6.0)(jsdom@16.7.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))(terser@5.18.2) + vitest: 1.6.0(@types/node@20.11.13)(@vitest/browser@1.6.0)(jsdom@16.7.0(bufferutil@4.0.8)(utf-8-validate@6.0.4))(terser@5.18.2) optionalDependencies: playwright: 1.44.0 webdriverio: 8.36.1(bufferutil@4.0.8)(typescript@5.2.2)(utf-8-validate@6.0.4) From b1a6206b2da502be8ded536bc0d7d6cc4c853bdc Mon Sep 17 00:00:00 2001 From: chad Date: Wed, 12 Jun 2024 18:25:39 -0400 Subject: [PATCH 08/15] feat: update BN formatter --- packages/logger/package.json | 3 ++- packages/logger/src/index.ts | 26 ++++++++++++++++++++++++++ pnpm-lock.yaml | 6 ++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/logger/package.json b/packages/logger/package.json index 2f2b81099d2..6e692a8d346 100644 --- a/packages/logger/package.json +++ b/packages/logger/package.json @@ -32,7 +32,8 @@ "dependencies": { "debug": "^4.3.4", "@fuel-ts/address": "workspace:*", - "@fuel-ts/interfaces": "workspace:*" + "@fuel-ts/interfaces": "workspace:*", + "@fuel-ts/math": "workspace:*" }, "devDependencies": { "@types/debug": "^4.1.12" diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts index 3ffa95414b0..c4b69c3fdf0 100644 --- a/packages/logger/src/index.ts +++ b/packages/logger/src/index.ts @@ -34,6 +34,8 @@ import { toBech32 } from '@fuel-ts/address'; import type { Address } from '@fuel-ts/address'; import type { AbstractAddress } from '@fuel-ts/interfaces'; +import type { BN } from '@fuel-ts/math'; +import { bn } from '@fuel-ts/math'; import debug from 'debug'; import { truncateWalletAddress } from './utils'; @@ -95,6 +97,27 @@ export function enabled(namespaces: string): boolean { return debug.enabled(namespaces); } +// Add a formatter for outputting a comma separated BN string +debug.formatters.a = (v?: BN): string => { + if (!v) { + return 'undefined'; + } + return v.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); +}; + +// Converts a hex string to a BN string +debug.formatters.n = (hex: string): string => { + if (!hex) { + return 'undefined'; + } + try { + const bnValue = bn(hex, 'hex'); + return bnValue.toString(); + } catch (error) { + return 'invalid hex'; + } +}; + // Add a formatter for converting to a b256 string debug.formatters.b = (v?: AbstractAddress): string => (v == null ? 'undefined' : v.toB256()); @@ -102,6 +125,9 @@ debug.formatters.b = (v?: AbstractAddress): string => (v == null ? 'undefined' : debug.formatters.n = (v?: AbstractAddress): string => v == null ? 'undefined' : toBech32(v.toAddress()); +// Add a formatter for outputting a BN hex string +debug.formatters.h = (v?: BN): string => (v == null ? 'undefined' : v.toHex()); + export interface Logger { (formatter: unknown, ...args: unknown[]): void; error(formatter: unknown, ...args: unknown[]): void; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a247dd4ca90..85868b8319e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -686,6 +686,9 @@ importers: '@fuel-ts/interfaces': specifier: workspace:* version: link:../interfaces + '@fuel-ts/logger': + specifier: workspace:* + version: link:../logger '@fuel-ts/math': specifier: workspace:* version: link:../math @@ -1023,6 +1026,9 @@ importers: '@fuel-ts/interfaces': specifier: workspace:* version: link:../interfaces + '@fuel-ts/math': + specifier: workspace:* + version: link:../math debug: specifier: ^4.3.4 version: 4.3.4(supports-color@5.5.0) From 2e3f26fed2d83f34aab903fb626726cffe61287b Mon Sep 17 00:00:00 2001 From: chad Date: Wed, 12 Jun 2024 18:28:39 -0400 Subject: [PATCH 09/15] build: update lockfile --- pnpm-lock.yaml | 3 --- 1 file changed, 3 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 85868b8319e..180477d5946 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -686,9 +686,6 @@ importers: '@fuel-ts/interfaces': specifier: workspace:* version: link:../interfaces - '@fuel-ts/logger': - specifier: workspace:* - version: link:../logger '@fuel-ts/math': specifier: workspace:* version: link:../math From 2275c66a778552093cc449c99be191bdc80b99d8 Mon Sep 17 00:00:00 2001 From: chad Date: Mon, 17 Jun 2024 15:35:34 -0500 Subject: [PATCH 10/15] test: add more tests --- packages/logger/test/index.test.ts | 30 +++++++++++++++++++++++++++++- packages/logger/test/utils.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 packages/logger/test/utils.test.ts diff --git a/packages/logger/test/index.test.ts b/packages/logger/test/index.test.ts index 8fcba6d9e4e..5594d296ea1 100644 --- a/packages/logger/test/index.test.ts +++ b/packages/logger/test/index.test.ts @@ -1,9 +1,11 @@ +import type { Address } from '@fuel-ts/address'; import debug from 'debug'; -import { logger } from '../src/index'; +import { logger, prefixLogger, defaultLogger } from '../src/index'; /** * @group node + * @group browser */ describe('Logger Tests', () => { let debugSpy; @@ -38,4 +40,30 @@ describe('Logger Tests', () => { const callArgs = debugSpy.mock.calls[0][0]; expect(callArgs).toContain('0x123456789abcdef'); }); + + it('should prefix log messages correctly using prefixLogger', () => { + const prefix = 'my-node'; + const component = 'my-component'; + const message = 'hello world'; + const prefixedLogger = prefixLogger(prefix); + const log = prefixedLogger.forComponent(component); + + debug.enable('my-node:my-component'); + + log(message); + const callArgs = debugSpy.mock.calls[0][0]; + expect(callArgs).toContain(`${prefix}:${component} ${message}`); + }); + + it('should create a default logger and log messages correctly', () => { + const defaultLog = defaultLogger(); + const log = defaultLog.forComponent('test-component'); + debug.enable('test-component'); + const message = 'default logger test message'; + + log(message); + + const callArgs = debugSpy.mock.calls[0][0]; + expect(callArgs).toContain(`test-component ${message}`); + }); }); diff --git a/packages/logger/test/utils.test.ts b/packages/logger/test/utils.test.ts new file mode 100644 index 00000000000..ad1f324ad44 --- /dev/null +++ b/packages/logger/test/utils.test.ts @@ -0,0 +1,22 @@ +import type { Address } from '@fuel-ts/address'; + +import { truncateWalletAddress } from '../src/utils'; + +describe('truncateWalletAddress Tests', () => { + it('should correctly truncate a wallet address', () => { + const mockAddress: Address = { + toString: () => '0x1234567890abcdef1234567890abcdef', + }; + const options = { prefixLength: 6, suffixLength: 4 }; + const result = truncateWalletAddress(mockAddress, options); + expect(result).toBe('0x1234…cdef'); + }); + + it('should handle default options if none provided', () => { + const mockAddress: Address = { + toString: () => '0x1234567890abcdef1234567890abcdef', + }; + const result = truncateWalletAddress(mockAddress); + expect(result).toBe('0x…cdef'); + }); +}); From 7bef07d3cb1b6afad8c5be195d0bb6813e9e9049 Mon Sep 17 00:00:00 2001 From: chad Date: Mon, 17 Jun 2024 15:38:09 -0500 Subject: [PATCH 11/15] docs: update changeset --- .changeset/stupid-steaks-count.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/stupid-steaks-count.md b/.changeset/stupid-steaks-count.md index aaff9944a7c..e5f5060d451 100644 --- a/.changeset/stupid-steaks-count.md +++ b/.changeset/stupid-steaks-count.md @@ -2,4 +2,4 @@ "@fuel-ts/logger": minor --- -chore!: add debug logger for fuel-ts ecosystem \ No newline at end of file +chore: add debug logger for fuel-ts ecosystem \ No newline at end of file From 7c403c24968bfaa58321940c6530026be7c3826f Mon Sep 17 00:00:00 2001 From: chad Date: Mon, 17 Jun 2024 15:42:53 -0500 Subject: [PATCH 12/15] test: add test environment config --- packages/logger/test/utils.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/logger/test/utils.test.ts b/packages/logger/test/utils.test.ts index ad1f324ad44..aa90837ad35 100644 --- a/packages/logger/test/utils.test.ts +++ b/packages/logger/test/utils.test.ts @@ -2,6 +2,10 @@ import type { Address } from '@fuel-ts/address'; import { truncateWalletAddress } from '../src/utils'; +/** + * @group node + * @group browser + */ describe('truncateWalletAddress Tests', () => { it('should correctly truncate a wallet address', () => { const mockAddress: Address = { From 9019b50104fc3b820744ef013e3e61d563afafc2 Mon Sep 17 00:00:00 2001 From: chad Date: Mon, 17 Jun 2024 17:25:30 -0500 Subject: [PATCH 13/15] test: remove browser testing --- packages/logger/test/index.test.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/logger/test/index.test.ts b/packages/logger/test/index.test.ts index 5594d296ea1..856e7670031 100644 --- a/packages/logger/test/index.test.ts +++ b/packages/logger/test/index.test.ts @@ -1,11 +1,9 @@ -import type { Address } from '@fuel-ts/address'; import debug from 'debug'; import { logger, prefixLogger, defaultLogger } from '../src/index'; /** * @group node - * @group browser */ describe('Logger Tests', () => { let debugSpy; @@ -24,7 +22,7 @@ describe('Logger Tests', () => { const message = 'This is a message'; log(message); const callArgs = debugSpy.mock.calls[0][0]; - expect(callArgs.substring(callArgs.indexOf(' '))).toBe(` test ${message}`); + expect(callArgs).toContain(`test ${message}`); }); it('should format a b256 string correctly', () => { From f958588e1764af1fcd9f1c0b3f2f59bec518eb5a Mon Sep 17 00:00:00 2001 From: chad Date: Mon, 17 Jun 2024 17:29:16 -0500 Subject: [PATCH 14/15] docs: revert changeset --- .changeset/stupid-steaks-count.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/stupid-steaks-count.md b/.changeset/stupid-steaks-count.md index e5f5060d451..aaff9944a7c 100644 --- a/.changeset/stupid-steaks-count.md +++ b/.changeset/stupid-steaks-count.md @@ -2,4 +2,4 @@ "@fuel-ts/logger": minor --- -chore: add debug logger for fuel-ts ecosystem \ No newline at end of file +chore!: add debug logger for fuel-ts ecosystem \ No newline at end of file From 22609cf4d50c21222e69bbf63802dc202621adbb Mon Sep 17 00:00:00 2001 From: chad Date: Tue, 18 Jun 2024 12:42:51 -0500 Subject: [PATCH 15/15] test: add formatter tests --- packages/logger/src/index.ts | 20 ++++----- packages/logger/test/index.test.ts | 72 ++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts index c4b69c3fdf0..a93a53989c5 100644 --- a/packages/logger/src/index.ts +++ b/packages/logger/src/index.ts @@ -105,6 +105,16 @@ debug.formatters.a = (v?: BN): string => { return v.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; +// Add a formatter for converting to a b256 string +debug.formatters.b = (v?: AbstractAddress): string => (v == null ? 'undefined' : v.toB256()); + +// Add a formatter for outputting a bech32 address +debug.formatters.c = (v?: AbstractAddress): string => + v == null ? 'undefined' : toBech32(v.toString()); + +// Add a formatter for outputting a BN hex string +debug.formatters.h = (v?: BN): string => (v == null ? 'undefined' : v.toHex()); + // Converts a hex string to a BN string debug.formatters.n = (hex: string): string => { if (!hex) { @@ -118,16 +128,6 @@ debug.formatters.n = (hex: string): string => { } }; -// Add a formatter for converting to a b256 string -debug.formatters.b = (v?: AbstractAddress): string => (v == null ? 'undefined' : v.toB256()); - -// Add a formatter for outputting a bech32 address -debug.formatters.n = (v?: AbstractAddress): string => - v == null ? 'undefined' : toBech32(v.toAddress()); - -// Add a formatter for outputting a BN hex string -debug.formatters.h = (v?: BN): string => (v == null ? 'undefined' : v.toHex()); - export interface Logger { (formatter: unknown, ...args: unknown[]): void; error(formatter: unknown, ...args: unknown[]): void; diff --git a/packages/logger/test/index.test.ts b/packages/logger/test/index.test.ts index 856e7670031..d458df5e663 100644 --- a/packages/logger/test/index.test.ts +++ b/packages/logger/test/index.test.ts @@ -1,3 +1,5 @@ +import type { AbstractAddress } from '@fuel-ts/interfaces'; +import { BN } from '@fuel-ts/math'; import debug from 'debug'; import { logger, prefixLogger, defaultLogger } from '../src/index'; @@ -64,4 +66,74 @@ describe('Logger Tests', () => { const callArgs = debugSpy.mock.calls[0][0]; expect(callArgs).toContain(`test-component ${message}`); }); + + it('should format BN values with commas correctly using formatter a', () => { + const bnValue = new BN('1000000'); + const formatted = debug.formatters.a(bnValue); + expect(formatted).toBe('1,000,000'); + }); + + it('should return undefined for null input using formatter a', () => { + const formatted = debug.formatters.a(null); + expect(formatted).toBe('undefined'); + }); + + it('should format AbstractAddress to b256 string using formatter b', () => { + const mockAddress = { + toB256: () => '0xabcdef1234567890', + }; + const formatted = debug.formatters.b(mockAddress); + expect(formatted).toBe('0xabcdef1234567890'); + }); + + it('should return undefined for null input using formatter b', () => { + const formatted = debug.formatters.b(null); + expect(formatted).toBe('undefined'); + }); + + it('should format AbstractAddress to bech32 string using formatter c', () => { + const mockAddress: AbstractAddress = { + toJSON: () => '', + toString: () => '0x000000000000000000000000000000000000000000000000000000000000002a', + toAddress: () => 'fuel1xyzabc123', + toB256: () => '', + toHexString: () => '', + toBytes: () => new Uint8Array(), + equals: () => false, + }; + const formatted = debug.formatters.c(mockAddress); + expect(formatted).toBe('fuel1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq4qvpkv30'); + }); + + it('should return undefined for null input using formatter c', () => { + const formatted = debug.formatters.c(null); + expect(formatted).toBe('undefined'); + }); + + it('should format BN to hex string using formatter h', () => { + const bnValue = new BN('255'); + const formatted = debug.formatters.h(bnValue); + expect(formatted).toBe('0xff'); + }); + + it('should return undefined for null input using formatter h', () => { + const formatted = debug.formatters.h(null); + expect(formatted).toBe('undefined'); + }); + + it('should convert hex string to BN string using formatter n', () => { + const hex = '0xff'; + const formatted = debug.formatters.n(hex); + expect(formatted).toBe('255'); + }); + + it('should return undefined for empty input using formatter n', () => { + const formatted = debug.formatters.n(''); + expect(formatted).toBe('undefined'); + }); + + it('should return invalid hex for invalid input using formatter n', () => { + const formatted = debug.formatters.n('zzz'); + expect(formatted).toBe('invalid hex'); + }); });