@allternit/gizzi-code 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/bin/gizzi +4 -0
  2. package/bin/gizzi-ink +5 -0
  3. package/package.json +137 -31
  4. package/src/Tool.ts +26 -0
  5. package/src/bootstrap/state.ts +165 -322
  6. package/src/commands.ts +209 -0
  7. package/src/context/QueuedMessageContext.tsx +63 -0
  8. package/src/context/fpsMetrics.tsx +30 -0
  9. package/src/context/mailbox.tsx +38 -0
  10. package/src/context/modalContext.tsx +58 -0
  11. package/src/context/notifications.tsx +240 -0
  12. package/src/context/overlayContext.tsx +151 -0
  13. package/src/context/promptOverlayContext.tsx +125 -0
  14. package/src/context/stats.tsx +220 -0
  15. package/src/context/voice.tsx +88 -0
  16. package/src/hooks/useCanUseTool.ts +11 -0
  17. package/src/hooks/useExitOnCtrlCD.ts +40 -187
  18. package/src/hooks/useExitOnCtrlCDWithKeybindings.ts +68 -0
  19. package/src/hooks/useKeybinding.ts +68 -209
  20. package/src/hooks/useTerminalSize.ts +31 -99
  21. package/src/hooks.ts +37 -0
  22. package/src/ink.ts +204 -0
  23. package/src/main.ts +7 -0
  24. package/src/types/command.ts +216 -0
  25. package/src/types/connectorText.ts +39 -0
  26. package/src/types/fileSuggestion.ts +15 -0
  27. package/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.ts +865 -0
  28. package/src/types/generated/events_mono/common/v1/auth.ts +100 -0
  29. package/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.ts +223 -0
  30. package/src/types/generated/google/protobuf/timestamp.ts +187 -0
  31. package/src/types/hooks.ts +319 -0
  32. package/src/types/ids.ts +44 -0
  33. package/src/types/logs.ts +331 -0
  34. package/src/types/merged/index.ts +5 -0
  35. package/src/types/merged/message.ts +552 -0
  36. package/src/types/message.ts +927 -186
  37. package/src/types/messageQueueTypes.ts +21 -0
  38. package/src/types/notebook.ts +72 -0
  39. package/src/types/permissions.ts +447 -0
  40. package/src/types/plugin.ts +363 -0
  41. package/src/types/statusLine.ts +15 -0
  42. package/src/types/textInputTypes.ts +387 -0
  43. package/src/types/tools.ts +149 -0
  44. package/src/types/utils.ts +20 -0
  45. package/src/utils/advisor.ts +12 -0
  46. package/src/utils/api.ts +29 -0
  47. package/src/utils/array.ts +7 -0
  48. package/src/utils/attachments.ts +60 -0
  49. package/src/utils/auth.ts +3 -0
  50. package/src/utils/claudeInChrome/chromeNativeHost.ts +15 -0
  51. package/src/utils/claudeInChrome/common.ts +12 -0
  52. package/src/utils/claudeInChrome/mcpServer.ts +15 -0
  53. package/src/utils/computerUse/common.ts +19 -0
  54. package/src/utils/computerUse/mcpServer.ts +15 -0
  55. package/src/utils/config.ts +35 -0
  56. package/src/utils/context.ts +19 -0
  57. package/src/utils/cwd.ts +3 -0
  58. package/src/utils/debug.ts +3 -0
  59. package/src/utils/earlyInput.ts +7 -0
  60. package/src/utils/effort.ts +13 -0
  61. package/src/utils/embeddedTools.ts +12 -0
  62. package/src/utils/envUtils.ts +3 -0
  63. package/src/utils/errors.ts +3 -0
  64. package/src/utils/execFileNoThrow.ts +24 -0
  65. package/src/utils/feature-flags.ts +112 -0
  66. package/src/utils/file.ts +3 -0
  67. package/src/utils/fileHistory.ts +17 -0
  68. package/src/utils/fingerprint.ts +7 -0
  69. package/src/utils/format.ts +75 -305
  70. package/src/utils/frontmatterParser.ts +33 -0
  71. package/src/utils/fsOperations.ts +31 -0
  72. package/src/utils/fullscreen.ts +40 -350
  73. package/src/utils/git.ts +15 -0
  74. package/src/utils/imageResizer.ts +30 -0
  75. package/src/utils/lazySchema.ts +9 -0
  76. package/src/utils/log.ts +3 -0
  77. package/src/utils/markdownConfigLoader.ts +12 -0
  78. package/src/utils/messages.ts +13 -0
  79. package/src/utils/migration.ts +137 -0
  80. package/src/utils/model/providers.ts +15 -0
  81. package/src/utils/path.ts +3 -0
  82. package/src/utils/permissions/PermissionResult.ts +14 -0
  83. package/src/utils/permissions/autoModeState.ts +12 -0
  84. package/src/utils/permissions/filesystem.ts +12 -0
  85. package/src/utils/plugins/loadPluginOutputStyles.ts +12 -0
  86. package/src/utils/plugins/schemas.ts +25 -0
  87. package/src/utils/process.ts +16 -0
  88. package/src/utils/sandbox/sandbox-adapter.ts +19 -0
  89. package/src/utils/sessionStorage.ts +238 -472
  90. package/src/utils/settings/constants.ts +10 -0
  91. package/src/utils/settings/settings.ts +19 -0
  92. package/src/utils/settings/types.ts +18 -0
  93. package/src/utils/shell/shellToolUtils.ts +9 -0
  94. package/src/utils/sinks.ts +11 -0
  95. package/src/utils/sleep.ts +7 -0
  96. package/src/utils/sliceAnsi.ts +7 -0
  97. package/src/utils/slowOperations.ts +3 -0
  98. package/src/utils/startupProfiler.ts +11 -0
  99. package/src/utils/stringUtils.ts +106 -0
  100. package/src/utils/systemPromptType.ts +9 -0
  101. package/src/utils/teleport/api.ts +15 -0
  102. package/src/utils/textHighlighting.ts +16 -0
  103. package/src/utils/theme.ts +17 -0
  104. package/src/utils/thinking.ts +58 -0
  105. package/src/utils/tokens.ts +11 -0
  106. package/src/utils/toolResultStorage.ts +17 -0
  107. package/src/utils/worktreeModeEnabled.ts +7 -0
  108. package/WORKSPACE_INTEGRATION.md +0 -290
  109. package/chat-sessions/sessions-index.json +0 -98
  110. package/package.json.original +0 -31
  111. package/package.json.publish +0 -47
  112. package/src/bootstrap/state.d.ts +0 -169
  113. package/src/bootstrap/state.js +0 -261
  114. package/src/context/pack-builder.d.ts +0 -24
  115. package/src/context/pack-builder.js +0 -281
  116. package/src/hooks/useExitOnCtrlCD.d.ts +0 -86
  117. package/src/hooks/useExitOnCtrlCD.js +0 -130
  118. package/src/hooks/useKeybinding.d.ts +0 -89
  119. package/src/hooks/useKeybinding.js +0 -163
  120. package/src/hooks/useTerminalSize.d.ts +0 -41
  121. package/src/hooks/useTerminalSize.js +0 -90
  122. package/src/index.d.ts +0 -23
  123. package/src/index.js +0 -24
  124. package/src/runtime/brand/brand.d.ts +0 -488
  125. package/src/runtime/brand/brand.js +0 -464
  126. package/src/runtime/brand/brand.ts +0 -667
  127. package/src/runtime/services/tokenEstimation.d.ts +0 -187
  128. package/src/runtime/services/tokenEstimation.js +0 -423
  129. package/src/runtime/services/tokenEstimation.ts +0 -547
  130. package/src/runtime/tools/Tool.d.ts +0 -239
  131. package/src/runtime/tools/Tool.js +0 -285
  132. package/src/runtime/tools/Tool.ts +0 -524
  133. package/src/scheduler/TaskScheduler.d.ts +0 -98
  134. package/src/scheduler/TaskScheduler.js +0 -201
  135. package/src/scheduler/TaskScheduler.ts +0 -259
  136. package/src/state/AppStateStore.d.ts +0 -347
  137. package/src/state/AppStateStore.js +0 -439
  138. package/src/state/AppStateStore.ts +0 -658
  139. package/src/state/WorkspaceStateStore.d.ts +0 -43
  140. package/src/state/WorkspaceStateStore.js +0 -224
  141. package/src/state/WorkspaceStateStore.ts +0 -297
  142. package/src/types/message.d.ts +0 -190
  143. package/src/types/message.js +0 -77
  144. package/src/utils/format.d.ts +0 -126
  145. package/src/utils/format.js +0 -230
  146. package/src/utils/fullscreen.d.ts +0 -161
  147. package/src/utils/fullscreen.js +0 -277
  148. package/src/utils/sessionStorage.d.ts +0 -210
  149. package/src/utils/sessionStorage.js +0 -435
  150. package/src/watcher/WorkspaceWatcher.d.ts +0 -70
  151. package/src/watcher/WorkspaceWatcher.js +0 -191
  152. package/src/watcher/WorkspaceWatcher.ts +0 -251
  153. package/src/workspace/loader.d.ts +0 -30
  154. package/src/workspace/loader.js +0 -117
  155. package/src/workspace/types.d.ts +0 -91
  156. package/src/workspace/types.js +0 -7
  157. package/threads/thread_1775361175022.json +0 -9
  158. package/tsconfig.json +0 -14
@@ -1,190 +0,0 @@
1
- /**
2
- * @fileoverview Message types for gizzi-code integration
3
- * @module types/message
4
- *
5
- * Defines core message interfaces and types used across the application
6
- * for chat, notifications, and system communications.
7
- */
8
- /**
9
- * Represents the possible roles a message can have in a conversation
10
- * @typedef {'user' | 'assistant' | 'system'} MessageRole
11
- */
12
- export type MessageRole = 'user' | 'assistant' | 'system';
13
- /**
14
- * Valid message role values for runtime validation
15
- * @constant {MessageRole[]}
16
- */
17
- export declare const MESSAGE_ROLES: readonly MessageRole[];
18
- /**
19
- * Supported MIME types for message attachments
20
- * @typedef {string} AttachmentMimeType
21
- */
22
- export type AttachmentMimeType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | 'image/svg+xml' | 'text/plain' | 'text/markdown' | 'text/html' | 'application/json' | 'application/pdf' | 'application/zip' | 'audio/mpeg' | 'audio/wav' | 'video/mp4' | 'video/webm' | string;
23
- /**
24
- * Attachment metadata and content structure
25
- * @interface Attachment
26
- */
27
- export interface Attachment {
28
- /** Unique identifier for the attachment */
29
- readonly id: string;
30
- /** Original filename */
31
- readonly name: string;
32
- /** MIME type of the attachment */
33
- readonly mimeType: AttachmentMimeType;
34
- /** File size in bytes */
35
- readonly size: number;
36
- /** Data URL or storage reference for the attachment content */
37
- readonly url: string;
38
- /** Optional preview/thumbnail URL for image/video attachments */
39
- readonly previewUrl?: string;
40
- /** Optional caption or description */
41
- readonly caption?: string;
42
- /** Timestamp when the attachment was created */
43
- readonly createdAt: Date;
44
- /** Optional metadata for specific attachment types */
45
- readonly metadata?: Readonly<Record<string, unknown>>;
46
- }
47
- /**
48
- * Message status indicators
49
- * @typedef {'pending' | 'sent' | 'delivered' | 'read' | 'error'} MessageStatus
50
- */
51
- export type MessageStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'error';
52
- /**
53
- * Core message structure for all communications
54
- * @interface Message
55
- */
56
- export interface Message {
57
- /** Unique message identifier */
58
- readonly id: string;
59
- /** Message role identifying the sender type */
60
- readonly role: MessageRole;
61
- /** Message content - can be text or structured data */
62
- readonly content: string;
63
- /** Optional timestamp when the message was created */
64
- readonly timestamp?: Date;
65
- /** Optional array of file attachments */
66
- readonly attachments?: readonly Attachment[];
67
- /** Current status of the message delivery */
68
- readonly status?: MessageStatus;
69
- /** Optional metadata for extended message properties */
70
- readonly metadata?: Readonly<Record<string, unknown>>;
71
- /** Optional ID of the message this is replying to */
72
- readonly replyTo?: string;
73
- /** Optional edit history for tracking modifications */
74
- readonly edits?: ReadonlyArray<{
75
- readonly content: string;
76
- readonly timestamp: Date;
77
- }>;
78
- }
79
- /**
80
- * System-specific message with additional metadata
81
- * @interface SystemMessage
82
- * @extends Message
83
- */
84
- export interface SystemMessage extends Message {
85
- readonly role: 'system';
86
- /** System message type categorization */
87
- readonly systemType: 'notification' | 'error' | 'warning' | 'info' | 'command';
88
- /** Optional action button or link */
89
- readonly action?: {
90
- readonly label: string;
91
- readonly handler: string;
92
- readonly payload?: unknown;
93
- };
94
- }
95
- /**
96
- * User message with optional context
97
- * @interface UserMessage
98
- * @extends Message
99
- */
100
- export interface UserMessage extends Message {
101
- readonly role: 'user';
102
- /** Optional session or conversation context */
103
- readonly context?: Readonly<Record<string, unknown>>;
104
- }
105
- /**
106
- * Assistant/AI response message with optional thinking/reasoning
107
- * @interface AssistantMessage
108
- * @extends Message
109
- */
110
- export interface AssistantMessage extends Message {
111
- readonly role: 'assistant';
112
- /** Optional thinking/reasoning process for the response */
113
- readonly reasoning?: string;
114
- /** Token usage statistics for the response */
115
- readonly tokenUsage?: {
116
- readonly prompt: number;
117
- readonly completion: number;
118
- readonly total: number;
119
- };
120
- /** Model identifier that generated the response */
121
- readonly model?: string;
122
- }
123
- /**
124
- * Union type for all message variants
125
- * @typedef {UserMessage | AssistantMessage | SystemMessage} TypedMessage
126
- */
127
- export type TypedMessage = UserMessage | AssistantMessage | SystemMessage;
128
- /**
129
- * Message thread/conversation structure
130
- * @interface MessageThread
131
- */
132
- export interface MessageThread {
133
- /** Unique thread identifier */
134
- readonly id: string;
135
- /** Thread title or subject */
136
- readonly title?: string;
137
- /** Array of messages in the thread */
138
- readonly messages: readonly TypedMessage[];
139
- /** Thread creation timestamp */
140
- readonly createdAt: Date;
141
- /** Last activity timestamp */
142
- readonly updatedAt: Date;
143
- /** Optional metadata for the thread */
144
- readonly metadata?: Readonly<Record<string, unknown>>;
145
- }
146
- /**
147
- * Type guard to check if a message is from a user
148
- * @param {Message} message - The message to check
149
- * @returns {boolean} True if the message is from a user
150
- */
151
- export declare function isUserMessage(message: Message): message is UserMessage;
152
- /**
153
- * Type guard to check if a message is from the assistant
154
- * @param {Message} message - The message to check
155
- * @returns {boolean} True if the message is from the assistant
156
- */
157
- export declare function isAssistantMessage(message: Message): message is AssistantMessage;
158
- /**
159
- * Type guard to check if a message is a system message
160
- * @param {Message} message - The message to check
161
- * @returns {boolean} True if the message is a system message
162
- */
163
- export declare function isSystemMessage(message: Message): message is SystemMessage;
164
- /**
165
- * Type guard to check if a value is a valid MessageRole
166
- * @param {unknown} value - The value to check
167
- * @returns {boolean} True if the value is a valid MessageRole
168
- */
169
- export declare function isMessageRole(value: unknown): value is MessageRole;
170
- /**
171
- * Creates a new message with proper defaults
172
- * @param {Object} params - Message creation parameters
173
- * @returns {Message} A new message object
174
- */
175
- export declare function createMessage(params: {
176
- role: MessageRole;
177
- content: string;
178
- attachments?: Attachment[];
179
- metadata?: Record<string, unknown>;
180
- replyTo?: string;
181
- }): Message;
182
- declare const _default: {
183
- MESSAGE_ROLES: readonly MessageRole[];
184
- isUserMessage: typeof isUserMessage;
185
- isAssistantMessage: typeof isAssistantMessage;
186
- isSystemMessage: typeof isSystemMessage;
187
- isMessageRole: typeof isMessageRole;
188
- createMessage: typeof createMessage;
189
- };
190
- export default _default;
@@ -1,77 +0,0 @@
1
- /**
2
- * @fileoverview Message types for gizzi-code integration
3
- * @module types/message
4
- *
5
- * Defines core message interfaces and types used across the application
6
- * for chat, notifications, and system communications.
7
- */
8
- /**
9
- * Valid message role values for runtime validation
10
- * @constant {MessageRole[]}
11
- */
12
- export const MESSAGE_ROLES = ['user', 'assistant', 'system'];
13
- /**
14
- * Type guard to check if a message is from a user
15
- * @param {Message} message - The message to check
16
- * @returns {boolean} True if the message is from a user
17
- */
18
- export function isUserMessage(message) {
19
- return message.role === 'user';
20
- }
21
- /**
22
- * Type guard to check if a message is from the assistant
23
- * @param {Message} message - The message to check
24
- * @returns {boolean} True if the message is from the assistant
25
- */
26
- export function isAssistantMessage(message) {
27
- return message.role === 'assistant';
28
- }
29
- /**
30
- * Type guard to check if a message is a system message
31
- * @param {Message} message - The message to check
32
- * @returns {boolean} True if the message is a system message
33
- */
34
- export function isSystemMessage(message) {
35
- return message.role === 'system';
36
- }
37
- /**
38
- * Type guard to check if a value is a valid MessageRole
39
- * @param {unknown} value - The value to check
40
- * @returns {boolean} True if the value is a valid MessageRole
41
- */
42
- export function isMessageRole(value) {
43
- return typeof value === 'string' && MESSAGE_ROLES.includes(value);
44
- }
45
- /**
46
- * Creates a new message with proper defaults
47
- * @param {Object} params - Message creation parameters
48
- * @returns {Message} A new message object
49
- */
50
- export function createMessage(params) {
51
- return {
52
- id: generateMessageId(),
53
- role: params.role,
54
- content: params.content,
55
- timestamp: new Date(),
56
- status: 'pending',
57
- ...(params.attachments && { attachments: params.attachments }),
58
- ...(params.metadata && { metadata: params.metadata }),
59
- ...(params.replyTo && { replyTo: params.replyTo }),
60
- };
61
- }
62
- /**
63
- * Generates a unique message ID
64
- * @returns {string} A unique identifier
65
- */
66
- function generateMessageId() {
67
- return `msg_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
68
- }
69
- // Default export for convenient importing
70
- export default {
71
- MESSAGE_ROLES,
72
- isUserMessage,
73
- isAssistantMessage,
74
- isSystemMessage,
75
- isMessageRole,
76
- createMessage,
77
- };
@@ -1,126 +0,0 @@
1
- /**
2
- * @fileoverview Format utilities for gizzi-code integration
3
- * @module utils/format
4
- *
5
- * Provides formatting utilities for durations, byte sizes, and numbers.
6
- * These functions are commonly used in CLI output and display components.
7
- */
8
- /**
9
- * Number format options
10
- * @interface NumberFormatOptions
11
- */
12
- export interface NumberFormatOptions {
13
- /** Minimum number of decimal places */
14
- readonly minimumFractionDigits?: number;
15
- /** Maximum number of decimal places */
16
- readonly maximumFractionDigits?: number;
17
- /** Use thousands separator */
18
- readonly useGrouping?: boolean;
19
- /** Locale for formatting (default: 'en-US') */
20
- readonly locale?: string;
21
- }
22
- /**
23
- * Duration format options
24
- * @interface DurationFormatOptions
25
- */
26
- export interface DurationFormatOptions {
27
- /** Format style (default: 'auto') */
28
- readonly style?: 'short' | 'long' | 'narrow' | 'auto';
29
- /** Maximum number of units to display (default: 2) */
30
- readonly maxUnits?: number;
31
- /** Include milliseconds in output */
32
- readonly includeMs?: boolean;
33
- /** Round to nearest unit */
34
- readonly round?: boolean;
35
- }
36
- /**
37
- * Byte format options
38
- * @interface ByteFormatOptions
39
- */
40
- export interface ByteFormatOptions {
41
- /** Number of decimal places (default: 2) */
42
- readonly decimals?: number;
43
- /** Use binary units (KiB, MiB) instead of decimal (KB, MB) */
44
- readonly binary?: boolean;
45
- /** Include space between value and unit */
46
- readonly space?: boolean;
47
- }
48
- /**
49
- * Formats a duration in milliseconds to a human-readable string
50
- *
51
- * @param {number} ms - Duration in milliseconds
52
- * @param {DurationFormatOptions} [options] - Format options
53
- * @returns {string} Formatted duration string
54
- * @example
55
- * ```typescript
56
- * formatDuration(5000); // "5s"
57
- * formatDuration(65000); // "1m 5s"
58
- * formatDuration(3600000); // "1h"
59
- * formatDuration(90000, { style: 'long' }); // "1 minute 30 seconds"
60
- * ```
61
- */
62
- export declare function formatDuration(ms: number, options?: DurationFormatOptions): string;
63
- /**
64
- * Formats a byte size to a human-readable string
65
- *
66
- * @param {number} bytes - Size in bytes
67
- * @param {ByteFormatOptions} [options] - Format options
68
- * @returns {string} Formatted size string
69
- * @example
70
- * ```typescript
71
- * formatBytes(1024); // "1 KB"
72
- * formatBytes(1536); // "1.50 KB"
73
- * formatBytes(1048576); // "1 MB"
74
- * formatBytes(1024, { binary: true }); // "1 KiB"
75
- * ```
76
- */
77
- export declare function formatBytes(bytes: number, options?: ByteFormatOptions): string;
78
- /**
79
- * Formats a number with locale-aware formatting
80
- *
81
- * @param {number} num - Number to format
82
- * @param {NumberFormatOptions} [options] - Format options
83
- * @returns {string} Formatted number string
84
- * @example
85
- * ```typescript
86
- * formatNumber(1234567); // "1,234,567"
87
- * formatNumber(1234.5678, { maximumFractionDigits: 2 }); // "1,234.57"
88
- * formatNumber(0.001234, { minimumFractionDigits: 6 }); // "0.001234"
89
- * ```
90
- */
91
- export declare function formatNumber(num: number, options?: NumberFormatOptions): string;
92
- /**
93
- * Formats a number as a percentage
94
- *
95
- * @param {number} value - Value to format (0.5 = 50%)
96
- * @param {number} [decimals=1] - Number of decimal places
97
- * @returns {string} Formatted percentage string
98
- * @example
99
- * ```typescript
100
- * formatPercentage(0.5); // "50%"
101
- * formatPercentage(0.1234, 2); // "12.34%"
102
- * ```
103
- */
104
- export declare function formatPercentage(value: number, decimals?: number): string;
105
- /**
106
- * Formats a number as compact notation (1K, 1M, etc.)
107
- *
108
- * @param {number} num - Number to format
109
- * @param {number} [decimals=1] - Number of decimal places
110
- * @returns {string} Compact formatted string
111
- * @example
112
- * ```typescript
113
- * formatCompact(1234); // "1.2K"
114
- * formatCompact(1000000); // "1M"
115
- * formatCompact(1234567890); // "1.2B"
116
- * ```
117
- */
118
- export declare function formatCompact(num: number, decimals?: number): string;
119
- declare const _default: {
120
- formatDuration: typeof formatDuration;
121
- formatBytes: typeof formatBytes;
122
- formatNumber: typeof formatNumber;
123
- formatPercentage: typeof formatPercentage;
124
- formatCompact: typeof formatCompact;
125
- };
126
- export default _default;
@@ -1,230 +0,0 @@
1
- /**
2
- * @fileoverview Format utilities for gizzi-code integration
3
- * @module utils/format
4
- *
5
- * Provides formatting utilities for durations, byte sizes, and numbers.
6
- * These functions are commonly used in CLI output and display components.
7
- */
8
- /**
9
- * Time unit definitions for duration formatting
10
- * @constant {Record<string, number>}
11
- */
12
- const TIME_UNITS = {
13
- millisecond: 1,
14
- second: 1000,
15
- minute: 60 * 1000,
16
- hour: 60 * 60 * 1000,
17
- day: 24 * 60 * 60 * 1000,
18
- week: 7 * 24 * 60 * 60 * 1000,
19
- month: 30 * 24 * 60 * 60 * 1000,
20
- year: 365 * 24 * 60 * 60 * 1000,
21
- };
22
- /**
23
- * Byte unit definitions for size formatting
24
- * @constant {string[]}
25
- */
26
- const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
27
- /**
28
- * Formats a duration in milliseconds to a human-readable string
29
- *
30
- * @param {number} ms - Duration in milliseconds
31
- * @param {DurationFormatOptions} [options] - Format options
32
- * @returns {string} Formatted duration string
33
- * @example
34
- * ```typescript
35
- * formatDuration(5000); // "5s"
36
- * formatDuration(65000); // "1m 5s"
37
- * formatDuration(3600000); // "1h"
38
- * formatDuration(90000, { style: 'long' }); // "1 minute 30 seconds"
39
- * ```
40
- */
41
- export function formatDuration(ms, options = {}) {
42
- const { style = 'auto', maxUnits = 2, includeMs = false, round = false, } = options;
43
- // Handle edge cases
44
- if (!Number.isFinite(ms) || ms < 0) {
45
- return style === 'long' ? 'unknown duration' : '--';
46
- }
47
- if (ms === 0) {
48
- return style === 'long' ? '0 seconds' : '0s';
49
- }
50
- // Round if requested
51
- const duration = round ? Math.round(ms) : ms;
52
- // Determine appropriate units
53
- const units = [
54
- { value: TIME_UNITS.year, short: 'y', long: 'year' },
55
- { value: TIME_UNITS.month, short: 'mo', long: 'month' },
56
- { value: TIME_UNITS.week, short: 'w', long: 'week' },
57
- { value: TIME_UNITS.day, short: 'd', long: 'day' },
58
- { value: TIME_UNITS.hour, short: 'h', long: 'hour' },
59
- { value: TIME_UNITS.minute, short: 'm', long: 'minute' },
60
- { value: TIME_UNITS.second, short: 's', long: 'second' },
61
- ];
62
- // Add milliseconds if requested
63
- if (includeMs || duration < TIME_UNITS.second) {
64
- units.push({ value: TIME_UNITS.millisecond, short: 'ms', long: 'millisecond' });
65
- }
66
- const parts = [];
67
- let remaining = Math.abs(duration);
68
- for (const unit of units) {
69
- if (remaining >= unit.value) {
70
- const count = Math.floor(remaining / unit.value);
71
- remaining %= unit.value;
72
- const useLong = style === 'long';
73
- const unitStr = useLong
74
- ? `${unit.long}${count !== 1 ? 's' : ''}`
75
- : unit.short;
76
- parts.push(useLong ? `${count} ${unitStr}` : `${count}${unitStr}`);
77
- if (parts.length >= maxUnits) {
78
- break;
79
- }
80
- }
81
- }
82
- if (parts.length === 0) {
83
- return style === 'long' ? '0 seconds' : '0s';
84
- }
85
- return parts.join(style === 'long' ? ' ' : ' ');
86
- }
87
- /**
88
- * Formats a byte size to a human-readable string
89
- *
90
- * @param {number} bytes - Size in bytes
91
- * @param {ByteFormatOptions} [options] - Format options
92
- * @returns {string} Formatted size string
93
- * @example
94
- * ```typescript
95
- * formatBytes(1024); // "1 KB"
96
- * formatBytes(1536); // "1.50 KB"
97
- * formatBytes(1048576); // "1 MB"
98
- * formatBytes(1024, { binary: true }); // "1 KiB"
99
- * ```
100
- */
101
- export function formatBytes(bytes, options = {}) {
102
- const { decimals = 2, binary = false, space = true } = options;
103
- // Handle edge cases
104
- if (!Number.isFinite(bytes)) {
105
- return '0 B';
106
- }
107
- const absBytes = Math.abs(bytes);
108
- if (absBytes === 0) {
109
- return '0 B';
110
- }
111
- // Use 1024 for binary (KiB, MiB) or 1000 for decimal (KB, MB)
112
- const base = binary ? 1024 : 1000;
113
- const binarySuffix = binary ? 'i' : '';
114
- // Find appropriate unit
115
- const exponent = Math.min(Math.floor(Math.log(absBytes) / Math.log(base)), BYTE_UNITS.length - 1);
116
- const value = bytes / Math.pow(base, exponent);
117
- const unit = BYTE_UNITS[exponent] + (exponent > 0 ? binarySuffix : '');
118
- // Format with specified decimal places
119
- const formattedValue = value.toFixed(decimals);
120
- const trimmedValue = parseFloat(formattedValue).toString();
121
- return space ? `${trimmedValue} ${unit}` : `${trimmedValue}${unit}`;
122
- }
123
- /**
124
- * Formats a number with locale-aware formatting
125
- *
126
- * @param {number} num - Number to format
127
- * @param {NumberFormatOptions} [options] - Format options
128
- * @returns {string} Formatted number string
129
- * @example
130
- * ```typescript
131
- * formatNumber(1234567); // "1,234,567"
132
- * formatNumber(1234.5678, { maximumFractionDigits: 2 }); // "1,234.57"
133
- * formatNumber(0.001234, { minimumFractionDigits: 6 }); // "0.001234"
134
- * ```
135
- */
136
- export function formatNumber(num, options = {}) {
137
- const { minimumFractionDigits, maximumFractionDigits = 2, useGrouping = true, locale = 'en-US', } = options;
138
- // Handle edge cases
139
- if (!Number.isFinite(num)) {
140
- if (Number.isNaN(num))
141
- return 'NaN';
142
- return num > 0 ? '∞' : '-∞';
143
- }
144
- try {
145
- return new Intl.NumberFormat(locale, {
146
- minimumFractionDigits,
147
- maximumFractionDigits,
148
- useGrouping,
149
- }).format(num);
150
- }
151
- catch {
152
- // Fallback for environments without Intl support
153
- const absNum = Math.abs(num);
154
- const sign = num < 0 ? '-' : '';
155
- // Handle integer part with grouping
156
- const integerPart = Math.floor(absNum);
157
- const fractionPart = absNum - integerPart;
158
- let result = useGrouping
159
- ? integerPart.toLocaleString(locale)
160
- : integerPart.toString();
161
- // Add fraction part if needed
162
- const minDecimals = minimumFractionDigits ?? 0;
163
- const maxDecimals = maximumFractionDigits ?? 2;
164
- if (fractionPart > 0 || minDecimals > 0) {
165
- const fractionStr = fractionPart
166
- .toFixed(maxDecimals)
167
- .slice(2)
168
- .padEnd(minDecimals, '0');
169
- // Trim trailing zeros if no minimum required
170
- const trimmedFraction = minDecimals === 0
171
- ? fractionStr.replace(/0+$/, '')
172
- : fractionStr;
173
- if (trimmedFraction.length > 0) {
174
- result += '.' + trimmedFraction;
175
- }
176
- }
177
- return sign + result;
178
- }
179
- }
180
- /**
181
- * Formats a number as a percentage
182
- *
183
- * @param {number} value - Value to format (0.5 = 50%)
184
- * @param {number} [decimals=1] - Number of decimal places
185
- * @returns {string} Formatted percentage string
186
- * @example
187
- * ```typescript
188
- * formatPercentage(0.5); // "50%"
189
- * formatPercentage(0.1234, 2); // "12.34%"
190
- * ```
191
- */
192
- export function formatPercentage(value, decimals = 1) {
193
- if (!Number.isFinite(value)) {
194
- return '--%';
195
- }
196
- return `${(value * 100).toFixed(decimals)}%`;
197
- }
198
- /**
199
- * Formats a number as compact notation (1K, 1M, etc.)
200
- *
201
- * @param {number} num - Number to format
202
- * @param {number} [decimals=1] - Number of decimal places
203
- * @returns {string} Compact formatted string
204
- * @example
205
- * ```typescript
206
- * formatCompact(1234); // "1.2K"
207
- * formatCompact(1000000); // "1M"
208
- * formatCompact(1234567890); // "1.2B"
209
- * ```
210
- */
211
- export function formatCompact(num, decimals = 1) {
212
- if (!Number.isFinite(num) || num === 0) {
213
- return '0';
214
- }
215
- const absNum = Math.abs(num);
216
- const sign = num < 0 ? '-' : '';
217
- const units = ['', 'K', 'M', 'B', 'T'];
218
- const unitIndex = Math.min(Math.floor(Math.log10(absNum) / 3), units.length - 1);
219
- const value = absNum / Math.pow(1000, unitIndex);
220
- const formatted = value.toFixed(decimals).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1');
221
- return `${sign}${formatted}${units[unitIndex]}`;
222
- }
223
- // Default export
224
- export default {
225
- formatDuration,
226
- formatBytes,
227
- formatNumber,
228
- formatPercentage,
229
- formatCompact,
230
- };