Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ jobs:
CI_JOB_NUMBER: 2
steps:
- uses: actions/checkout@v1
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v6
with:
node-version-file: '.nvmrc'
- run: corepack enable
- run: yarn install
- run: yarn workspace @hawk.so/javascript test
- run: yarn test:modified origin/${{ github.event.pull_request.base.ref }}

build:
runs-on: ubuntu-latest
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"dev": "yarn workspace @hawk.so/javascript dev",
"build:all": "yarn workspaces foreach -Apt run build",
"build:modified": "yarn workspaces foreach --since=\"$@\" -Rpt run build",
"test:all": "yarn workspaces foreach -Apt run test",
"test:modified": "yarn workspaces foreach --since=\"$@\" -Rpt run test",
"stats": "yarn workspace @hawk.so/javascript stats",
"lint": "eslint -c ./.eslintrc.cjs packages/*/src --ext .ts,.js --fix",
"lint-test": "eslint -c ./.eslintrc.cjs packages/*/src --ext .ts,.js"
Expand Down
12 changes: 10 additions & 2 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
}
},
"scripts": {
"build": "vite build"
"build": "vite build",
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"lint": "eslint --fix \"src/**/*.{js,ts}\""
},
"repository": {
"type": "git",
Expand All @@ -33,8 +36,13 @@
"url": "https://github.com/codex-team/hawk.javascript/issues"
},
"homepage": "https://github.com/codex-team/hawk.javascript#readme",
"dependencies": {
"@hawk.so/types": "0.5.8"
},
"devDependencies": {
"@vitest/coverage-v8": "^4.0.18",
"vite": "^7.3.1",
"vite-plugin-dts": "^4.2.4"
"vite-plugin-dts": "^4.2.4",
"vitest": "^4.0.18"
}
}
File renamed without changes.
11 changes: 11 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export type { HawkStorage } from './storages/hawk-storage';
export { HawkUserManager } from './users/hawk-user-manager';
export type { Logger, LogType } from './logger/logger';
export { isLoggerSet, setLogger, resetLogger, log } from './logger/logger';
export { Sanitizer } from './modules/sanitizer';
export { StackParser } from './modules/stack-parser';
export { buildElementSelector } from './utils/selector';
export type { Transport } from './transports/transport';
export { EventRejectedError } from './errors';
export { isErrorProcessed, markErrorAsProcessed } from './utils/event';
export { isPlainObject, validateUser, validateContext, isValidEventPayload, isValidBreadcrumb } from './utils/validation';
68 changes: 68 additions & 0 deletions packages/core/src/logger/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/**
* Log level type for categorizing log messages.
*
* Includes standard console methods supported in both browser and Node.js:
* - Standard levels: `log`, `warn`, `error`, `info`
* - Performance timing: `time`, `timeEnd`
*/
export type LogType = 'log' | 'warn' | 'error' | 'info' | 'time' | 'timeEnd';

/**
* Logger function interface for environment-specific logging implementations.
*
* Implementations should handle message formatting, output styling,
* and platform-specific logging mechanisms (e.g., console, file, network).
*
* @param msg - The message to log.
* @param type - Log level/severity (default: 'log').
* @param args - Additional data to include with the log message.
*/
export interface Logger {
(msg: string, type?: LogType, args?: unknown): void;
}

/**
* Global logger instance, set by environment-specific packages.
*/
let loggerInstance: Logger | null = null;

/**
* Checks if logger instance has been registered.
*/
export function isLoggerSet(): boolean {
return loggerInstance !== null;
}

/**
* Registers the environment-specific logger implementation.
*
* This should be called once during application initialization
* by the environment-specific package.
*
* @param logger - Logger implementation to use globally.
*/
export function setLogger(logger: Logger): void {
loggerInstance = logger;
}

/**
* Clears the registered logger instance.
*/
export function resetLogger(): void {
loggerInstance = null;
}

/**
* Logs a message using the registered logger implementation.
*
* If no logger has been registered via {@link setLogger}, this is a no-op.
*
* @param msg - Message to log.
* @param type - Log level (default: 'log').
* @param args - Additional arguments to log.
*/
export function log(msg: string, type?: LogType, args?: unknown): void {
if (loggerInstance) {
loggerInstance(msg, type, args);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import log from '../utils/log';
import { log } from '@hawk.so/core';

/**
* Sends AJAX request and wait for some time.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { isPlainObject } from '../utils/validation';

/**
* This class provides methods for preparing data to sending to Hawk
* - trim long strings
* - represent html elements like <div ...> as "<div>" instead of "{}"
* - represent big objects as "<big object>"
* - represent class as <class SomeClass> or <instance of SomeClass>
*/
export default class Sanitizer {
export class Sanitizer {
/**
* Maximum string length
*/
Expand Down Expand Up @@ -34,7 +36,7 @@ export default class Sanitizer {
* @param target - variable to check
*/
public static isObject(target: any): boolean {
return Sanitizer.typeOf(target) === 'object';
return isPlainObject(target);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { StackFrame } from 'error-stack-parser';
import ErrorStackParser from 'error-stack-parser';
import type { BacktraceFrame, SourceCodeLine } from '@hawk.so/types';
import fetchTimer from './fetchTimer';
import fetchTimer from './fetch-timer';

/**
* This module prepares parsed backtrace
*/
export default class StackParser {
export class StackParser {
/**
* Prevents loading one file several times
* name -> content
Expand Down Expand Up @@ -48,7 +48,7 @@ export default class StackParser {
try {
if (!frame.fileName) {
return null;
};
}

if (!this.isValidUrl(frame.fileName)) {
return null;
Expand Down Expand Up @@ -118,9 +118,9 @@ export default class StackParser {
/**
* Downloads source file
*
* @param {string} fileName - name of file to download
* @param fileName - name of file to download
*/
private async loadSourceFile(fileName): Promise<string | null> {
private async loadSourceFile(fileName: string): Promise<string | null> {
if (this.sourceFilesCache[fileName] !== undefined) {
return this.sourceFilesCache[fileName];
}
Expand Down
26 changes: 26 additions & 0 deletions packages/core/src/storages/hawk-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Abstract key–value storage contract used by Hawk internals to persist data across sessions.
*/
export interface HawkStorage {
/**
* Returns the value associated with the given key, or `null` if none exists or on error.
*
* @param key - Storage key to look up.
*/
getItem(key: string): string | null;

/**
* Persists a value under the given key. Must not throw on failure.
*
* @param key - Storage key.
* @param value - Value to store.
*/
setItem(key: string, value: string): void;

/**
* Removes the entry for the given key. Must not throw on failure.
*
* @param key - Storage key to remove.
*/
removeItem(key: string): void;
}
9 changes: 9 additions & 0 deletions packages/core/src/transports/transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { CatcherMessage } from '@hawk.so/types';
import { CatcherMessageType } from '@hawk.so/types';

/**
* Transport interface — anything that can send a CatcherMessage
*/
export interface Transport<T extends CatcherMessageType> {
send(message: CatcherMessage<T>): Promise<void>;
}
71 changes: 71 additions & 0 deletions packages/core/src/users/hawk-user-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import type { AffectedUser } from '@hawk.so/types';
import type { HawkStorage } from '../storages/hawk-storage';

/**
* Storage key used to persist the auto-generated user ID.
*/
export const HAWK_USER_ID_KEY = 'hawk-user-id';

/**
* Manages the affected user identity.
*
* Manually provided users are kept in memory only (they don't change restarts).
* {@link HawkStorage} is used solely to persist the auto-generated ID
* so it survives across sessions.
*/
export class HawkUserManager {
/**
* In-memory user set explicitly via {@link setUser}.
*/
private user: AffectedUser | null = null;

/**
* Underlying storage used to persist auto-generated user ID.
*/
private readonly storage: HawkStorage;

/**
* @param storage - Storage backend to use for persistence.
*/
constructor(storage: HawkStorage) {
this.storage = storage;
}

/**
* Returns the current affected user, or `null` if none is available.
*
* Priority: in-memory user > persisted user ID.
*/
public getUser(): AffectedUser | null {
if (this.user) {
return this.user;
}
const storedId = this.storage.getItem(HAWK_USER_ID_KEY);
return storedId ? { id: storedId } : null;
}

/**
* Sets the user explicitly (in memory only).
*
* @param user - The affected user provided by the application.
*/
public setUser(user: AffectedUser): void {
this.user = user;
}

/**
* Persists an auto-generated user ID to storage.
*
* @param id - The generated ID to persist.
*/
public persistGeneratedId(id: string): void {
this.storage.setItem(HAWK_USER_ID_KEY, id);
}

/**
* Clears the explicitly set user, falling back to the persisted user ID.
*/
public clear(): void {
this.user = null;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import log from './log';
import { log } from '../logger/logger';

/**
* Symbol to mark error as processed by Hawk
*/
const errorSentShadowProperty = Symbol('__hawk_processed__');

/**
* Check if the error has alrady been sent to Hawk.
* Check if the error has already been sent to Hawk.
*
* Motivation:
* Some integrations may catch errors on their own side and then normally re-throw them down.
Expand All @@ -20,7 +20,7 @@ export function isErrorProcessed(error: unknown): boolean {
return false;
}

return error[errorSentShadowProperty] === true;
return (error as Record<symbol, unknown>)[errorSentShadowProperty] === true;
}

/**
Expand All @@ -35,7 +35,7 @@ export function markErrorAsProcessed(error: unknown): void {
}

Object.defineProperty(error, errorSentShadowProperty, {
enumerable: false, // Prevent from beight collected by Hawk
enumerable: false, // Prevent from being collected by Hawk
value: true,
writable: true,
configurable: true,
Expand Down
Loading