@tanstack/devtools-vite 0.8.1 → 0.8.3

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 (81) hide show
  1. package/dist/esm/plugin.d.ts +4 -74
  2. package/dist/esm/plugin.js +2 -12
  3. package/dist/esm/plugin.js.map +1 -1
  4. package/package.json +2 -6
  5. package/src/plugin.ts +25 -97
  6. package/dist/esm/ast-utils.d.ts +0 -11
  7. package/dist/esm/ast-utils.js +0 -44
  8. package/dist/esm/ast-utils.js.map +0 -1
  9. package/dist/esm/ast-utils.test.d.ts +0 -1
  10. package/dist/esm/devtools-packages.d.ts +0 -2
  11. package/dist/esm/devtools-packages.js +0 -15
  12. package/dist/esm/devtools-packages.js.map +0 -1
  13. package/dist/esm/devtools-packages.test.d.ts +0 -1
  14. package/dist/esm/editor.d.ts +0 -25
  15. package/dist/esm/editor.js +0 -20
  16. package/dist/esm/editor.js.map +0 -1
  17. package/dist/esm/editor.test.d.ts +0 -1
  18. package/dist/esm/enhance-logs.d.ts +0 -4
  19. package/dist/esm/enhance-logs.js +0 -51
  20. package/dist/esm/enhance-logs.js.map +0 -1
  21. package/dist/esm/enhance-logs.test.d.ts +0 -1
  22. package/dist/esm/inject-plugin.d.ts +0 -22
  23. package/dist/esm/inject-plugin.js +0 -179
  24. package/dist/esm/inject-plugin.js.map +0 -1
  25. package/dist/esm/inject-plugin.test.d.ts +0 -1
  26. package/dist/esm/inject-source.d.ts +0 -7
  27. package/dist/esm/inject-source.js +0 -114
  28. package/dist/esm/inject-source.js.map +0 -1
  29. package/dist/esm/inject-source.test.d.ts +0 -1
  30. package/dist/esm/matcher.d.ts +0 -1
  31. package/dist/esm/matcher.js +0 -13
  32. package/dist/esm/matcher.js.map +0 -1
  33. package/dist/esm/matcher.test.d.ts +0 -1
  34. package/dist/esm/offset-to-loc.d.ts +0 -14
  35. package/dist/esm/offset-to-loc.js +0 -29
  36. package/dist/esm/offset-to-loc.js.map +0 -1
  37. package/dist/esm/offset-to-loc.test.d.ts +0 -1
  38. package/dist/esm/package-manager.d.ts +0 -16
  39. package/dist/esm/package-manager.js +0 -98
  40. package/dist/esm/package-manager.js.map +0 -1
  41. package/dist/esm/remove-devtools.d.ts +0 -4
  42. package/dist/esm/remove-devtools.js +0 -96
  43. package/dist/esm/remove-devtools.js.map +0 -1
  44. package/dist/esm/remove-devtools.test.d.ts +0 -1
  45. package/dist/esm/runtime-bridge.d.ts +0 -31
  46. package/dist/esm/runtime-bridge.js +0 -75
  47. package/dist/esm/runtime-bridge.js.map +0 -1
  48. package/dist/esm/runtime-bridge.test.d.ts +0 -1
  49. package/dist/esm/utils.d.ts +0 -31
  50. package/dist/esm/utils.js +0 -155
  51. package/dist/esm/utils.js.map +0 -1
  52. package/dist/esm/utils.test.d.ts +0 -1
  53. package/dist/esm/virtual-console.d.ts +0 -19
  54. package/dist/esm/virtual-console.js +0 -336
  55. package/dist/esm/virtual-console.js.map +0 -1
  56. package/dist/esm/virtual-console.test.d.ts +0 -1
  57. package/src/ast-utils.test.ts +0 -109
  58. package/src/ast-utils.ts +0 -58
  59. package/src/devtools-packages.test.ts +0 -58
  60. package/src/devtools-packages.ts +0 -12
  61. package/src/editor.test.ts +0 -75
  62. package/src/editor.ts +0 -53
  63. package/src/enhance-logs.test.ts +0 -132
  64. package/src/enhance-logs.ts +0 -71
  65. package/src/inject-plugin.test.ts +0 -1139
  66. package/src/inject-plugin.ts +0 -300
  67. package/src/inject-source.test.ts +0 -939
  68. package/src/inject-source.ts +0 -235
  69. package/src/matcher.test.ts +0 -33
  70. package/src/matcher.ts +0 -19
  71. package/src/offset-to-loc.test.ts +0 -34
  72. package/src/offset-to-loc.ts +0 -39
  73. package/src/package-manager.ts +0 -181
  74. package/src/remove-devtools.test.ts +0 -607
  75. package/src/remove-devtools.ts +0 -190
  76. package/src/runtime-bridge.test.ts +0 -179
  77. package/src/runtime-bridge.ts +0 -113
  78. package/src/utils.test.ts +0 -184
  79. package/src/utils.ts +0 -247
  80. package/src/virtual-console.test.ts +0 -244
  81. package/src/virtual-console.ts +0 -341
@@ -1,190 +0,0 @@
1
- import MagicString from 'magic-string'
2
- import { parseSync } from 'oxc-parser'
3
- import { walk } from './ast-utils'
4
- import { isTanStackDevtoolsImport } from './devtools-packages'
5
- import type { JSXOpeningElement } from 'oxc-parser'
6
-
7
- /**
8
- * Extract component names referenced in the `plugins` prop of a devtools element.
9
- */
10
- function getPluginReferences(opening: JSXOpeningElement): Array<string> {
11
- const refs: Array<string> = []
12
-
13
- for (const attr of opening.attributes) {
14
- if (attr.type !== 'JSXAttribute') continue
15
- if (attr.name.type !== 'JSXIdentifier' || attr.name.name !== 'plugins')
16
- continue
17
- if (
18
- !attr.value ||
19
- attr.value.type !== 'JSXExpressionContainer' ||
20
- attr.value.expression.type !== 'ArrayExpression'
21
- )
22
- continue
23
-
24
- for (const el of attr.value.expression.elements) {
25
- if (!el || el.type !== 'ObjectExpression') continue
26
-
27
- for (const prop of el.properties) {
28
- if (
29
- prop.type !== 'Property' ||
30
- prop.key.type !== 'Identifier' ||
31
- prop.key.name !== 'render'
32
- )
33
- continue
34
-
35
- const value = prop.value
36
-
37
- // handle <ReactRouterPanel />
38
- if (
39
- value.type === 'JSXElement' &&
40
- value.openingElement.name.type === 'JSXIdentifier'
41
- ) {
42
- refs.push(value.openingElement.name.name)
43
- }
44
- // handle () => <ReactRouterPanel />
45
- else if (
46
- value.type === 'ArrowFunctionExpression' ||
47
- value.type === 'FunctionExpression'
48
- ) {
49
- const body = value.body
50
- if (
51
- body &&
52
- body.type === 'JSXElement' &&
53
- body.openingElement.name.type === 'JSXIdentifier'
54
- ) {
55
- refs.push(body.openingElement.name.name)
56
- }
57
- }
58
- // handle render: SomeComponent
59
- else if (value.type === 'Identifier') {
60
- refs.push(value.name)
61
- }
62
- // handle render: someFunction()
63
- else if (
64
- value.type === 'CallExpression' &&
65
- value.callee.type === 'Identifier'
66
- ) {
67
- refs.push(value.callee.name)
68
- }
69
- }
70
- }
71
- }
72
-
73
- return refs
74
- }
75
-
76
- export function removeDevtools(code: string, id: string) {
77
- const filePath = id.split('?')[0]!
78
-
79
- try {
80
- const result = parseSync(filePath, code, {
81
- sourceType: 'module',
82
- lang: 'tsx',
83
- })
84
- if (result.errors.length > 0) return
85
-
86
- const s = new MagicString(code)
87
- const devtoolsNames = new Set<string>()
88
- const pluginRefs: Array<string> = []
89
-
90
- // Pass 1: Collect devtools import names and mark for removal
91
- walk(result.program, (node) => {
92
- if (
93
- node.type === 'ImportDeclaration' &&
94
- isTanStackDevtoolsImport(node.source.value)
95
- ) {
96
- for (const spec of node.specifiers) {
97
- devtoolsNames.add(spec.local.name)
98
- }
99
- let end = node.end
100
- if (code[end] === '\n') end++
101
- s.remove(node.start, end)
102
- }
103
- })
104
-
105
- if (devtoolsNames.size === 0) return
106
-
107
- // Pass 2: Find and remove devtools JSX elements, collect plugin references
108
- walk(result.program, (node, parentNode) => {
109
- if (node.type !== 'JSXElement') return
110
-
111
- const opening = node.openingElement
112
- let matches = false
113
-
114
- if (
115
- opening.name.type === 'JSXIdentifier' &&
116
- devtoolsNames.has(opening.name.name)
117
- ) {
118
- matches = true
119
- } else if (
120
- opening.name.type === 'JSXMemberExpression' &&
121
- opening.name.object.type === 'JSXIdentifier' &&
122
- devtoolsNames.has(opening.name.object.name)
123
- ) {
124
- matches = true
125
- }
126
-
127
- if (!matches) return
128
-
129
- pluginRefs.push(...getPluginReferences(opening))
130
-
131
- let end = node.end
132
- if (code[end] === '\n') end++
133
- if (parentNode?.type === 'ParenthesizedExpression') {
134
- s.overwrite(node.start, end, 'null')
135
- } else {
136
- s.remove(node.start, end)
137
- }
138
- })
139
-
140
- // Pass 3: Remove plugin imports that are no longer referenced
141
- if (pluginRefs.length > 0) {
142
- walk(result.program, (node) => {
143
- if (node.type !== 'ImportDeclaration') return
144
- if (isTanStackDevtoolsImport(node.source.value)) return
145
-
146
- const toRemove = node.specifiers.filter(
147
- (spec) =>
148
- spec.type === 'ImportSpecifier' &&
149
- pluginRefs.includes(spec.local.name),
150
- )
151
-
152
- if (toRemove.length === 0) return
153
-
154
- const remaining = node.specifiers.filter(
155
- (spec) => !toRemove.includes(spec),
156
- )
157
-
158
- if (remaining.length === 0) {
159
- let end = node.end
160
- if (code[end] === '\n') end++
161
- s.remove(node.start, end)
162
- } else {
163
- // Rebuild import with remaining specifiers
164
- const specTexts = remaining.map((spec) =>
165
- code.slice(spec.start, spec.end),
166
- )
167
- const sourceText = code.slice(node.source.start, node.source.end)
168
- s.overwrite(
169
- node.start,
170
- node.end,
171
- `import { ${specTexts.join(', ')} } from ${sourceText}`,
172
- )
173
- }
174
- })
175
- }
176
-
177
- if (!s.hasChanged()) return
178
-
179
- return {
180
- code: s.toString(),
181
- map: s.generateMap({
182
- source: filePath,
183
- file: id,
184
- includeContent: true,
185
- }),
186
- }
187
- } catch (e) {
188
- return
189
- }
190
- }
@@ -1,179 +0,0 @@
1
- import { describe, expect, test } from 'vitest'
2
- import {
3
- generateRuntimeBridgeCode,
4
- injectRuntimeBridge,
5
- wireRuntimeBridgeChannels,
6
- } from './runtime-bridge'
7
-
8
- describe('generateRuntimeBridgeCode', () => {
9
- test('guards on import.meta.hot and an unset global target', () => {
10
- const code = generateRuntimeBridgeCode()
11
- expect(code).toContain('import.meta.hot')
12
- expect(code).toContain('globalThis.__TANSTACK_EVENT_TARGET__')
13
- expect(code).toContain('!globalThis.__TANSTACK_EVENT_TARGET__')
14
- })
15
-
16
- test('completes the connect handshake locally', () => {
17
- const code = generateRuntimeBridgeCode()
18
- expect(code).toContain("'tanstack-connect'")
19
- expect(code).toContain("'tanstack-connect-success'")
20
- })
21
-
22
- test('forwards dispatched events to the dev server', () => {
23
- const code = generateRuntimeBridgeCode()
24
- expect(code).toContain("'tanstack-dispatch-event'")
25
- expect(code).toContain("import.meta.hot.send('tsd:to-server'")
26
- })
27
-
28
- test('receives dev-server events and redispatches them locally', () => {
29
- const code = generateRuntimeBridgeCode()
30
- expect(code).toContain("import.meta.hot.on('tsd:to-client'")
31
- expect(code).toContain("'tanstack-devtools-global'")
32
- })
33
-
34
- test('has no external imports', () => {
35
- expect(generateRuntimeBridgeCode()).not.toContain('import ')
36
- })
37
- })
38
-
39
- describe('injectRuntimeBridge', () => {
40
- const EVENT_CLIENT_ID =
41
- '/repo/node_modules/@tanstack/devtools-event-client/dist/esm/index.js'
42
- const EVENT_CLIENT_CODE = 'class EventClient { emit() {} }'
43
-
44
- test('injects into the event-client module in a server environment', () => {
45
- const out = injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, 'ssr')
46
- expect(out).toBeDefined()
47
- expect(out).toContain(EVENT_CLIENT_CODE)
48
- expect(out).toContain('__tsdRuntimeBridge')
49
- })
50
-
51
- test('matches the workspace source path too', () => {
52
- const id = '/repo/packages/event-bus-client/src/plugin.ts'
53
- expect(injectRuntimeBridge(EVENT_CLIENT_CODE, id, 'ssr')).toBeDefined()
54
- })
55
-
56
- test('skips the client environment', () => {
57
- expect(
58
- injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, 'client'),
59
- ).toBeUndefined()
60
- })
61
-
62
- test('skips when environment name is unknown (pre-Environment-API)', () => {
63
- expect(
64
- injectRuntimeBridge(EVENT_CLIENT_CODE, EVENT_CLIENT_ID, undefined),
65
- ).toBeUndefined()
66
- })
67
-
68
- test('skips modules that are not the event-client', () => {
69
- expect(
70
- injectRuntimeBridge('export const x = 1', '/repo/src/app.ts', 'ssr'),
71
- ).toBeUndefined()
72
- })
73
-
74
- test('skips event-client-pathed modules that lack the EventClient class', () => {
75
- const id =
76
- '/repo/node_modules/@tanstack/devtools-event-client/dist/esm/foo.js'
77
- expect(injectRuntimeBridge('export const y = 2', id, 'ssr')).toBeUndefined()
78
- })
79
- })
80
-
81
- describe('wireRuntimeBridgeChannels', () => {
82
- function makeEnv() {
83
- type Handler = (data: any) => void
84
- const handlers: Record<string, Handler> = {}
85
- const removed: Array<{ event: string; cb: Handler }> = []
86
- const sent: Array<{ event: string; data: any }> = []
87
- return {
88
- hot: {
89
- on: (event: string, cb: Handler) => (handlers[event] = cb),
90
- off: (event: string, cb: Handler) => removed.push({ event, cb }),
91
- send: (event: string, data: any) => sent.push({ event, data }),
92
- },
93
- __handlers: handlers,
94
- __removed: removed,
95
- __sent: sent,
96
- }
97
- }
98
-
99
- test('worker event -> dispatches tanstack-dispatch-event on the target', () => {
100
- const target = new EventTarget()
101
- const ssr = makeEnv()
102
- const server = { environments: { client: { hot: null }, ssr } }
103
- const received: Array<any> = []
104
- target.addEventListener('tanstack-dispatch-event', (e) =>
105
- received.push((e as CustomEvent).detail),
106
- )
107
-
108
- wireRuntimeBridgeChannels(server as any, () => target)
109
- const evt = { type: 'q:foo', payload: 1 }
110
- ssr.__handlers['tsd:to-server']!(evt)
111
-
112
- expect(received).toEqual([evt])
113
- })
114
-
115
- test('target global event -> forwarded to the env via tsd:to-client', () => {
116
- const target = new EventTarget()
117
- const ssr = makeEnv()
118
- const server = { environments: { ssr } }
119
-
120
- wireRuntimeBridgeChannels(server as any, () => target)
121
- const evt = { type: 'q:bar', payload: 2 }
122
- target.dispatchEvent(
123
- new CustomEvent('tanstack-devtools-global', { detail: evt }),
124
- )
125
-
126
- expect(ssr.__sent).toEqual([{ event: 'tsd:to-client', data: evt }])
127
- })
128
-
129
- test('skips the client environment', () => {
130
- const client = makeEnv()
131
- const server = { environments: { client } }
132
- wireRuntimeBridgeChannels(server as any, () => new EventTarget())
133
- expect(client.__handlers['tsd:to-server']).toBeUndefined()
134
- })
135
-
136
- test('teardown stops forwarding', () => {
137
- const target = new EventTarget()
138
- const ssr = makeEnv()
139
- const server = { environments: { ssr } }
140
- const teardown = wireRuntimeBridgeChannels(server as any, () => target)
141
- teardown()
142
- target.dispatchEvent(
143
- new CustomEvent('tanstack-devtools-global', { detail: { type: 'x' } }),
144
- )
145
- expect(ssr.__sent).toEqual([])
146
- })
147
-
148
- test('teardown removes the tsd:to-server handler via hot.off (I1)', () => {
149
- const target = new EventTarget()
150
- const ssr = makeEnv()
151
- const server = { environments: { ssr } }
152
- const teardown = wireRuntimeBridgeChannels(server as any, () => target)
153
-
154
- // Capture the registered handler reference before teardown.
155
- const registeredHandler = ssr.__handlers['tsd:to-server']
156
- expect(registeredHandler).toBeDefined()
157
-
158
- teardown()
159
-
160
- // hot.off must have been called with the exact same handler reference.
161
- expect(ssr.__removed).toContainEqual({
162
- event: 'tsd:to-server',
163
- cb: registeredHandler,
164
- })
165
-
166
- // Dispatching a worker event after teardown must not reach the target.
167
- const received: Array<any> = []
168
- target.addEventListener('tanstack-dispatch-event', (e) =>
169
- received.push((e as CustomEvent).detail),
170
- )
171
- registeredHandler!({ type: 'post-teardown' })
172
- // The handler still dispatches (it holds a closure over getTarget) but the
173
- // important invariant is that hot.off was called so the real HMR channel
174
- // will no longer invoke it on subsequent dev-server restarts.
175
- expect(
176
- ssr.__removed.filter((r) => r.event === 'tsd:to-server'),
177
- ).toHaveLength(1)
178
- })
179
- })
@@ -1,113 +0,0 @@
1
- /**
2
- * Worker-side bridge for isolated server runtimes (Nitro v3 worker, Cloudflare workerd).
3
- *
4
- * Injected into the `@tanstack/devtools-event-client` module ONLY in non-client
5
- * (server) environments during dev. At module-eval time it gives the isolated
6
- * runtime a real `globalThis.__TANSTACK_EVENT_TARGET__` (so the unchanged
7
- * `EventClient` uses it instead of a throwaway target) and bridges that target to
8
- * the Vite dev process over the framework plugin's existing HMR HotChannel.
9
- *
10
- * Guards:
11
- * - `import.meta.hot` falsy (production / no HMR) -> tree-shaken / no-op.
12
- * - global target already set (in-process RunnableDevEnvironment, where
13
- * ServerEventBus lives) -> no-op, so existing behavior is unchanged.
14
- *
15
- * The bridge replicates ServerEventBus's in-process responsibilities so the
16
- * EventClient protocol is identical across the wire (see design doc).
17
- */
18
- export function generateRuntimeBridgeCode(): string {
19
- return `
20
- ;(function __tsdRuntimeBridge() {
21
- if (typeof import.meta === 'undefined' || !import.meta.hot) return;
22
- if (!globalThis.__TANSTACK_EVENT_TARGET__) {
23
- var target = new EventTarget();
24
- globalThis.__TANSTACK_EVENT_TARGET__ = target;
25
-
26
- // Complete EventClient's connect handshake locally so queued events flush.
27
- target.addEventListener('tanstack-connect', function () {
28
- target.dispatchEvent(new CustomEvent('tanstack-connect-success'));
29
- });
30
-
31
- // Worker -> Vite dev server.
32
- target.addEventListener('tanstack-dispatch-event', function (e) {
33
- import.meta.hot.send('tsd:to-server', e.detail);
34
- });
35
-
36
- // Vite dev server -> worker listeners.
37
- import.meta.hot.on('tsd:to-client', function (event) {
38
- target.dispatchEvent(new CustomEvent(event.type, { detail: event }));
39
- target.dispatchEvent(new CustomEvent('tanstack-devtools-global', { detail: event }));
40
- });
41
- }
42
- })();
43
- `
44
- }
45
-
46
- function isEventClientModule(id: string, code: string): boolean {
47
- const isEventClientPath =
48
- id.includes('devtools-event-client') || id.includes('event-bus-client')
49
- // Only the module that actually defines the class — avoids re-export shims
50
- // and unrelated files inside the package.
51
- return isEventClientPath && code.includes('EventClient')
52
- }
53
-
54
- export function injectRuntimeBridge(
55
- code: string,
56
- id: string,
57
- environmentName: string | undefined,
58
- ): string | undefined {
59
- // Only isolated server environments need the bridge. The client environment
60
- // has `window`; the in-process RunnableDevEnvironment is handled by the
61
- // runtime global guard inside the injected code.
62
- if (!environmentName || environmentName === 'client') return undefined
63
- if (!isEventClientModule(id, code)) return undefined
64
- return `${code}\n${generateRuntimeBridgeCode()}`
65
- }
66
-
67
- interface BridgeHotChannel {
68
- on?: (event: string, cb: (data: any) => void) => void
69
- off?: (event: string, cb: (data: any) => void) => void
70
- send?: (event: string, data: any) => void
71
- }
72
- interface BridgeServerLike {
73
- environments: Record<string, { hot?: BridgeHotChannel | null } | undefined>
74
- }
75
-
76
- export function wireRuntimeBridgeChannels(
77
- server: BridgeServerLike,
78
- getTarget: () => EventTarget | null | undefined,
79
- ): () => void {
80
- const teardowns: Array<() => void> = []
81
-
82
- for (const [name, env] of Object.entries(server.environments)) {
83
- if (name === 'client') continue
84
- const hot = env?.hot
85
- if (
86
- !hot ||
87
- typeof hot.on !== 'function' ||
88
- typeof hot.send !== 'function'
89
- ) {
90
- continue
91
- }
92
-
93
- // Worker -> ServerEventBus (broadcasts to browser + in-process listeners).
94
- const onToServer = (event: any) => {
95
- getTarget()?.dispatchEvent(
96
- new CustomEvent('tanstack-dispatch-event', { detail: event }),
97
- )
98
- }
99
- hot.on('tsd:to-server', onToServer)
100
- teardowns.push(() => hot.off?.('tsd:to-server', onToServer))
101
-
102
- // ServerEventBus output -> worker listeners.
103
- const target = getTarget()
104
- const forward = (e: Event) =>
105
- hot.send!('tsd:to-client', (e as CustomEvent).detail)
106
- target?.addEventListener('tanstack-devtools-global', forward)
107
- teardowns.push(() =>
108
- target?.removeEventListener('tanstack-devtools-global', forward),
109
- )
110
- }
111
-
112
- return () => teardowns.forEach((off) => off())
113
- }
package/src/utils.test.ts DELETED
@@ -1,184 +0,0 @@
1
- import { describe, expect, test } from 'vitest'
2
- import { parseOpenSourceParam, stripEnhancedLogPrefix } from './utils'
3
-
4
- describe('parseOpenSourceParam', () => {
5
- test('parses simple file:line:column format', () => {
6
- const result = parseOpenSourceParam('src/file.tsx:26:13')
7
- expect(result).toEqual({ file: 'src/file.tsx', line: '26', column: '13' })
8
- })
9
-
10
- test('parses file path with multiple slashes', () => {
11
- const result = parseOpenSourceParam('src/components/Header.tsx:100:5')
12
- expect(result).toEqual({
13
- file: 'src/components/Header.tsx',
14
- line: '100',
15
- column: '5',
16
- })
17
- })
18
-
19
- test('parses file path with colons in filename (Windows-style)', () => {
20
- const result = parseOpenSourceParam('C:/Users/test/file.tsx:10:20')
21
- expect(result).toEqual({
22
- file: 'C:/Users/test/file.tsx',
23
- line: '10',
24
- column: '20',
25
- })
26
- })
27
-
28
- test('returns null for invalid format without line/column', () => {
29
- const result = parseOpenSourceParam('src/file.tsx')
30
- expect(result).toBeNull()
31
- })
32
-
33
- test('returns null for invalid format with only one number', () => {
34
- const result = parseOpenSourceParam('src/file.tsx:26')
35
- expect(result).toBeNull()
36
- })
37
- })
38
-
39
- describe('stripEnhancedLogPrefix', () => {
40
- test('returns empty array for empty input', () => {
41
- const result = stripEnhancedLogPrefix([])
42
- expect(result).toEqual([])
43
- })
44
-
45
- test('returns args unchanged when no enhanced log URL is present', () => {
46
- const args = ['hello', 'world', 123]
47
- const result = stripEnhancedLogPrefix(args)
48
- expect(result).toEqual(args)
49
- })
50
-
51
- test('extracts source location and user args from enhanced log format', () => {
52
- // Simulated enhanced log format:
53
- // ['%cLOG%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Ffile.tsx%3A26%3A13%c \n → ', 'style1', 'style2', 'style3', 'style4', 'user message']
54
- const args = [
55
- '%cLOG%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Ffile.tsx%3A26%3A13%c \n → ',
56
- 'color: blue',
57
- 'color: reset',
58
- 'color: green',
59
- 'color: reset',
60
- 'user message',
61
- ]
62
- const result = stripEnhancedLogPrefix(args)
63
- expect(result).toEqual(['src/file.tsx:26:13', 'user message'])
64
- })
65
-
66
- test('handles multiple user args after enhanced log prefix', () => {
67
- const args = [
68
- '%cLOG%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Fcomponents%2FHeader.tsx%3A100%3A5%c \n → ',
69
- 'style1',
70
- 'style2',
71
- 'style3',
72
- 'style4',
73
- 'message 1',
74
- { key: 'value' },
75
- 42,
76
- ]
77
- const result = stripEnhancedLogPrefix(args)
78
- expect(result).toEqual([
79
- 'src/components/Header.tsx:100:5',
80
- 'message 1',
81
- { key: 'value' },
82
- 42,
83
- ])
84
- })
85
-
86
- test('handles source location with leading slash by removing it', () => {
87
- const args = [
88
- '%cINFO%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fapp%2Fpage.tsx%3A10%3A1%c \n → ',
89
- 's1',
90
- 's2',
91
- 's3',
92
- 's4',
93
- 'info log',
94
- ]
95
- const result = stripEnhancedLogPrefix(args)
96
- // Leading slash is removed
97
- expect(result).toEqual(['app/page.tsx:10:1', 'info log'])
98
- })
99
-
100
- test('applies custom formatter to source location', () => {
101
- const args = [
102
- '%cWARN%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Findex.ts%3A5%3A2%c \n → ',
103
- 's1',
104
- 's2',
105
- 's3',
106
- 's4',
107
- 'warning message',
108
- ]
109
- const customFormatter = (loc: string) => `[${loc}]`
110
- const result = stripEnhancedLogPrefix(args, customFormatter)
111
- expect(result).toEqual(['[src/index.ts:5:2]', 'warning message'])
112
- })
113
-
114
- test('handles ANSI prefix format (second variant)', () => {
115
- // Format: ['\x1b[...]%s\x1b[...]', '%cLOG%c %cGo to Source: ...%c \n → ', 'style...', ..., 'message']
116
- const args = [
117
- '\x1b[90m%s\x1b[0m',
118
- '%cDEBUG%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Fdebug.ts%3A1%3A1%c \n → ',
119
- 's1',
120
- 's2',
121
- 's3',
122
- 's4',
123
- 'debug output',
124
- ]
125
- const result = stripEnhancedLogPrefix(args)
126
- // The source URL is in index 1, so source location should be extracted from there
127
- expect(result).toEqual(['src/debug.ts:1:1', 'debug output'])
128
- })
129
-
130
- test('returns original args when source URL decoding fails', () => {
131
- const args = [
132
- '%cLOG%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%INVALID%c \n → ',
133
- 's1',
134
- 's2',
135
- 's3',
136
- 's4',
137
- 'message',
138
- ]
139
- // Should gracefully handle decoding error and return user args without source
140
- const result = stripEnhancedLogPrefix(args)
141
- // Since decoding fails, sourceLocation will be empty, so result should just have user args
142
- expect(result).toEqual(['message'])
143
- })
144
-
145
- test('handles enhanced log with no user args after style markers', () => {
146
- const args = [
147
- 'Go to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Ftest.ts%3A1%3A1%c',
148
- 'style-arg', // This is consumed as a style arg due to %c marker
149
- ]
150
- const result = stripEnhancedLogPrefix(args)
151
- // One %c marker means one style arg follows the source arg, leaving no user args
152
- expect(result).toEqual(['src/test.ts:1:1'])
153
- })
154
-
155
- test('handles enhanced log at non-zero index in args array', () => {
156
- const args = [
157
- 'some prefix',
158
- '%cERROR%c %cGo to Source: http://localhost:3000/__tsd/open-source?source=%2Fsrc%2Ferror.ts%3A50%3A10%c \n → ',
159
- 's1',
160
- 's2',
161
- 's3',
162
- 's4',
163
- 'error details',
164
- ]
165
- const result = stripEnhancedLogPrefix(args)
166
- expect(result).toEqual(['src/error.ts:50:10', 'error details'])
167
- })
168
-
169
- test('handles deeply nested path in source location', () => {
170
- const args = [
171
- '%cLOG%c %cGo to Source: http://localhost:5173/__tsd/open-source?source=%2Fpackages%2Fdevtools-vite%2Fsrc%2Fplugin.ts%3A123%3A45%c \n → ',
172
- 's1',
173
- 's2',
174
- 's3',
175
- 's4',
176
- 'deep path log',
177
- ]
178
- const result = stripEnhancedLogPrefix(args)
179
- expect(result).toEqual([
180
- 'packages/devtools-vite/src/plugin.ts:123:45',
181
- 'deep path log',
182
- ])
183
- })
184
- })