{"element_type":"file","project_name":"tsgitlabtest","uuid":"b5f74108-2d6a-4fd3-8c76-300f41f00325","name":"DefaultCrossWindowChannel.test.ts","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['noop'], 'import_path': 'lodash'}, {'import_name': ['DefaultCrossWindowChannel'], 'import_path': '.\/DefaultCrossWindowChannel'}, {'import_name': ['PortChannelRequestMessage', 'PortChannelResponseMessage', 'PortName', 'WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"import { createFakePartial } from '@gitlab\/utils-test';\nimport type { Disposable } from '@gitlab\/web-ide-types';\nimport { noop } from 'lodash';\nimport { DefaultCrossWindowChannel } from '.\/DefaultCrossWindowChannel';\nimport type {\n PortChannelRequestMessage,\n PortChannelResponseMessage,\n PortName,\n WindowChannelMessage,\n} from '.\/types';\n\ndescribe('DefaultCrossWindowChannel', () => {\n let defaultWindowChannel: DefaultCrossWindowChannel;\n let localWindow: Window;\n let remoteWindow: Window;\n const REMOTE_WINDOW_ORIGIN = 'http:\/\/example.com';\n const TEST_MESSAGE: PortChannelRequestMessage = {\n key: 'port-channel-request',\n params: {\n name: 'auth-port',\n },\n };\n const invokeMessageEventListeners = (window: Window, event: MessageEvent) => {\n jest.mocked(window.addEventListener).mock.calls.forEach(([, handler]) => {\n if (typeof handler === 'function') {\n handler(event);\n } else {\n handler.handleEvent(event);\n }\n });\n };\n\n beforeEach(() => {\n global.MessageChannel = jest.fn().mockImplementation(() =>\n createFakePartial({\n port1: createFakePartial({}),\n port2: createFakePartial({}),\n }),\n );\n\n localWindow = createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n });\n remoteWindow = createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n });\n\n defaultWindowChannel = new DefaultCrossWindowChannel({\n localWindow,\n remoteWindow,\n remoteWindowOrigin: REMOTE_WINDOW_ORIGIN,\n });\n });\n\n describe('postMessage', () => {\n it('posts messages to the target window', () => {\n defaultWindowChannel.postMessage(TEST_MESSAGE);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(TEST_MESSAGE, REMOTE_WINDOW_ORIGIN);\n });\n\n describe('when message is port-channel-response message', () => {\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port: createFakePartial({}),\n },\n };\n\n it('sends port as a transferable object', () => {\n defaultWindowChannel.postMessage(portChannelResponseMessage);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n [portChannelResponseMessage.params.port],\n );\n });\n });\n });\n\n describe('addMessagesListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessagesListener(listener);\n });\n\n it('listens for messages on the localWindow', () => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: TEST_MESSAGE,\n }),\n );\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when the receive message has incorrect origin', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n }),\n );\n });\n\n it('ignores the message', () => {\n expect(listener).not.toHaveBeenCalled();\n });\n });\n\n describe('when the event source is the remote window', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n source: remoteWindow,\n }),\n );\n });\n\n it('accepts messages from any origin', () => {\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n });\n\n describe('addMessageListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessageListener(TEST_MESSAGE.key, listener);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const event = new MessageEvent('message', {\n data: TEST_MESSAGE,\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n\n describe('when receiving unexpected message key', () => {\n it('does not invoke the callback function', () => {\n const event = new MessageEvent('message', {\n data: {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: 'error' },\n },\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('requestRemotePortChannel', () => {\n it('posts a port-channel-request message to targetWindow', () => {\n defaultWindowChannel.requestRemotePortChannel('auth-port').catch(noop);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-request',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n\n describe('when targetWindow responds with a port-channel-response message', () => {\n it('returns the response as PortChannel', async () => {\n const port = createFakePartial({});\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port,\n },\n };\n\n const portChannelPromise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n const messageEvent = new MessageEvent('message', {\n data: portChannelResponseMessage,\n origin: REMOTE_WINDOW_ORIGIN,\n ports: [port],\n });\n\n invokeMessageEventListeners(localWindow, messageEvent);\n\n const portChannel = await portChannelPromise;\n\n expect(portChannel.messagePort).toBe(port);\n });\n });\n\n describe('when channel does not receive a valid response and times out', () => {\n jest.useFakeTimers();\n\n it('throws a timeout error', async () => {\n const promise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n\n jest.runAllTimers();\n\n await expect(promise).rejects.toThrow(\/timed out\/);\n });\n });\n });\n\n describe('createLocalPortChannel', () => {\n it('does not create a port channel twice', () => {\n const portChannelOne = defaultWindowChannel.createLocalPortChannel('auth-port');\n const portChannelTwo = defaultWindowChannel.createLocalPortChannel('auth-port');\n\n expect(portChannelOne.messagePort).toBe(portChannelTwo.messagePort);\n });\n\n describe('when origin window receives a port-channel-request message', () => {\n const sendPortChannelRequestMessage = (name: PortName) => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: { key: 'port-channel-request', params: { name } },\n }),\n );\n };\n\n describe('when port has been created', () => {\n beforeEach(() => {\n defaultWindowChannel.createLocalPortChannel('auth-port');\n });\n\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n });\n });\n\n describe('when port has not been created', () => {\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n });\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f41b1f1c-bb19-4679-9155-26e1ee513640","name":"DefaultCrossWindowChannel","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['noop'], 'import_path': 'lodash'}, {'import_name': ['DefaultCrossWindowChannel'], 'import_path': '.\/DefaultCrossWindowChannel'}, {'import_name': ['PortChannelRequestMessage', 'PortChannelResponseMessage', 'PortName', 'WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('DefaultCrossWindowChannel', () => {\n let defaultWindowChannel: DefaultCrossWindowChannel;\n let localWindow: Window;\n let remoteWindow: Window;\n const REMOTE_WINDOW_ORIGIN = 'http:\/\/example.com';\n const TEST_MESSAGE: PortChannelRequestMessage = {\n key: 'port-channel-request',\n params: {\n name: 'auth-port',\n },\n };\n const invokeMessageEventListeners = (window: Window, event: MessageEvent) => {\n jest.mocked(window.addEventListener).mock.calls.forEach(([, handler]) => {\n if (typeof handler === 'function') {\n handler(event);\n } else {\n handler.handleEvent(event);\n }\n });\n };\n\n beforeEach(() => {\n global.MessageChannel = jest.fn().mockImplementation(() =>\n createFakePartial({\n port1: createFakePartial({}),\n port2: createFakePartial({}),\n }),\n );\n\n localWindow = createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n });\n remoteWindow = createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n });\n\n defaultWindowChannel = new DefaultCrossWindowChannel({\n localWindow,\n remoteWindow,\n remoteWindowOrigin: REMOTE_WINDOW_ORIGIN,\n });\n });\n\n describe('postMessage', () => {\n it('posts messages to the target window', () => {\n defaultWindowChannel.postMessage(TEST_MESSAGE);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(TEST_MESSAGE, REMOTE_WINDOW_ORIGIN);\n });\n\n describe('when message is port-channel-response message', () => {\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port: createFakePartial({}),\n },\n };\n\n it('sends port as a transferable object', () => {\n defaultWindowChannel.postMessage(portChannelResponseMessage);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n [portChannelResponseMessage.params.port],\n );\n });\n });\n });\n\n describe('addMessagesListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessagesListener(listener);\n });\n\n it('listens for messages on the localWindow', () => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: TEST_MESSAGE,\n }),\n );\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when the receive message has incorrect origin', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n }),\n );\n });\n\n it('ignores the message', () => {\n expect(listener).not.toHaveBeenCalled();\n });\n });\n\n describe('when the event source is the remote window', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n source: remoteWindow,\n }),\n );\n });\n\n it('accepts messages from any origin', () => {\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n });\n\n describe('addMessageListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessageListener(TEST_MESSAGE.key, listener);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const event = new MessageEvent('message', {\n data: TEST_MESSAGE,\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n\n describe('when receiving unexpected message key', () => {\n it('does not invoke the callback function', () => {\n const event = new MessageEvent('message', {\n data: {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: 'error' },\n },\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('requestRemotePortChannel', () => {\n it('posts a port-channel-request message to targetWindow', () => {\n defaultWindowChannel.requestRemotePortChannel('auth-port').catch(noop);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-request',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n\n describe('when targetWindow responds with a port-channel-response message', () => {\n it('returns the response as PortChannel', async () => {\n const port = createFakePartial({});\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port,\n },\n };\n\n const portChannelPromise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n const messageEvent = new MessageEvent('message', {\n data: portChannelResponseMessage,\n origin: REMOTE_WINDOW_ORIGIN,\n ports: [port],\n });\n\n invokeMessageEventListeners(localWindow, messageEvent);\n\n const portChannel = await portChannelPromise;\n\n expect(portChannel.messagePort).toBe(port);\n });\n });\n\n describe('when channel does not receive a valid response and times out', () => {\n jest.useFakeTimers();\n\n it('throws a timeout error', async () => {\n const promise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n\n jest.runAllTimers();\n\n await expect(promise).rejects.toThrow(\/timed out\/);\n });\n });\n });\n\n describe('createLocalPortChannel', () => {\n it('does not create a port channel twice', () => {\n const portChannelOne = defaultWindowChannel.createLocalPortChannel('auth-port');\n const portChannelTwo = defaultWindowChannel.createLocalPortChannel('auth-port');\n\n expect(portChannelOne.messagePort).toBe(portChannelTwo.messagePort);\n });\n\n describe('when origin window receives a port-channel-request message', () => {\n const sendPortChannelRequestMessage = (name: PortName) => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: { key: 'port-channel-request', params: { name } },\n }),\n );\n };\n\n describe('when port has been created', () => {\n beforeEach(() => {\n defaultWindowChannel.createLocalPortChannel('auth-port');\n });\n\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n });\n });\n\n describe('when port has not been created', () => {\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n });\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"b64f820b-a1e3-4c89-a6f8-8ce4397384c5","name":"postMessage","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('postMessage', () => {\n it('posts messages to the target window', () => {\n defaultWindowChannel.postMessage(TEST_MESSAGE);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(TEST_MESSAGE, REMOTE_WINDOW_ORIGIN);\n });\n\n describe('when message is port-channel-response message', () => {\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port: createFakePartial({}),\n },\n };\n\n it('sends port as a transferable object', () => {\n defaultWindowChannel.postMessage(portChannelResponseMessage);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n [portChannelResponseMessage.params.port],\n );\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"5dbb4bd4-5e11-4afd-bbab-40a8d71acd43","name":"when message is port-channel-response message","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when message is port-channel-response message', () => {\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port: createFakePartial({}),\n },\n };\n\n it('sends port as a transferable object', () => {\n defaultWindowChannel.postMessage(portChannelResponseMessage);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n [portChannelResponseMessage.params.port],\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"5e6837f1-3136-4135-922d-d71592ce7705","name":"addMessagesListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('addMessagesListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessagesListener(listener);\n });\n\n it('listens for messages on the localWindow', () => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: TEST_MESSAGE,\n }),\n );\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when the receive message has incorrect origin', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n }),\n );\n });\n\n it('ignores the message', () => {\n expect(listener).not.toHaveBeenCalled();\n });\n });\n\n describe('when the event source is the remote window', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n source: remoteWindow,\n }),\n );\n });\n\n it('accepts messages from any origin', () => {\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"30f39978-ed9c-420f-8632-435238832f07","name":"when the receive message has incorrect origin","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when the receive message has incorrect origin', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n }),\n );\n });\n\n it('ignores the message', () => {\n expect(listener).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"048c9b8e-7797-45ff-ab68-c04b869d34b6","name":"when the event source is the remote window","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when the event source is the remote window', () => {\n beforeEach(() => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n data: TEST_MESSAGE,\n source: remoteWindow,\n }),\n );\n });\n\n it('accepts messages from any origin', () => {\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"27bad85c-c023-4d96-b985-61842115b717","name":"addMessageListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('addMessageListener', () => {\n let disposable: Disposable;\n let listener: jest.Mock;\n\n beforeEach(() => {\n listener = jest.fn();\n\n disposable = defaultWindowChannel.addMessageListener(TEST_MESSAGE.key, listener);\n });\n\n it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const event = new MessageEvent('message', {\n data: TEST_MESSAGE,\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n });\n\n describe('when receiving unexpected message key', () => {\n it('does not invoke the callback function', () => {\n const event = new MessageEvent('message', {\n data: {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: 'error' },\n },\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).not.toHaveBeenCalled();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f04b0022-9234-4de4-9148-96b88b10f7c1","name":"when receiving expected message key","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const event = new MessageEvent('message', {\n data: TEST_MESSAGE,\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"2c1c2033-e6e3-454e-9177-aa42378bf8ac","name":"when receiving unexpected message key","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when receiving unexpected message key', () => {\n it('does not invoke the callback function', () => {\n const event = new MessageEvent('message', {\n data: {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: 'error' },\n },\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"2e8b429a-ddda-4104-87d1-5650471144f6","name":"requestRemotePortChannel","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['noop'], 'import_path': 'lodash'}, {'import_name': ['PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('requestRemotePortChannel', () => {\n it('posts a port-channel-request message to targetWindow', () => {\n defaultWindowChannel.requestRemotePortChannel('auth-port').catch(noop);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-request',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n\n describe('when targetWindow responds with a port-channel-response message', () => {\n it('returns the response as PortChannel', async () => {\n const port = createFakePartial({});\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port,\n },\n };\n\n const portChannelPromise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n const messageEvent = new MessageEvent('message', {\n data: portChannelResponseMessage,\n origin: REMOTE_WINDOW_ORIGIN,\n ports: [port],\n });\n\n invokeMessageEventListeners(localWindow, messageEvent);\n\n const portChannel = await portChannelPromise;\n\n expect(portChannel.messagePort).toBe(port);\n });\n });\n\n describe('when channel does not receive a valid response and times out', () => {\n jest.useFakeTimers();\n\n it('throws a timeout error', async () => {\n const promise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n\n jest.runAllTimers();\n\n await expect(promise).rejects.toThrow(\/timed out\/);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"56fe0021-bf80-4282-82cf-9b49685e3b8e","name":"when targetWindow responds with a port-channel-response message","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when targetWindow responds with a port-channel-response message', () => {\n it('returns the response as PortChannel', async () => {\n const port = createFakePartial({});\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port,\n },\n };\n\n const portChannelPromise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n const messageEvent = new MessageEvent('message', {\n data: portChannelResponseMessage,\n origin: REMOTE_WINDOW_ORIGIN,\n ports: [port],\n });\n\n invokeMessageEventListeners(localWindow, messageEvent);\n\n const portChannel = await portChannelPromise;\n\n expect(portChannel.messagePort).toBe(port);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"5ded7d69-0f56-42ca-ad37-622fd0648c88","name":"when channel does not receive a valid response and times out","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when channel does not receive a valid response and times out', () => {\n jest.useFakeTimers();\n\n it('throws a timeout error', async () => {\n const promise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n\n jest.runAllTimers();\n\n await expect(promise).rejects.toThrow(\/timed out\/);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"2f5824e6-ccab-4a29-b59c-2e6e31c67bc0","name":"createLocalPortChannel","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelRequestMessage', 'PortName'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('createLocalPortChannel', () => {\n it('does not create a port channel twice', () => {\n const portChannelOne = defaultWindowChannel.createLocalPortChannel('auth-port');\n const portChannelTwo = defaultWindowChannel.createLocalPortChannel('auth-port');\n\n expect(portChannelOne.messagePort).toBe(portChannelTwo.messagePort);\n });\n\n describe('when origin window receives a port-channel-request message', () => {\n const sendPortChannelRequestMessage = (name: PortName) => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: { key: 'port-channel-request', params: { name } },\n }),\n );\n };\n\n describe('when port has been created', () => {\n beforeEach(() => {\n defaultWindowChannel.createLocalPortChannel('auth-port');\n });\n\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n });\n });\n\n describe('when port has not been created', () => {\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"9da888a7-85e9-4f58-89e6-7d0599b8ad7b","name":"when origin window receives a port-channel-request message","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelRequestMessage', 'PortName'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when origin window receives a port-channel-request message', () => {\n const sendPortChannelRequestMessage = (name: PortName) => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: { key: 'port-channel-request', params: { name } },\n }),\n );\n };\n\n describe('when port has been created', () => {\n beforeEach(() => {\n defaultWindowChannel.createLocalPortChannel('auth-port');\n });\n\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n });\n });\n\n describe('when port has not been created', () => {\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"1ffe65a6-e80c-4a54-b81c-151b21019b24","name":"when port has been created","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelRequestMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when port has been created', () => {\n beforeEach(() => {\n defaultWindowChannel.createLocalPortChannel('auth-port');\n });\n\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"31e1cfa4-188b-4653-9876-6159c84680f8","name":"when port has not been created","imports":"[{'import_name': ['PortChannelRequestMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"describe('when port has not been created', () => {\n it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"07bc39fb-ff01-453f-9a01-9b4507fedd84","name":"posts messages to the target window","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('posts messages to the target window', () => {\n defaultWindowChannel.postMessage(TEST_MESSAGE);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(TEST_MESSAGE, REMOTE_WINDOW_ORIGIN);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"aa7dbe7b-c9d3-41cc-9607-33f63e8ca9d1","name":"sends port as a transferable object","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('sends port as a transferable object', () => {\n defaultWindowChannel.postMessage(portChannelResponseMessage);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n [portChannelResponseMessage.params.port],\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"2f96cc0a-0f0f-4456-9fee-05841b23fee3","name":"listens for messages on the localWindow","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('listens for messages on the localWindow', () => {\n invokeMessageEventListeners(\n localWindow,\n new MessageEvent('message', {\n origin: REMOTE_WINDOW_ORIGIN,\n data: TEST_MESSAGE,\n }),\n );\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"e7979db2-04b1-4f2a-bad7-b7819be4566e","name":"returns a disposable that allows removing event listener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"3a104f33-83c0-4207-b6a8-0426e1a5a555","name":"ignores the message","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('ignores the message', () => {\n expect(listener).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c2190abc-9111-440f-b397-92f81572bb5b","name":"accepts messages from any origin","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('accepts messages from any origin', () => {\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"8160fbed-3d33-4b28-b170-2f322056d622","name":"returns a disposable that allows removing event listener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('returns a disposable that allows removing event listener', () => {\n disposable.dispose();\n\n const nativeListener = jest.mocked(localWindow.addEventListener).mock.lastCall[1];\n\n expect(localWindow.removeEventListener).toHaveBeenCalledWith('message', nativeListener);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"64447e1b-a9fb-421e-a720-7908fd854f3d","name":"invokes the callback function","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('invokes the callback function', () => {\n const event = new MessageEvent('message', {\n data: TEST_MESSAGE,\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).toHaveBeenCalledWith(TEST_MESSAGE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"b23a6b9a-e0f7-4214-9588-e244f23275f7","name":"does not invoke the callback function","imports":"[{'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('does not invoke the callback function', () => {\n const event = new MessageEvent('message', {\n data: {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: 'error' },\n },\n origin: REMOTE_WINDOW_ORIGIN,\n });\n\n invokeMessageEventListeners(localWindow, event);\n\n expect(listener).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"50ee91e5-699b-4b47-9c51-83ac1163be6e","name":"posts a port-channel-request message to targetWindow","imports":"[{'import_name': ['noop'], 'import_path': 'lodash'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('posts a port-channel-request message to targetWindow', () => {\n defaultWindowChannel.requestRemotePortChannel('auth-port').catch(noop);\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-request',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"034041e9-eaf9-4d66-8550-0497a33b6f89","name":"returns the response as PortChannel","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('returns the response as PortChannel', async () => {\n const port = createFakePartial({});\n const portChannelResponseMessage: PortChannelResponseMessage = {\n key: 'port-channel-response',\n params: {\n name: 'auth-port',\n port,\n },\n };\n\n const portChannelPromise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n const messageEvent = new MessageEvent('message', {\n data: portChannelResponseMessage,\n origin: REMOTE_WINDOW_ORIGIN,\n ports: [port],\n });\n\n invokeMessageEventListeners(localWindow, messageEvent);\n\n const portChannel = await portChannelPromise;\n\n expect(portChannel.messagePort).toBe(port);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"290b6349-ba15-4cb6-a6bb-f41d30c7ef14","name":"throws a timeout error","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('throws a timeout error', async () => {\n const promise = defaultWindowChannel.requestRemotePortChannel('auth-port');\n\n jest.runAllTimers();\n\n await expect(promise).rejects.toThrow(\/timed out\/);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"94957e92-d231-4a27-84fb-16b03b10df3f","name":"does not create a port channel twice","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('does not create a port channel twice', () => {\n const portChannelOne = defaultWindowChannel.createLocalPortChannel('auth-port');\n const portChannelTwo = defaultWindowChannel.createLocalPortChannel('auth-port');\n\n expect(portChannelOne.messagePort).toBe(portChannelTwo.messagePort);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"996c59ac-b112-4fcc-a6a8-7cc4b34c45c0","name":"sends port-channel-response to the target window","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelRequestMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response',\n params: { name: 'auth-port' },\n },\n REMOTE_WINDOW_ORIGIN,\n expect.arrayContaining([createFakePartial({})]),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"31ea7c30-c401-4d55-8c91-8d8e8902969d","name":"sends port-channel-response to the target window","imports":"[{'import_name': ['PortChannelRequestMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.test.ts","code":"it('sends port-channel-response to the target window', () => {\n sendPortChannelRequestMessage('auth-port');\n\n expect(remoteWindow.postMessage).toHaveBeenCalledWith(\n {\n key: 'port-channel-response-error',\n params: { name: 'auth-port', error: expect.any(String) },\n },\n REMOTE_WINDOW_ORIGIN,\n );\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"ae132d02-5fb5-4e63-8a08-8a1e5a088d66","name":"DefaultCrossWindowChannel.ts","imports":"[{'import_name': ['omit'], 'import_path': 'lodash'}, {'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}, {'import_name': ['PortChannel', 'CrossWindowChannel', 'WindowChannelMessage', 'WindowChannelMessageKey', 'PortName', 'PortChannelResponseMessage', 'PortChannelRequestMessage'], 'import_path': '.\/types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"import { omit } from 'lodash';\nimport type { Disposable } from '@gitlab\/web-ide-types';\nimport { DefaultPortChannel } from '.\/DefaultPortChannel';\nimport type {\n PortChannel,\n CrossWindowChannel,\n WindowChannelMessage,\n WindowChannelMessageKey,\n PortName,\n PortChannelResponseMessage,\n PortChannelRequestMessage,\n} from '.\/types';\nimport { WAIT_FOR_MESSAGE_TIMEOUT } from '.\/constants';\n\ninterface WindowChannelConstructorOptions {\n remoteWindowOrigin: string;\n remoteWindow: Window;\n localWindow: Window;\n}\n\nexport class DefaultCrossWindowChannel implements CrossWindowChannel {\n readonly #localWindow: Window;\n\n readonly #remoteWindow: Window;\n\n readonly #remoteWindowOrigin: string;\n\n readonly #messageChannels: Map;\n\n readonly #disposables: Disposable[];\n\n constructor({ localWindow, remoteWindow, remoteWindowOrigin }: WindowChannelConstructorOptions) {\n this.#localWindow = localWindow;\n this.#remoteWindow = remoteWindow;\n this.#remoteWindowOrigin = remoteWindowOrigin;\n this.#messageChannels = new Map();\n this.#disposables = [];\n\n this.#disposables.push(\n this.addMessageListener('port-channel-request', event => {\n const { name } = event.params;\n const channel = this.#messageChannels.get(name);\n\n if (channel) {\n this.postMessage({ key: 'port-channel-response', params: { name, port: channel.port2 } });\n } else {\n this.postMessage({\n key: 'port-channel-response-error',\n params: { name, error: `Could not find a port with name ${name}` },\n });\n }\n }),\n );\n }\n\n dispose() {\n this.#disposables.forEach(disposable => {\n disposable.dispose();\n });\n }\n\n postMessage(message: WindowChannelMessage): void {\n if (message.key === 'port-channel-response') {\n this.#remoteWindow.postMessage(\n { key: message.key, params: { ...omit(message.params, 'port') } },\n this.#remoteWindowOrigin,\n [message.params.port],\n );\n } else {\n this.#remoteWindow.postMessage(message, this.#remoteWindowOrigin);\n }\n }\n\n addMessagesListener(callback: (message: WindowChannelMessage) => void): Disposable {\n const localWindow = this.#localWindow;\n const remoteWindowOrigin = this.#remoteWindowOrigin;\n\n const listener = (event: MessageEvent) => {\n const message = event.data;\n\n if (event.source !== this.#remoteWindow && event.origin !== remoteWindowOrigin) {\n return;\n }\n\n if (message.key === 'port-channel-response') {\n callback({\n key: 'port-channel-response',\n params: { name: message.params.name, port: event.ports[0] },\n });\n } else {\n callback(message);\n }\n };\n\n localWindow.addEventListener('message', listener);\n\n return {\n dispose() {\n localWindow.removeEventListener('message', listener);\n },\n };\n }\n\n addMessageListener(\n targetMessageKey: WindowChannelMessageKey,\n callback: (message: T) => void,\n ): Disposable {\n return this.addMessagesListener(message => {\n if (message.key === targetMessageKey) {\n callback(message as T);\n }\n });\n }\n\n waitForMessage(\n targetMessageKey: WindowChannelMessageKey,\n ): Promise {\n return new Promise((resolve, reject) => {\n const disposable = this.addMessageListener(targetMessageKey, message => {\n resolve(message);\n disposable.dispose();\n });\n\n setTimeout(() => {\n disposable.dispose();\n reject(new Error(`Channel timed out while waiting for message ${targetMessageKey}`));\n }, WAIT_FOR_MESSAGE_TIMEOUT);\n });\n }\n\n async requestRemotePortChannel(name: PortName): Promise {\n this.postMessage({ key: 'port-channel-request', params: { name } });\n\n const message = await this.waitForMessage('port-channel-response');\n\n return new DefaultPortChannel({ name, messagePort: message.params.port });\n }\n\n createLocalPortChannel(name: PortName): PortChannel {\n let channel = this.#messageChannels.get(name);\n\n if (!channel) {\n channel = new MessageChannel();\n this.#messageChannels.set(name, channel);\n }\n\n return new DefaultPortChannel({ name, messagePort: channel.port1 });\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f0bb19a9-eaf8-4466-99c4-fcd5d4be3e00","name":"constructor","imports":"[{'import_name': ['PortChannel', 'PortName', 'PortChannelRequestMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"constructor({ localWindow, remoteWindow, remoteWindowOrigin }: WindowChannelConstructorOptions) {\n this.#localWindow = localWindow;\n this.#remoteWindow = remoteWindow;\n this.#remoteWindowOrigin = remoteWindowOrigin;\n this.#messageChannels = new Map();\n this.#disposables = [];\n\n this.#disposables.push(\n this.addMessageListener('port-channel-request', event => {\n const { name } = event.params;\n const channel = this.#messageChannels.get(name);\n\n if (channel) {\n this.postMessage({ key: 'port-channel-response', params: { name, port: channel.port2 } });\n } else {\n this.postMessage({\n key: 'port-channel-response-error',\n params: { name, error: `Could not find a port with name ${name}` },\n });\n }\n }),\n );\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f4c82910-ec71-427f-807d-963904151968","name":"dispose","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"dispose() {\n this.#disposables.forEach(disposable => {\n disposable.dispose();\n });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"eef9b1fd-f180-412a-b41a-d976f7caa858","name":"postMessage","imports":"[{'import_name': ['omit'], 'import_path': 'lodash'}, {'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"postMessage(message: WindowChannelMessage): void {\n if (message.key === 'port-channel-response') {\n this.#remoteWindow.postMessage(\n { key: message.key, params: { ...omit(message.params, 'port') } },\n this.#remoteWindowOrigin,\n [message.params.port],\n );\n } else {\n this.#remoteWindow.postMessage(message, this.#remoteWindowOrigin);\n }\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"833a18da-151e-405a-9c0f-d3f7b67fb700","name":"addMessagesListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['WindowChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"addMessagesListener(callback: (message: WindowChannelMessage) => void): Disposable {\n const localWindow = this.#localWindow;\n const remoteWindowOrigin = this.#remoteWindowOrigin;\n\n const listener = (event: MessageEvent) => {\n const message = event.data;\n\n if (event.source !== this.#remoteWindow && event.origin !== remoteWindowOrigin) {\n return;\n }\n\n if (message.key === 'port-channel-response') {\n callback({\n key: 'port-channel-response',\n params: { name: message.params.name, port: event.ports[0] },\n });\n } else {\n callback(message);\n }\n };\n\n localWindow.addEventListener('message', listener);\n\n return {\n dispose() {\n localWindow.removeEventListener('message', listener);\n },\n };\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d6290cee-b3c6-4d6d-800c-b33e6dddded4","name":"addMessageListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['WindowChannelMessage', 'WindowChannelMessageKey'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"addMessageListener(\n targetMessageKey: WindowChannelMessageKey,\n callback: (message: T) => void,\n ): Disposable {\n return this.addMessagesListener(message => {\n if (message.key === targetMessageKey) {\n callback(message as T);\n }\n });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6d413e50-b6d6-4193-82d5-85cbc3071ea7","name":"waitForMessage","imports":"[{'import_name': ['WindowChannelMessage', 'WindowChannelMessageKey'], 'import_path': '.\/types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"waitForMessage(\n targetMessageKey: WindowChannelMessageKey,\n ): Promise {\n return new Promise((resolve, reject) => {\n const disposable = this.addMessageListener(targetMessageKey, message => {\n resolve(message);\n disposable.dispose();\n });\n\n setTimeout(() => {\n disposable.dispose();\n reject(new Error(`Channel timed out while waiting for message ${targetMessageKey}`));\n }, WAIT_FOR_MESSAGE_TIMEOUT);\n });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ca141940-0931-4725-bae7-a5c56c64c159","name":"requestRemotePortChannel","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}, {'import_name': ['PortChannel', 'PortName', 'PortChannelResponseMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"async requestRemotePortChannel(name: PortName): Promise {\n this.postMessage({ key: 'port-channel-request', params: { name } });\n\n const message = await this.waitForMessage('port-channel-response');\n\n return new DefaultPortChannel({ name, messagePort: message.params.port });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"1b9ad5dd-884e-4995-b218-42a11d2092aa","name":"createLocalPortChannel","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}, {'import_name': ['PortChannel', 'PortName'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultCrossWindowChannel.ts","code":"createLocalPortChannel(name: PortName): PortChannel {\n let channel = this.#messageChannels.get(name);\n\n if (!channel) {\n channel = new MessageChannel();\n this.#messageChannels.set(name, channel);\n }\n\n return new DefaultPortChannel({ name, messagePort: channel.port1 });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultCrossWindowChannel'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2a1b46f9-c7ba-423a-86ae-3de1e84fe445","name":"DefaultPortChannel.test.ts","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"import { createFakePartial } from '@gitlab\/utils-test';\nimport type { PortChannelMessage } from '.\/types';\nimport { WAIT_FOR_MESSAGE_TIMEOUT } from '.\/constants';\nimport { DefaultPortChannel } from '.\/DefaultPortChannel';\n\ndescribe('DefaultPortChannel', () => {\n const invokeMessageEventListeners = (messagePort: MessagePort, event: MessageEvent) => {\n jest.mocked(messagePort.addEventListener).mock.calls.forEach(([, handler]) => {\n if (typeof handler === 'function') {\n handler(event);\n } else {\n handler.handleEvent(event);\n }\n });\n };\n\n const createFakeMessagePort = (): MessagePort =>\n createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n start: jest.fn(),\n close: jest.fn(),\n });\n\n describe('start', () => {\n it('should start the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.start();\n\n expect(mockMessagePort.start).toHaveBeenCalled();\n });\n });\n\n describe('postMessage', () => {\n it('should post the given message', () => {\n const message: PortChannelMessage = {\n key: 'authentication-token-response',\n params: { token: 'foo' },\n };\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.postMessage(message);\n\n expect(mockMessagePort.postMessage).toHaveBeenCalledWith(message);\n });\n });\n\n describe('addMessagesListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessagesListener(listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessagesListener(callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('addMessageListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessageListener('authentication-token-changed', listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-changed', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('waitForMessage', () => {\n jest.useFakeTimers();\n\n const mockMessagePort = createFakeMessagePort();\n const mockMessage: PortChannelMessage = {\n key: 'authentication-token-response',\n params: {\n token: 'foo',\n },\n };\n const messageEvent = new MessageEvent('message', {\n data: mockMessage,\n ports: [],\n });\n let channel: DefaultPortChannel;\n let waitForMessagePromise: Promise;\n\n beforeEach(() => {\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n waitForMessagePromise = channel.waitForMessage(mockMessage.key);\n });\n\n describe('when expected message is received', () => {\n it('returns the received message', async () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(await waitForMessagePromise).toEqual(mockMessage);\n });\n\n it('removes the event listener after receiving the expected message', () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n });\n\n describe('when expected message is not received', () => {\n it('should reject with a timeout error', async () => {\n jest.advanceTimersByTime(WAIT_FOR_MESSAGE_TIMEOUT);\n\n await expect(waitForMessagePromise).rejects.toThrow(\/Channel timed out\/);\n });\n });\n });\n\n describe('dispose', () => {\n it('should close the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n\n channel.dispose();\n\n expect(mockMessagePort.close).toHaveBeenCalled();\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"98d16d17-3bbe-46ea-889d-70b6f728bb42","name":"DefaultPortChannel","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('DefaultPortChannel', () => {\n const invokeMessageEventListeners = (messagePort: MessagePort, event: MessageEvent) => {\n jest.mocked(messagePort.addEventListener).mock.calls.forEach(([, handler]) => {\n if (typeof handler === 'function') {\n handler(event);\n } else {\n handler.handleEvent(event);\n }\n });\n };\n\n const createFakeMessagePort = (): MessagePort =>\n createFakePartial({\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n postMessage: jest.fn(),\n start: jest.fn(),\n close: jest.fn(),\n });\n\n describe('start', () => {\n it('should start the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.start();\n\n expect(mockMessagePort.start).toHaveBeenCalled();\n });\n });\n\n describe('postMessage', () => {\n it('should post the given message', () => {\n const message: PortChannelMessage = {\n key: 'authentication-token-response',\n params: { token: 'foo' },\n };\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.postMessage(message);\n\n expect(mockMessagePort.postMessage).toHaveBeenCalledWith(message);\n });\n });\n\n describe('addMessagesListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessagesListener(listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessagesListener(callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('addMessageListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessageListener('authentication-token-changed', listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-changed', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('waitForMessage', () => {\n jest.useFakeTimers();\n\n const mockMessagePort = createFakeMessagePort();\n const mockMessage: PortChannelMessage = {\n key: 'authentication-token-response',\n params: {\n token: 'foo',\n },\n };\n const messageEvent = new MessageEvent('message', {\n data: mockMessage,\n ports: [],\n });\n let channel: DefaultPortChannel;\n let waitForMessagePromise: Promise;\n\n beforeEach(() => {\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n waitForMessagePromise = channel.waitForMessage(mockMessage.key);\n });\n\n describe('when expected message is received', () => {\n it('returns the received message', async () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(await waitForMessagePromise).toEqual(mockMessage);\n });\n\n it('removes the event listener after receiving the expected message', () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n });\n\n describe('when expected message is not received', () => {\n it('should reject with a timeout error', async () => {\n jest.advanceTimersByTime(WAIT_FOR_MESSAGE_TIMEOUT);\n\n await expect(waitForMessagePromise).rejects.toThrow(\/Channel timed out\/);\n });\n });\n });\n\n describe('dispose', () => {\n it('should close the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n\n channel.dispose();\n\n expect(mockMessagePort.close).toHaveBeenCalled();\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"20cb7319-3335-4d1f-b49d-0e1b6740a65d","name":"start","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('start', () => {\n it('should start the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.start();\n\n expect(mockMessagePort.start).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"e1ca57ba-c49b-41cb-9189-8704bfb09ac2","name":"postMessage","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('postMessage', () => {\n it('should post the given message', () => {\n const message: PortChannelMessage = {\n key: 'authentication-token-response',\n params: { token: 'foo' },\n };\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.postMessage(message);\n\n expect(mockMessagePort.postMessage).toHaveBeenCalledWith(message);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"6ec5899a-01a9-48ca-b691-33e2bfc075d8","name":"addMessagesListener","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('addMessagesListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessagesListener(listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessagesListener(callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"71d91910-dcac-407e-92bb-8f9b505ab253","name":"when receiving expected message key","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessagesListener(callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"69998047-ea3d-4dfb-9fcb-7ca293e62d9d","name":"when receiving a different message key","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"71547160-8b5e-44ec-9a51-dfdcc3d4b21e","name":"addMessageListener","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('addMessageListener', () => {\n let mockMessagePort: MessagePort;\n let channel: DefaultPortChannel;\n\n beforeEach(() => {\n mockMessagePort = createFakeMessagePort();\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n });\n\n it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessageListener('authentication-token-changed', listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n\n describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-changed', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n });\n\n describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8175ba47-17fd-4ad8-95cb-7dbd5f11fea7","name":"when receiving expected message key","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when receiving expected message key', () => {\n it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-changed', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ea64ca8f-4b35-4aad-a5ee-0197939bad0b","name":"when receiving a different message key","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when receiving a different message key', () => {\n it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"0f708007-5602-4763-b10f-5d8bf788dda4","name":"waitForMessage","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('waitForMessage', () => {\n jest.useFakeTimers();\n\n const mockMessagePort = createFakeMessagePort();\n const mockMessage: PortChannelMessage = {\n key: 'authentication-token-response',\n params: {\n token: 'foo',\n },\n };\n const messageEvent = new MessageEvent('message', {\n data: mockMessage,\n ports: [],\n });\n let channel: DefaultPortChannel;\n let waitForMessagePromise: Promise;\n\n beforeEach(() => {\n channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n waitForMessagePromise = channel.waitForMessage(mockMessage.key);\n });\n\n describe('when expected message is received', () => {\n it('returns the received message', async () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(await waitForMessagePromise).toEqual(mockMessage);\n });\n\n it('removes the event listener after receiving the expected message', () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n });\n\n describe('when expected message is not received', () => {\n it('should reject with a timeout error', async () => {\n jest.advanceTimersByTime(WAIT_FOR_MESSAGE_TIMEOUT);\n\n await expect(waitForMessagePromise).rejects.toThrow(\/Channel timed out\/);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"371f57bc-351b-47df-9ea3-423e8819904d","name":"when expected message is received","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when expected message is received', () => {\n it('returns the received message', async () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(await waitForMessagePromise).toEqual(mockMessage);\n });\n\n it('removes the event listener after receiving the expected message', () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"b31bb2a6-f885-44c7-a2a2-50961908a4d0","name":"when expected message is not received","imports":"[{'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('when expected message is not received', () => {\n it('should reject with a timeout error', async () => {\n jest.advanceTimersByTime(WAIT_FOR_MESSAGE_TIMEOUT);\n\n await expect(waitForMessagePromise).rejects.toThrow(\/Channel timed out\/);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"e1a42b4e-b0d8-48da-be4d-c21da4b9a9e3","name":"dispose","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"describe('dispose', () => {\n it('should close the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n\n channel.dispose();\n\n expect(mockMessagePort.close).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c471791f-3c05-4c68-81e1-e76384d7ed7f","name":"should start the message port","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('should start the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.start();\n\n expect(mockMessagePort.start).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"b1b6b054-45ce-4eb6-b325-1c9ae4d228a1","name":"should post the given message","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}, {'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('should post the given message', () => {\n const message: PortChannelMessage = {\n key: 'authentication-token-response',\n params: { token: 'foo' },\n };\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n channel.postMessage(message);\n\n expect(mockMessagePort.postMessage).toHaveBeenCalledWith(message);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"540c70f4-7f5c-4697-a6ec-99e7264610b6","name":"returns a disposable that allows removing event listener from message port","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessagesListener(listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"874f310a-f497-4e74-8c98-6d306a977dc8","name":"invokes the callback function","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessagesListener(callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"6a032f52-19c3-4f1a-961d-3ba1e8761ef9","name":"does not invoke the callback","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"20f3266a-e254-491f-afad-a4193992afa1","name":"returns a disposable that allows removing event listener from message port","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('returns a disposable that allows removing event listener from message port', () => {\n const listener = jest.fn();\n const disposable = channel.addMessageListener('authentication-token-changed', listener);\n\n disposable.dispose();\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1b4f0585-49a9-4639-8150-f2ff96ff9be1","name":"invokes the callback function","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('invokes the callback function', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-changed', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).toHaveBeenCalledWith({\n key: 'authentication-token-changed',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c2530e27-8373-4b09-bb58-544c9234a8ad","name":"does not invoke the callback","imports":"[{'import_name': ['PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('does not invoke the callback', () => {\n const callback = jest.fn();\n const event = new MessageEvent('message', {\n data: {\n key: 'authentication-token-changed',\n },\n });\n\n channel.addMessageListener('authentication-token-response', callback);\n\n invokeMessageEventListeners(mockMessagePort, event);\n\n expect(callback).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"363b8816-e5ff-48ae-93b5-ed1a1a9a1535","name":"returns the received message","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('returns the received message', async () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(await waitForMessagePromise).toEqual(mockMessage);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c7093018-a06f-4fb3-b2e4-0642e148491e","name":"removes the event listener after receiving the expected message","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('removes the event listener after receiving the expected message', () => {\n invokeMessageEventListeners(mockMessagePort, messageEvent);\n\n expect(mockMessagePort.removeEventListener).toHaveBeenCalledWith(\n 'message',\n jest.mocked(mockMessagePort.addEventListener).mock.calls[0][1],\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"fe148c19-88eb-4bc2-8b2e-fbd7ecf75090","name":"should reject with a timeout error","imports":"[{'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('should reject with a timeout error', async () => {\n jest.advanceTimersByTime(WAIT_FOR_MESSAGE_TIMEOUT);\n\n await expect(waitForMessagePromise).rejects.toThrow(\/Channel timed out\/);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"0f98b238-054f-47f2-9648-9c442d9c4695","name":"should close the message port","imports":"[{'import_name': ['DefaultPortChannel'], 'import_path': '.\/DefaultPortChannel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.test.ts","code":"it('should close the message port', () => {\n const mockMessagePort = createFakeMessagePort();\n const channel = new DefaultPortChannel({ name: 'auth-port', messagePort: mockMessagePort });\n\n channel.dispose();\n\n expect(mockMessagePort.close).toHaveBeenCalled();\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0128dbc6-7be1-4b22-b11a-e545c8e3968d","name":"DefaultPortChannel.ts","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}, {'import_name': ['PortChannel', 'PortChannelMessage', 'PortChannelMessageKey', 'PortName'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"import type { Disposable } from '@gitlab\/web-ide-types';\nimport { WAIT_FOR_MESSAGE_TIMEOUT } from '.\/constants';\nimport type { PortChannel, PortChannelMessage, PortChannelMessageKey, PortName } from '.\/types';\n\ninterface DefaultPortChannelConstructorOptions {\n name: PortName;\n messagePort: MessagePort;\n}\n\nexport class DefaultPortChannel implements PortChannel {\n readonly messagePort: MessagePort;\n\n readonly name: PortName;\n\n constructor({ name, messagePort }: DefaultPortChannelConstructorOptions) {\n this.messagePort = messagePort;\n this.name = name;\n }\n\n dispose() {\n this.messagePort.close();\n }\n\n start() {\n this.messagePort.start();\n }\n\n addMessagesListener(callback: (message: PortChannelMessage) => void): Disposable {\n const port = this.messagePort;\n const listener = (event: MessageEvent) => {\n const message = event.data;\n\n callback(message);\n };\n\n port.addEventListener('message', listener);\n\n return {\n dispose() {\n port.removeEventListener('message', listener);\n },\n };\n }\n\n addMessageListener(\n messageKey: PortChannelMessageKey,\n callback: (message: T) => void,\n ): Disposable {\n return this.addMessagesListener(message => {\n if (message.key === messageKey) {\n callback(message as T);\n }\n });\n }\n\n postMessage(message: PortChannelMessage): void {\n this.messagePort.postMessage(message);\n }\n\n waitForMessage(\n messageKey: PortChannelMessageKey,\n ): Promise {\n return new Promise((resolve, reject) => {\n const disposable = this.addMessageListener(messageKey, message => {\n resolve(message);\n disposable.dispose();\n });\n\n setTimeout(() => {\n disposable.dispose();\n reject(new Error(`Channel timed out while waiting for message ${messageKey}`));\n }, WAIT_FOR_MESSAGE_TIMEOUT);\n });\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"296f60a2-08b8-4e53-8a62-7cb996726275","name":"constructor","imports":"[{'import_name': ['PortChannel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"constructor({ name, messagePort }: DefaultPortChannelConstructorOptions) {\n this.messagePort = messagePort;\n this.name = name;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"09672981-8158-4eb1-97b0-ce105d5f3e32","name":"dispose","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"dispose() {\n this.messagePort.close();\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"10205658-33d7-42b4-bcd4-3d5352e71e5d","name":"start","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"start() {\n this.messagePort.start();\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8cf58974-55d7-4b5d-9f3a-aaf8677e7743","name":"addMessagesListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['PortChannel', 'PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"addMessagesListener(callback: (message: PortChannelMessage) => void): Disposable {\n const port = this.messagePort;\n const listener = (event: MessageEvent) => {\n const message = event.data;\n\n callback(message);\n };\n\n port.addEventListener('message', listener);\n\n return {\n dispose() {\n port.removeEventListener('message', listener);\n },\n };\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"75ee2669-fb84-403f-b481-d2d92ea48c44","name":"addMessageListener","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['PortChannel', 'PortChannelMessage', 'PortChannelMessageKey'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"addMessageListener(\n messageKey: PortChannelMessageKey,\n callback: (message: T) => void,\n ): Disposable {\n return this.addMessagesListener(message => {\n if (message.key === messageKey) {\n callback(message as T);\n }\n });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"523573a9-eba1-4440-b360-72d7f37784e0","name":"postMessage","imports":"[{'import_name': ['PortChannel', 'PortChannelMessage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"postMessage(message: PortChannelMessage): void {\n this.messagePort.postMessage(message);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"81f4ffd5-a5e3-4435-abca-eee2b210e3fd","name":"waitForMessage","imports":"[{'import_name': ['WAIT_FOR_MESSAGE_TIMEOUT'], 'import_path': '.\/constants'}, {'import_name': ['PortChannel', 'PortChannelMessage', 'PortChannelMessageKey'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/DefaultPortChannel.ts","code":"waitForMessage(\n messageKey: PortChannelMessageKey,\n ): Promise {\n return new Promise((resolve, reject) => {\n const disposable = this.addMessageListener(messageKey, message => {\n resolve(message);\n disposable.dispose();\n });\n\n setTimeout(() => {\n disposable.dispose();\n reject(new Error(`Channel timed out while waiting for message ${messageKey}`));\n }, WAIT_FOR_MESSAGE_TIMEOUT);\n });\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultPortChannel'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"62f4f92f-de59-4ed4-a186-6f72798dce04","name":"constants.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/constants.ts","code":"export const WAIT_FOR_MESSAGE_TIMEOUT = 10000;\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"b959a76a-13aa-49a7-80d3-877ca8eef1f4","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/index.ts","code":"export { DefaultCrossWindowChannel } from '.\/DefaultCrossWindowChannel';\nexport { DefaultPortChannel } from '.\/DefaultPortChannel';\nexport * from '.\/types';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"65291de2-a51e-482b-a6c7-0bf081b4eec8","name":"types.ts","imports":"[{'import_name': ['Disposable', 'ErrorType', 'TrackingEvent', 'WebIdeConfigLinks'], 'import_path': '@gitlab\/web-ide-types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/cross-origin-channel\/src\/types.ts","code":"import type {\n Disposable,\n ErrorType,\n TrackingEvent,\n WebIdeConfigLinks,\n} from '@gitlab\/web-ide-types';\n\ninterface BaseChannel extends Disposable {\n postMessage(message: Message): void;\n waitForMessage(messageKey: MessageKey): Promise;\n addMessageListener(\n messageKey: MessageKey,\n callback: (message: T) => void,\n ): Disposable;\n addMessagesListener(callback: (message: Message) => void): Disposable;\n}\n\nexport interface AuthenticationTokenRequestMessage {\n key: 'authentication-token-request';\n}\n\nexport interface AuthenticationTokenResponseMessage {\n key: 'authentication-token-response';\n params: {\n token: string;\n };\n}\n\nexport interface AuthenticationTokenChangedMessage {\n key: 'authentication-token-changed';\n}\n\nexport type PortChannelMessage =\n | AuthenticationTokenRequestMessage\n | AuthenticationTokenResponseMessage\n | AuthenticationTokenChangedMessage;\n\nexport type PortChannelMessageKey = PortChannelMessage['key'];\n\nexport interface PortChannel extends BaseChannel {\n readonly messagePort: MessagePort;\n start: () => void;\n}\n\nexport type PortName = 'auth-port';\n\nexport interface PortChannelRequestMessage {\n key: 'port-channel-request';\n params: {\n name: PortName;\n };\n}\n\nexport interface PortChannelResponseMessage {\n key: 'port-channel-response';\n params: {\n name: PortName;\n port: MessagePort;\n };\n}\n\nexport interface PortChannelResponseErrorMessage {\n key: 'port-channel-response-error';\n params: {\n name: PortName;\n error: string;\n };\n}\n\n\/**\n * Message sent to tell the parent window that the Web IDE is \"ready\".\n *\/\nexport interface ReadyMessage {\n key: 'ready';\n}\n\n\/**\n * Message sent to tell the parent window that an error occured.\n *\/\nexport interface ErrorMessage {\n key: 'error';\n params: {\n errorType: ErrorType;\n };\n}\n\nexport interface PreventUnloadMessage {\n key: 'prevent-unload';\n params: {\n shouldPrevent: boolean;\n };\n}\n\nexport interface WebIDETrackingMessage {\n key: 'web-ide-tracking';\n params: {\n event: TrackingEvent;\n };\n}\n\nexport interface UpdateWebIDEContextMessage {\n key: 'update-web-ide-context';\n params: {\n ref: string;\n projectPath: string;\n };\n}\n\nexport interface OpenURIMessage {\n key: 'open-uri';\n params: {\n uriKey: keyof WebIdeConfigLinks;\n };\n}\n\nexport interface SetHrefMessage {\n key: 'set-href';\n params: {\n href: string;\n };\n}\n\nexport interface WebIDEConfigRequestMessage {\n key: 'web-ide-config-request';\n}\n\nexport interface WebIDEConfigResponseMessage {\n key: 'web-ide-config-response';\n params: {\n config: string;\n };\n}\n\nexport type WindowChannelMessage =\n | PortChannelRequestMessage\n | PortChannelResponseMessage\n | PortChannelResponseErrorMessage\n | ReadyMessage\n | ErrorMessage\n | PreventUnloadMessage\n | WebIDETrackingMessage\n | UpdateWebIDEContextMessage\n | OpenURIMessage\n | SetHrefMessage\n | WebIDEConfigRequestMessage\n | WebIDEConfigResponseMessage;\n\nexport type WindowChannelMessageKey = WindowChannelMessage['key'];\n\nexport interface CrossWindowChannel\n extends BaseChannel {\n \/**\n * Requests a PortChannel from the remote origin. The remote\n * origin should've created a `PortChannel` using `createLocalPortChannel(name)`\n * first.\n * @param name\n *\/\n requestRemotePortChannel(name: PortName): Promise;\n \/**\n * Creates a PortChannel in the local origin. A remote origin\n * can request to communicate with this PortChannel by requesting\n * it using `requestRemotePortChannel(name)`.\n * @param name\n *\/\n createLocalPortChannel(name: PortName): PortChannel;\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7ed17798-ff04-42cf-b08a-32c5e190aa37","name":"vite.config.ts","imports":"[{'import_name': ['resolve'], 'import_path': 'path'}, {'import_name': ['defineConfig'], 'import_path': 'vite'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/config\/vite.config.ts","code":"import { resolve } from 'path';\nimport { defineConfig } from 'vite';\nimport vue from '@vitejs\/plugin-vue';\n\n\/\/ https:\/\/vitejs.dev\/config\/\nexport default defineConfig({\n plugins: [vue()],\n root: resolve(__dirname, '..\/src'),\n \/\/ why: Use relative URL's since this gets published to GitLab pages\n base: '.\/',\n build: {\n target: 'es2022',\n \/\/ why: The Makefile puts the web-ide self-hosted assets into this directory\n emptyOutDir: false,\n outDir: resolve(__dirname, '..\/dist'),\n rollupOptions: {\n input: [\n resolve(__dirname, '..\/src\/index.html'),\n resolve(__dirname, '..\/src\/oauth_callback.html'),\n ],\n },\n },\n});\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f78ca7cb-c910-4819-bc31-d55dee7774e0","name":"config.test.ts","imports":"[{'import_name': ['getBaseUrlFromLocation'], 'import_path': '.\/config'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.test.ts","code":"import { getBaseUrlFromLocation } from '.\/config';\n\ndescribe('.\/config', () => {\n describe('getBaseUrlFromLocation', () => {\n it.each`\n input | output\n ${'http:\/\/location:8000\/path\/to\/foo\/'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/path\/to\/foo\/index.html'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/'} | ${'http:\/\/location:8000\/web-ide\/public'}\n ${'http:\/\/location:8000\/index.html'} | ${'http:\/\/location:8000\/web-ide\/public'}\n `('with \"$input\", expects $output', ({ input, output }) => {\n \/\/ eslint-disable-next-line @typescript-eslint\/no-explicit-any\n (window as any).dom.reconfigure({ url: input });\n\n expect(getBaseUrlFromLocation()).toBe(output);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"079854c0-a6f3-4d88-a2e8-53d272e59d61","name":".\/config","imports":"[{'import_name': ['getBaseUrlFromLocation'], 'import_path': '.\/config'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.test.ts","code":"describe('.\/config', () => {\n describe('getBaseUrlFromLocation', () => {\n it.each`\n input | output\n ${'http:\/\/location:8000\/path\/to\/foo\/'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/path\/to\/foo\/index.html'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/'} | ${'http:\/\/location:8000\/web-ide\/public'}\n ${'http:\/\/location:8000\/index.html'} | ${'http:\/\/location:8000\/web-ide\/public'}\n `('with \"$input\", expects $output', ({ input, output }) => {\n \/\/ eslint-disable-next-line @typescript-eslint\/no-explicit-any\n (window as any).dom.reconfigure({ url: input });\n\n expect(getBaseUrlFromLocation()).toBe(output);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"17c4600b-d291-44e3-b1fb-73d855113238","name":"getBaseUrlFromLocation","imports":"[{'import_name': ['getBaseUrlFromLocation'], 'import_path': '.\/config'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.test.ts","code":"describe('getBaseUrlFromLocation', () => {\n it.each`\n input | output\n ${'http:\/\/location:8000\/path\/to\/foo\/'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/path\/to\/foo\/index.html'} | ${'http:\/\/location:8000\/path\/to\/foo\/web-ide\/public'}\n ${'http:\/\/location:8000\/'} | ${'http:\/\/location:8000\/web-ide\/public'}\n ${'http:\/\/location:8000\/index.html'} | ${'http:\/\/location:8000\/web-ide\/public'}\n `('with \"$input\", expects $output', ({ input, output }) => {\n \/\/ eslint-disable-next-line @typescript-eslint\/no-explicit-any\n (window as any).dom.reconfigure({ url: input });\n\n expect(getBaseUrlFromLocation()).toBe(output);\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0568eacf-b58a-4680-8edc-fee62a922a97","name":"config.ts","imports":"[{'import_name': ['ExtensionMarketplaceSettings'], 'import_path': '@gitlab\/web-ide-types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.ts","code":"import type { ExtensionMarketplaceSettings } from '@gitlab\/web-ide-types';\n\nexport const getBaseUrlFromLocation = () => {\n const newUrl = new URL('web-ide\/public', window.location.href);\n\n return newUrl.href;\n};\n\nexport const getRootUrlFromLocation = () => {\n const newUrl = new URL('\/', window.location.href);\n\n return newUrl.href;\n};\n\nexport const getOAuthCallbackUrl = () => {\n const url = new URL(window.location.href);\n const newUrl = new URL('oauth_callback.html', window.location.href);\n\n const username = url.searchParams.get('username');\n\n if (username) {\n newUrl.searchParams.set('username', username);\n }\n\n return newUrl.href;\n};\n\nexport const getSettingsContextHash = async (\n extensionMarketplaceSettings: ExtensionMarketplaceSettings | undefined,\n): Promise => {\n if (!extensionMarketplaceSettings?.enabled) return undefined;\n\n \/\/ Based on: https:\/\/gitlab.com\/gitlab-org\/gitlab\/-\/blob\/master\/lib\/web_ide\/settings_sync.rb#L6-15\n const { serviceUrl, itemUrl, resourceUrlTemplate } = extensionMarketplaceSettings.vscodeSettings;\n const key = `web_ide_${serviceUrl}_${itemUrl}_${resourceUrlTemplate}`;\n\n const encoder = new TextEncoder();\n const data = await encoder.encode(key);\n\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n\n \/\/ Return first 20 characters\n return hashHex.slice(0, 20);\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"7cfc7e5b-4ca7-4f77-8917-c48dbf8df78d","name":"getBaseUrlFromLocation","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.ts","code":"() => {\n const newUrl = new URL('web-ide\/public', window.location.href);\n\n return newUrl.href;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6fb6135d-9d7e-465b-8668-3d3f4b54d658","name":"getRootUrlFromLocation","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.ts","code":"() => {\n const newUrl = new URL('\/', window.location.href);\n\n return newUrl.href;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"96b62b2a-f7eb-42e1-9cc7-c867d8aa1c91","name":"getOAuthCallbackUrl","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.ts","code":"() => {\n const url = new URL(window.location.href);\n const newUrl = new URL('oauth_callback.html', window.location.href);\n\n const username = url.searchParams.get('username');\n\n if (username) {\n newUrl.searchParams.set('username', username);\n }\n\n return newUrl.href;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f10b4f32-b05b-4391-8e58-773791f0c393","name":"getSettingsContextHash","imports":"[{'import_name': ['ExtensionMarketplaceSettings'], 'import_path': '@gitlab\/web-ide-types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/config.ts","code":"async (\n extensionMarketplaceSettings: ExtensionMarketplaceSettings | undefined,\n): Promise => {\n if (!extensionMarketplaceSettings?.enabled) return undefined;\n\n \/\/ Based on: https:\/\/gitlab.com\/gitlab-org\/gitlab\/-\/blob\/master\/lib\/web_ide\/settings_sync.rb#L6-15\n const { serviceUrl, itemUrl, resourceUrlTemplate } = extensionMarketplaceSettings.vscodeSettings;\n const key = `web_ide_${serviceUrl}_${itemUrl}_${resourceUrlTemplate}`;\n\n const encoder = new TextEncoder();\n const data = await encoder.encode(key);\n\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');\n\n \/\/ Return first 20 characters\n return hashHex.slice(0, 20);\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"a74ecefb-9f1b-43e3-afea-057becca96d2","name":"configStorage.ts","imports":"[{'import_name': ['omit'], 'import_path': 'lodash'}, {'import_name': ['ExampleConfigPayload'], 'import_path': '.\/types'}, {'import_name': ['isExampleConfigPayload', 'SENSITIVE_KEYS'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/configStorage.ts","code":"import { omit } from 'lodash';\nimport type { ExampleConfigPayload } from '.\/types';\nimport { isExampleConfigPayload, SENSITIVE_KEYS } from '.\/types';\n\nconst STORAGE_KEY = 'gitlab.web-ide-example.config';\n\nconst cleanPayload = (payload: ExampleConfigPayload) => ({\n config: omit(payload.config, ...SENSITIVE_KEYS),\n});\n\nexport const saveConfig = (payloadUnclean: ExampleConfigPayload) => {\n try {\n const payload = cleanPayload(payloadUnclean);\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error('[gitlab-web-ide-example] Could not save user config!', e);\n }\n};\n\nexport const loadConfig = (): ExampleConfigPayload | null => {\n const savedJson = localStorage.getItem(STORAGE_KEY);\n\n if (!savedJson) {\n return null;\n }\n\n try {\n const savedObj = JSON.parse(savedJson);\n\n if (isExampleConfigPayload(savedObj)) {\n return savedObj;\n }\n\n return null;\n } catch {\n return null;\n }\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"352e58bb-97d6-4bef-bfe9-2a0e72aadef7","name":"cleanPayload","imports":"[{'import_name': ['omit'], 'import_path': 'lodash'}, {'import_name': ['ExampleConfigPayload'], 'import_path': '.\/types'}, {'import_name': ['SENSITIVE_KEYS'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/configStorage.ts","code":"(payload: ExampleConfigPayload) => ({\n config: omit(payload.config, ...SENSITIVE_KEYS),\n})","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ce92d86e-3c4d-4d63-93a8-d069de89ba5b","name":"saveConfig","imports":"[{'import_name': ['ExampleConfigPayload'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/configStorage.ts","code":"(payloadUnclean: ExampleConfigPayload) => {\n try {\n const payload = cleanPayload(payloadUnclean);\n\n localStorage.setItem(STORAGE_KEY, JSON.stringify(payload));\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error('[gitlab-web-ide-example] Could not save user config!', e);\n }\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bcd9a1ad-f17e-4132-b5f5-2b64a7077517","name":"loadConfig","imports":"[{'import_name': ['ExampleConfigPayload'], 'import_path': '.\/types'}, {'import_name': ['isExampleConfigPayload'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/configStorage.ts","code":"(): ExampleConfigPayload | null => {\n const savedJson = localStorage.getItem(STORAGE_KEY);\n\n if (!savedJson) {\n return null;\n }\n\n try {\n const savedObj = JSON.parse(savedJson);\n\n if (isExampleConfigPayload(savedObj)) {\n return savedObj;\n }\n\n return null;\n } catch {\n return null;\n }\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"c37b22d5-3c03-4506-995b-d3983c653d11","name":"index.ts","imports":"[{'import_name': ['createApp'], 'import_path': 'vue'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/index.ts","code":"import { createApp } from 'vue';\nimport App from '.\/components\/App.vue';\n\nconst root = document.getElementById('main');\nconst url = new URL(window.location.href);\nconst autostart = url.searchParams.get('autostart') === 'true';\n\nif (autostart) {\n url.searchParams.delete('autostart');\n window.history.replaceState({}, '', url);\n}\n\nif (!root) {\n throw new Error('#main element not found!');\n}\n\ncreateApp(App, { autostart }).mount(root);\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f461e199-69de-4d51-9865-2547a06ce2c9","name":"oauth_callback.ts","imports":"[{'import_name': ['oauthCallback'], 'import_path': '@gitlab\/web-ide'}, {'import_name': ['getOAuthCallbackUrl'], 'import_path': '.\/config'}, {'import_name': ['loadConfig'], 'import_path': '.\/configStorage'}, {'import_name': ['addParamsToOriginalUrl'], 'import_path': '.\/utils\/oauthHandshakeState'}, {'import_name': ['ExampleConfig'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/oauth_callback.ts","code":"import { oauthCallback } from '@gitlab\/web-ide';\nimport { getOAuthCallbackUrl } from '.\/config';\nimport { loadConfig } from '.\/configStorage';\nimport { addParamsToOriginalUrl } from '.\/utils\/oauthHandshakeState';\nimport type { ExampleConfig } from '.\/types';\n\nconst savedConfig = loadConfig();\n\nif (!savedConfig) {\n throw new Error('Could not find client config!');\n}\n\nconst url = new URL(document.location.href);\nconst config = savedConfig.config as ExampleConfig;\n\naddParamsToOriginalUrl(config.clientId, {\n autostart: 'true',\n});\n\n\/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\noauthCallback({\n gitlabUrl: config.gitlabUrl,\n auth: {\n type: 'oauth',\n callbackUrl: getOAuthCallbackUrl(),\n clientId: config.clientId,\n \/\/ why: Let's use regular refreshToken since we can't silently reauth in the example app\n protectRefreshToken: false,\n },\n username: url.searchParams.get('username') || undefined,\n});\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0fde4c56-d432-4630-abd5-77c5cf015afa","name":"types.ts","imports":"[{'import_name': ['AuthType', 'ExtensionMarketplaceDisabledReason'], 'import_path': '@gitlab\/web-ide-types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/types.ts","code":"import type { AuthType, ExtensionMarketplaceDisabledReason } from '@gitlab\/web-ide-types';\n\nexport interface ExampleConfig {\n gitlabUrl: string;\n projectPath: string;\n gitRef: string;\n codeSuggestionsEnabled: boolean;\n authType?: AuthType;\n gitlabToken: string;\n clientId: string;\n telemetryEnabled: boolean;\n extensionMarketplaceEnabled: boolean;\n settingsContextHash: string | undefined;\n extensionMarketplaceDisabledReason: ExtensionMarketplaceDisabledReason | undefined;\n languageServerEnabled: boolean;\n}\n\nexport type ExampleConfigKeys = keyof ExampleConfig;\n\nexport const SENSITIVE_KEYS: ExampleConfigKeys[] = ['gitlabToken'];\n\n\/**\n * Payload object that represents the user's settings and is saved\/loaded from local storage\n *\/\nexport interface ExampleConfigPayload {\n config: ExampleConfig;\n}\n\n\/\/ eslint-disable-next-line @typescript-eslint\/no-explicit-any\nexport const isExampleConfigPayload = (obj: any): obj is ExampleConfigPayload =>\n obj && typeof obj === 'object' && typeof obj.config === 'object';\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b3f5442f-184e-490c-86b5-114e803ef477","name":"isExampleConfigPayload","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/types.ts","code":"(obj: any): obj is ExampleConfigPayload =>\n obj && typeof obj === 'object' && typeof obj.config === 'object'","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"22adfbab-31a7-469e-8080-4be9eb7d7062","name":"oauthHandshakeState.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/utils\/oauthHandshakeState.ts","code":"function getHandshakeStateKey(clientId: string) {\n return `gitlab\/web-ide\/oauth\/${clientId}\/handshake`;\n}\n\n\/\/ PLEASE NOTE: This approach violates the encapsulate of the Web IDE\n\/\/ but we're justifying it here since this is developer tooling.\n\/\/ https:\/\/gitlab.com\/gitlab-org\/gitlab-web-ide\/-\/merge_requests\/259#note_1643865691\nexport function getHandshakeState(clientId: string) {\n const handshakeKey = getHandshakeStateKey(clientId);\n const handshakeStateRaw = localStorage.getItem(handshakeKey);\n\n if (!handshakeStateRaw) {\n return null;\n }\n\n return JSON.parse(atob(handshakeStateRaw));\n}\n\nexport function setHandshakeState(clientId: string, value: unknown) {\n const handshakeKey = getHandshakeStateKey(clientId);\n const handshakeStateRaw = btoa(JSON.stringify(value));\n\n localStorage.setItem(handshakeKey, handshakeStateRaw);\n}\n\nexport function addParamsToOriginalUrl(clientId: string, params: Record) {\n try {\n const handshakeState = getHandshakeState(clientId);\n const originalUrl = new URL(handshakeState.originalUrl);\n Object.entries(params).forEach(([key, value]) => {\n originalUrl.searchParams.set(key, value);\n });\n handshakeState.originalUrl = originalUrl.href;\n\n setHandshakeState(clientId, handshakeState);\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error('Failed to adjust originalUrl in handshake state!', e);\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6fffafde-96ad-4186-aaee-93bbd0f5e756","name":"getHandshakeStateKey","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/utils\/oauthHandshakeState.ts","code":"function getHandshakeStateKey(clientId: string) {\n return `gitlab\/web-ide\/oauth\/${clientId}\/handshake`;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"cfe7094c-0350-4e10-aa8c-048cdecbf7c2","name":"getHandshakeState","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/utils\/oauthHandshakeState.ts","code":"function getHandshakeState(clientId: string) {\n const handshakeKey = getHandshakeStateKey(clientId);\n const handshakeStateRaw = localStorage.getItem(handshakeKey);\n\n if (!handshakeStateRaw) {\n return null;\n }\n\n return JSON.parse(atob(handshakeStateRaw));\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"401fca57-92f5-44c6-9a08-59d31f9dbd50","name":"setHandshakeState","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/utils\/oauthHandshakeState.ts","code":"function setHandshakeState(clientId: string, value: unknown) {\n const handshakeKey = getHandshakeStateKey(clientId);\n const handshakeStateRaw = btoa(JSON.stringify(value));\n\n localStorage.setItem(handshakeKey, handshakeStateRaw);\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8bbaeedd-1392-4ea7-b9a5-8aacde868461","name":"addParamsToOriginalUrl","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/src\/utils\/oauthHandshakeState.ts","code":"function addParamsToOriginalUrl(clientId: string, params: Record) {\n try {\n const handshakeState = getHandshakeState(clientId);\n const originalUrl = new URL(handshakeState.originalUrl);\n Object.entries(params).forEach(([key, value]) => {\n originalUrl.searchParams.set(key, value);\n });\n handshakeState.originalUrl = originalUrl.href;\n\n setHandshakeState(clientId, handshakeState);\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error('Failed to adjust originalUrl in handshake state!', e);\n }\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f8560840-323e-4588-a14f-a62d6ae5c11e","name":"vue-shim.d.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/example\/vue-shim.d.ts","code":"declare module '*.vue' {\n import type { ComputedOptions, MethodOptions } from 'vue';\n import { Component } from 'vue';\n\n export default Component();\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"69056a3f-e395-45df-bc8a-7643821e328d","name":"DefaultAuthHeadersProvider.test.ts","imports":"[{'import_name': ['DefaultAuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['createOAuthHeadersProvider', 'createPrivateTokenHeadersProvider'], 'import_path': '.\/DefaultAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.test.ts","code":"import { DefaultAuthProvider } from '@gitlab\/gitlab-api-client';\n\nimport {\n createOAuthHeadersProvider,\n createPrivateTokenHeadersProvider,\n} from '.\/DefaultAuthHeadersProvider';\n\nconst TEST_AUTH_PROVIDER = new DefaultAuthProvider('test-token');\n\ndescribe('DefaultAuthHeadersProvider', () => {\n describe.each`\n desc | factory | expectation\n ${'createOAuthHeadersProvider'} | ${() => createOAuthHeadersProvider(TEST_AUTH_PROVIDER)} | ${{ Authorization: 'Bearer test-token' }}\n ${'createPrivateTokenHeadersProvider'} | ${() => createPrivateTokenHeadersProvider(TEST_AUTH_PROVIDER)} | ${{ 'PRIVATE-TOKEN': 'test-token' }}\n `('$desc', ({ factory, expectation }) => {\n it('creates a headers provider that returns expected headers', async () => {\n const authHeadersProvider = factory();\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(expectation);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"6232c82e-b922-4cce-9166-86dc55f16bab","name":"DefaultAuthHeadersProvider","imports":"[{'import_name': ['createOAuthHeadersProvider', 'createPrivateTokenHeadersProvider'], 'import_path': '.\/DefaultAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.test.ts","code":"describe('DefaultAuthHeadersProvider', () => {\n describe.each`\n desc | factory | expectation\n ${'createOAuthHeadersProvider'} | ${() => createOAuthHeadersProvider(TEST_AUTH_PROVIDER)} | ${{ Authorization: 'Bearer test-token' }}\n ${'createPrivateTokenHeadersProvider'} | ${() => createPrivateTokenHeadersProvider(TEST_AUTH_PROVIDER)} | ${{ 'PRIVATE-TOKEN': 'test-token' }}\n `('$desc', ({ factory, expectation }) => {\n it('creates a headers provider that returns expected headers', async () => {\n const authHeadersProvider = factory();\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(expectation);\n });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1432d5fc-6cc3-4735-9cb4-a0759d2b9ca2","name":"creates a headers provider that returns expected headers","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.test.ts","code":"it('creates a headers provider that returns expected headers', async () => {\n const authHeadersProvider = factory();\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(expectation);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d93c96e5-b9fe-4cfc-9d49-3b2eefd06331","name":"DefaultAuthHeadersProvider.ts","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"import type { AuthHeadersProvider, AuthProvider } from '@gitlab\/gitlab-api-client';\n\nconst oauthTokenAsHeaders = (token: string) => ({\n Authorization: `Bearer ${token}`,\n});\n\nconst accessTokenAsHeaders = (token: string) => ({\n 'PRIVATE-TOKEN': token,\n});\n\nclass DefaultAuthHeadersProvider implements AuthHeadersProvider {\n readonly #asHeaders: (token: string) => Record;\n\n readonly #authProvider: AuthProvider;\n\n constructor(authProvider: AuthProvider, asHeaders: (token: string) => Record) {\n this.#asHeaders = asHeaders;\n this.#authProvider = authProvider;\n }\n\n async getHeaders(): Promise> {\n const token = await this.#authProvider.getToken();\n\n return this.#asHeaders(token);\n }\n}\n\nexport const createOAuthHeadersProvider = (authProvider: AuthProvider) =>\n new DefaultAuthHeadersProvider(authProvider, oauthTokenAsHeaders);\n\nexport const createPrivateTokenHeadersProvider = (authProvider: AuthProvider) =>\n new DefaultAuthHeadersProvider(authProvider, accessTokenAsHeaders);\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"7cd3fc0b-74c1-4bc9-8f0c-4aef1b0e8b7a","name":"oauthTokenAsHeaders","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"(token: string) => ({\n Authorization: `Bearer ${token}`,\n})","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"536ae500-73a7-45b6-a962-9d170906832a","name":"accessTokenAsHeaders","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"(token: string) => ({\n 'PRIVATE-TOKEN': token,\n})","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e3019a0c-a7ca-4314-b00e-d7520b69269b","name":"constructor","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"constructor(authProvider: AuthProvider, asHeaders: (token: string) => Record) {\n this.#asHeaders = asHeaders;\n this.#authProvider = authProvider;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultAuthHeadersProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f79c96ee-cd7c-4433-ba76-78a2b853a9e2","name":"getHeaders","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"async getHeaders(): Promise> {\n const token = await this.#authProvider.getToken();\n\n return this.#asHeaders(token);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultAuthHeadersProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"022cd307-d247-47b4-8550-3e3fb53b0beb","name":"createOAuthHeadersProvider","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"(authProvider: AuthProvider) =>\n new DefaultAuthHeadersProvider(authProvider, oauthTokenAsHeaders)","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"57d4a0ca-eb0f-4ffb-bfd3-43318a3e3071","name":"createPrivateTokenHeadersProvider","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/DefaultAuthHeadersProvider.ts","code":"(authProvider: AuthProvider) =>\n new DefaultAuthHeadersProvider(authProvider, accessTokenAsHeaders)","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"066a68d9-f839-4e34-864e-63d4e17b0a41","name":"PortChannelAuthProvider.test.ts","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}, {'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"import type { PortChannel } from '@gitlab\/cross-origin-channel';\nimport { createFakePartial } from '@gitlab\/utils-test';\nimport { PortChannelAuthProvider } from '.\/PortChannelAuthProvider';\n\ndescribe('PortChannelAuthProvider', () => {\n let portChannelAuthProvider: PortChannelAuthProvider;\n let fakePortChannel: PortChannel;\n let onTokenChange: jest.Mock;\n\n beforeEach(() => {\n fakePortChannel = createFakePartial({\n addMessageListener: jest.fn(),\n waitForMessage: jest.fn(),\n postMessage: jest.fn(),\n start: jest.fn(),\n });\n onTokenChange = jest.fn();\n portChannelAuthProvider = new PortChannelAuthProvider({\n portChannel: fakePortChannel,\n onTokenChange,\n });\n });\n\n it('starts port channel', () => {\n expect(fakePortChannel.start).toHaveBeenCalledTimes(1);\n });\n\n describe('when port channel receives authentication-token-changed message', () => {\n beforeEach(() => {\n jest.mocked(fakePortChannel.addMessageListener).mock.calls[0][1]({\n key: 'authentication-token-changed',\n });\n });\n\n it('invokes onTokenChange callback', () => {\n expect(onTokenChange).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('getToken', () => {\n let tokenPromise: Promise;\n\n beforeEach(() => {\n jest.mocked(fakePortChannel.waitForMessage).mockResolvedValueOnce({\n params: { token: 'foo' },\n key: 'authentication-token-response',\n });\n tokenPromise = portChannelAuthProvider.getToken();\n });\n\n it('posts authentication-token-request message', () => {\n expect(fakePortChannel.postMessage).toHaveBeenCalledWith({\n key: 'authentication-token-request',\n });\n });\n\n it('returns token included in the authentication-token-response', async () => {\n expect(await tokenPromise).toBe('foo');\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"259d658a-6028-4e78-9d4e-b83b4ee6a516","name":"PortChannelAuthProvider","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}, {'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"describe('PortChannelAuthProvider', () => {\n let portChannelAuthProvider: PortChannelAuthProvider;\n let fakePortChannel: PortChannel;\n let onTokenChange: jest.Mock;\n\n beforeEach(() => {\n fakePortChannel = createFakePartial({\n addMessageListener: jest.fn(),\n waitForMessage: jest.fn(),\n postMessage: jest.fn(),\n start: jest.fn(),\n });\n onTokenChange = jest.fn();\n portChannelAuthProvider = new PortChannelAuthProvider({\n portChannel: fakePortChannel,\n onTokenChange,\n });\n });\n\n it('starts port channel', () => {\n expect(fakePortChannel.start).toHaveBeenCalledTimes(1);\n });\n\n describe('when port channel receives authentication-token-changed message', () => {\n beforeEach(() => {\n jest.mocked(fakePortChannel.addMessageListener).mock.calls[0][1]({\n key: 'authentication-token-changed',\n });\n });\n\n it('invokes onTokenChange callback', () => {\n expect(onTokenChange).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('getToken', () => {\n let tokenPromise: Promise;\n\n beforeEach(() => {\n jest.mocked(fakePortChannel.waitForMessage).mockResolvedValueOnce({\n params: { token: 'foo' },\n key: 'authentication-token-response',\n });\n tokenPromise = portChannelAuthProvider.getToken();\n });\n\n it('posts authentication-token-request message', () => {\n expect(fakePortChannel.postMessage).toHaveBeenCalledWith({\n key: 'authentication-token-request',\n });\n });\n\n it('returns token included in the authentication-token-response', async () => {\n expect(await tokenPromise).toBe('foo');\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"e79caddf-aac2-4636-970b-3f91bedaa077","name":"when port channel receives authentication-token-changed message","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"describe('when port channel receives authentication-token-changed message', () => {\n beforeEach(() => {\n jest.mocked(fakePortChannel.addMessageListener).mock.calls[0][1]({\n key: 'authentication-token-changed',\n });\n });\n\n it('invokes onTokenChange callback', () => {\n expect(onTokenChange).toHaveBeenCalledTimes(1);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ca5f5d57-9bb6-4457-a921-caaa6a1a2f55","name":"getToken","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"describe('getToken', () => {\n let tokenPromise: Promise;\n\n beforeEach(() => {\n jest.mocked(fakePortChannel.waitForMessage).mockResolvedValueOnce({\n params: { token: 'foo' },\n key: 'authentication-token-response',\n });\n tokenPromise = portChannelAuthProvider.getToken();\n });\n\n it('posts authentication-token-request message', () => {\n expect(fakePortChannel.postMessage).toHaveBeenCalledWith({\n key: 'authentication-token-request',\n });\n });\n\n it('returns token included in the authentication-token-response', async () => {\n expect(await tokenPromise).toBe('foo');\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"6e39808b-946d-468a-b20f-4964ed50ca9f","name":"starts port channel","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"it('starts port channel', () => {\n expect(fakePortChannel.start).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1c9a92b6-ea1f-4bc8-8397-8fc5c56d443a","name":"invokes onTokenChange callback","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"it('invokes onTokenChange callback', () => {\n expect(onTokenChange).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"515f727e-5b0e-4e62-b0f5-071724a5bc18","name":"posts authentication-token-request message","imports":"[{'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"it('posts authentication-token-request message', () => {\n expect(fakePortChannel.postMessage).toHaveBeenCalledWith({\n key: 'authentication-token-request',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"cb1e4022-1a38-4640-9dae-0827d05a2f70","name":"returns token included in the authentication-token-response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.test.ts","code":"it('returns token included in the authentication-token-response', async () => {\n expect(await tokenPromise).toBe('foo');\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"a98eb8be-8bf3-4414-8c13-7f0d87ff6a4e","name":"PortChannelAuthProvider.ts","imports":"[{'import_name': ['Disposable'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['AuthenticationTokenResponseMessage', 'PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.ts","code":"import type { Disposable } from '@gitlab\/web-ide-types';\nimport type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport type { AuthenticationTokenResponseMessage, PortChannel } from '@gitlab\/cross-origin-channel';\n\ntype OnTokenChange = () => void;\n\ninterface PortChannelAuthProviderConstructorOptions {\n portChannel: PortChannel;\n onTokenChange?: OnTokenChange;\n}\n\nexport class PortChannelAuthProvider implements AuthProvider, Disposable {\n readonly #portChannel: PortChannel;\n\n readonly #onTokenChange?: OnTokenChange;\n\n readonly #disposable: Disposable;\n\n constructor({ portChannel, onTokenChange }: PortChannelAuthProviderConstructorOptions) {\n this.#portChannel = portChannel;\n this.#onTokenChange = onTokenChange;\n\n this.#disposable = this.#portChannel.addMessageListener('authentication-token-changed', () => {\n this.#onTokenChange?.();\n });\n\n this.#portChannel.start();\n }\n\n dispose() {\n this.#disposable.dispose();\n }\n\n async getToken(): Promise {\n this.#portChannel.postMessage({ key: 'authentication-token-request' });\n const message = await this.#portChannel.waitForMessage(\n 'authentication-token-response',\n );\n\n return message.params.token;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"c9686491-3f96-493a-b9ca-ad05f5c625f4","name":"constructor","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.ts","code":"constructor({ portChannel, onTokenChange }: PortChannelAuthProviderConstructorOptions) {\n this.#portChannel = portChannel;\n this.#onTokenChange = onTokenChange;\n\n this.#disposable = this.#portChannel.addMessageListener('authentication-token-changed', () => {\n this.#onTokenChange?.();\n });\n\n this.#portChannel.start();\n }","parent":"{'type': 'class_declaration', 'name': 'PortChannelAuthProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d63b15fd-8087-4af2-8d2a-ddbb6c3b935d","name":"dispose","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.ts","code":"dispose() {\n this.#disposable.dispose();\n }","parent":"{'type': 'class_declaration', 'name': 'PortChannelAuthProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f00f6416-8d55-4ef9-918f-9236ff106261","name":"getToken","imports":"[{'import_name': ['AuthenticationTokenResponseMessage'], 'import_path': '@gitlab\/cross-origin-channel'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/PortChannelAuthProvider.ts","code":"async getToken(): Promise {\n this.#portChannel.postMessage({ key: 'authentication-token-request' });\n const message = await this.#portChannel.waitForMessage(\n 'authentication-token-response',\n );\n\n return message.params.token;\n }","parent":"{'type': 'class_declaration', 'name': 'PortChannelAuthProvider'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"cb26843a-2bc7-49c9-bd8f-5d696370ec39","name":"createGitLabClient.test.ts","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['createFakePartial', 'createWebIdeExtensionConfig'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['createGitLabClient'], 'import_path': '.\/createGitLabClient'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.test.ts","code":"import type { AuthHeadersProvider, AuthProvider } from '@gitlab\/gitlab-api-client';\nimport { DefaultGitLabClient } from '@gitlab\/gitlab-api-client';\nimport { createFakePartial, createWebIdeExtensionConfig } from '@gitlab\/utils-test';\nimport { createGitLabClient } from '.\/createGitLabClient';\nimport { getAuthHeadersProvider } from '.\/getAuthHeadersProvider';\n\njest.mock('@gitlab\/gitlab-api-client');\njest.mock('.\/getAuthHeadersProvider');\n\nconst TEST_CONFIG = {\n ...createWebIdeExtensionConfig(),\n httpHeaders: {\n 'X-Test-Header': 'test-header-value',\n },\n};\nconst TEST_AUTH_PROVIDER = createFakePartial({});\nconst TEST_AUTH_HEADERS_PROVIDER = createFakePartial({});\n\ndescribe('createGitLabClient', () => {\n let subject: DefaultGitLabClient;\n\n beforeEach(() => {\n jest.mocked(getAuthHeadersProvider).mockReturnValue(TEST_AUTH_HEADERS_PROVIDER);\n });\n\n it('creates a DefaultGitLabClient', () => {\n expect(DefaultGitLabClient).not.toHaveBeenCalled();\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(subject).toBeInstanceOf(DefaultGitLabClient);\n expect(DefaultGitLabClient).toHaveBeenCalledTimes(1);\n expect(DefaultGitLabClient).toHaveBeenCalledWith({\n auth: TEST_AUTH_HEADERS_PROVIDER,\n baseUrl: TEST_CONFIG.gitlabUrl,\n httpHeaders: TEST_CONFIG.httpHeaders,\n });\n });\n\n it('calls getAuthHeadersProvider headers', () => {\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(0);\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(1);\n expect(getAuthHeadersProvider).toHaveBeenCalledWith(TEST_CONFIG.auth?.type, TEST_AUTH_PROVIDER);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"50b94e2a-813d-498f-90d2-89abb997b4c5","name":"createGitLabClient","imports":"[{'import_name': ['AuthHeadersProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['createGitLabClient'], 'import_path': '.\/createGitLabClient'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.test.ts","code":"describe('createGitLabClient', () => {\n let subject: DefaultGitLabClient;\n\n beforeEach(() => {\n jest.mocked(getAuthHeadersProvider).mockReturnValue(TEST_AUTH_HEADERS_PROVIDER);\n });\n\n it('creates a DefaultGitLabClient', () => {\n expect(DefaultGitLabClient).not.toHaveBeenCalled();\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(subject).toBeInstanceOf(DefaultGitLabClient);\n expect(DefaultGitLabClient).toHaveBeenCalledTimes(1);\n expect(DefaultGitLabClient).toHaveBeenCalledWith({\n auth: TEST_AUTH_HEADERS_PROVIDER,\n baseUrl: TEST_CONFIG.gitlabUrl,\n httpHeaders: TEST_CONFIG.httpHeaders,\n });\n });\n\n it('calls getAuthHeadersProvider headers', () => {\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(0);\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(1);\n expect(getAuthHeadersProvider).toHaveBeenCalledWith(TEST_CONFIG.auth?.type, TEST_AUTH_PROVIDER);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"fa21f043-b3b9-4899-b3d0-b6218ff15d2b","name":"creates a DefaultGitLabClient","imports":"[{'import_name': ['DefaultGitLabClient'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['createGitLabClient'], 'import_path': '.\/createGitLabClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.test.ts","code":"it('creates a DefaultGitLabClient', () => {\n expect(DefaultGitLabClient).not.toHaveBeenCalled();\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(subject).toBeInstanceOf(DefaultGitLabClient);\n expect(DefaultGitLabClient).toHaveBeenCalledTimes(1);\n expect(DefaultGitLabClient).toHaveBeenCalledWith({\n auth: TEST_AUTH_HEADERS_PROVIDER,\n baseUrl: TEST_CONFIG.gitlabUrl,\n httpHeaders: TEST_CONFIG.httpHeaders,\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c8613549-4fd2-4f07-a5f7-72645218fa63","name":"calls getAuthHeadersProvider headers","imports":"[{'import_name': ['AuthHeadersProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['createGitLabClient'], 'import_path': '.\/createGitLabClient'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.test.ts","code":"it('calls getAuthHeadersProvider headers', () => {\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(0);\n\n subject = createGitLabClient(TEST_CONFIG, TEST_AUTH_PROVIDER);\n\n expect(getAuthHeadersProvider).toHaveBeenCalledTimes(1);\n expect(getAuthHeadersProvider).toHaveBeenCalledWith(TEST_CONFIG.auth?.type, TEST_AUTH_PROVIDER);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"8092067a-7235-4b46-a6e0-97c622ae99b6","name":"createGitLabClient.ts","imports":"[{'import_name': ['DefaultGitLabClient'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['WebIdeConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.ts","code":"import { DefaultGitLabClient } from '@gitlab\/gitlab-api-client';\nimport type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport type { WebIdeConfig } from '@gitlab\/web-ide-types';\nimport { getAuthHeadersProvider } from '.\/getAuthHeadersProvider';\n\nexport const createGitLabClient = (\n config: WebIdeConfig,\n auth?: AuthProvider,\n): DefaultGitLabClient =>\n new DefaultGitLabClient({\n baseUrl: config.gitlabUrl,\n auth: getAuthHeadersProvider(config.auth?.type, auth),\n httpHeaders: config.httpHeaders,\n });\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9c63fd05-c1ef-4dc1-9940-60bf5b3f5c8c","name":"createGitLabClient","imports":"[{'import_name': ['DefaultGitLabClient'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['WebIdeConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/createGitLabClient.ts","code":"(\n config: WebIdeConfig,\n auth?: AuthProvider,\n): DefaultGitLabClient =>\n new DefaultGitLabClient({\n baseUrl: config.gitlabUrl,\n auth: getAuthHeadersProvider(config.auth?.type, auth),\n httpHeaders: config.httpHeaders,\n })","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"6d30cb89-e796-4643-8cf9-23537078aa13","name":"getAuthHeadersProvider.test.ts","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthHeadersProvider.test.ts","code":"import type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport { getAuthHeadersProvider } from '.\/getAuthHeadersProvider';\n\nconst TEST_AUTH_PROVIDER: AuthProvider = {\n getToken() {\n return Promise.resolve('test-token');\n },\n};\n\ndescribe('getAuthHeadersProvider', () => {\n it.each`\n desc | authType | auth | expected\n ${'with no authType'} | ${undefined} | ${TEST_AUTH_PROVIDER} | ${undefined}\n ${'with no auth'} | ${'oauth'} | ${undefined} | ${undefined}\n ${'with oauth authType'} | ${'oauth'} | ${TEST_AUTH_PROVIDER} | ${{ Authorization: 'Bearer test-token' }}\n ${'with token authType'} | ${'token'} | ${TEST_AUTH_PROVIDER} | ${{ 'PRIVATE-TOKEN': 'test-token' }}\n `(\n '$desc, returns auth headers provider that gives $expected',\n async ({ authType, auth, expected }) => {\n const authHeadersProvider = getAuthHeadersProvider(authType, auth);\n\n const result = await authHeadersProvider?.getHeaders();\n\n expect(result).toEqual(expected);\n },\n );\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"4f86ea0e-ec4d-42f6-8ef4-800326e214e4","name":"getAuthHeadersProvider","imports":"[{'import_name': ['getAuthHeadersProvider'], 'import_path': '.\/getAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthHeadersProvider.test.ts","code":"describe('getAuthHeadersProvider', () => {\n it.each`\n desc | authType | auth | expected\n ${'with no authType'} | ${undefined} | ${TEST_AUTH_PROVIDER} | ${undefined}\n ${'with no auth'} | ${'oauth'} | ${undefined} | ${undefined}\n ${'with oauth authType'} | ${'oauth'} | ${TEST_AUTH_PROVIDER} | ${{ Authorization: 'Bearer test-token' }}\n ${'with token authType'} | ${'token'} | ${TEST_AUTH_PROVIDER} | ${{ 'PRIVATE-TOKEN': 'test-token' }}\n `(\n '$desc, returns auth headers provider that gives $expected',\n async ({ authType, auth, expected }) => {\n const authHeadersProvider = getAuthHeadersProvider(authType, auth);\n\n const result = await authHeadersProvider?.getHeaders();\n\n expect(result).toEqual(expected);\n },\n );\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"58881e02-f8b7-458d-b494-39562d998044","name":"getAuthHeadersProvider.ts","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['AuthType'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['createOAuthHeadersProvider', 'createPrivateTokenHeadersProvider'], 'import_path': '.\/DefaultAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthHeadersProvider.ts","code":"import type { AuthHeadersProvider, AuthProvider } from '@gitlab\/gitlab-api-client';\nimport type { AuthType } from '@gitlab\/web-ide-types';\n\nimport {\n createOAuthHeadersProvider,\n createPrivateTokenHeadersProvider,\n} from '.\/DefaultAuthHeadersProvider';\n\n\/\/ https:\/\/www.typescriptlang.org\/docs\/handbook\/unions-and-intersections.html#union-exhaustiveness-checking\nfunction assertNever(x: never): never {\n throw new Error(`assertNever - Unexpected object: ${x}`);\n}\n\nexport const getAuthHeadersProvider = (\n authType?: AuthType,\n auth?: AuthProvider,\n): AuthHeadersProvider | undefined => {\n \/\/ note: !auth implies !config.auth, but I'm checking for both to make TS happy\n if (!auth || !authType) {\n return undefined;\n }\n\n switch (authType) {\n case 'oauth':\n return createOAuthHeadersProvider(auth);\n case 'token':\n return createPrivateTokenHeadersProvider(auth);\n default:\n return assertNever(authType);\n }\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"0847c35c-15a0-4eba-a36b-df7c98b65d5c","name":"assertNever","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthHeadersProvider.ts","code":"function assertNever(x: never): never {\n throw new Error(`assertNever - Unexpected object: ${x}`);\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"59a20ae3-0903-4597-8adb-5da370f50a84","name":"getAuthHeadersProvider","imports":"[{'import_name': ['AuthHeadersProvider', 'AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['AuthType'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['createOAuthHeadersProvider', 'createPrivateTokenHeadersProvider'], 'import_path': '.\/DefaultAuthHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthHeadersProvider.ts","code":"(\n authType?: AuthType,\n auth?: AuthProvider,\n): AuthHeadersProvider | undefined => {\n \/\/ note: !auth implies !config.auth, but I'm checking for both to make TS happy\n if (!auth || !authType) {\n return undefined;\n }\n\n switch (authType) {\n case 'oauth':\n return createOAuthHeadersProvider(auth);\n case 'token':\n return createPrivateTokenHeadersProvider(auth);\n default:\n return assertNever(authType);\n }\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"fdac78c1-358f-449d-a61e-b3cfcf744539","name":"getAuthProvider.test.ts","imports":"[{'import_name': ['createConfig', 'createFakeCrossWindowChannel', 'createFakePartial', 'useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['AuthConfig', 'OAuthConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['DefaultOAuthClient', 'setupAutoRefresh'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}, {'import_name': ['DefaultAuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"import {\n createConfig,\n createFakeCrossWindowChannel,\n createFakePartial,\n useFakeBroadcastChannel,\n} from '@gitlab\/utils-test';\nimport type { AuthConfig, OAuthConfig } from '@gitlab\/web-ide-types';\nimport { DefaultOAuthClient, setupAutoRefresh } from '@gitlab\/oauth-client';\nimport type { PortChannel } from '@gitlab\/cross-origin-channel';\nimport { DefaultAuthProvider } from '@gitlab\/gitlab-api-client';\nimport { getAuthProvider } from '.\/getAuthProvider';\nimport { PortChannelAuthProvider } from '.\/PortChannelAuthProvider';\n\njest.mock('@gitlab\/oauth-client\/src\/OAuthClient');\njest.mock('@gitlab\/oauth-client\/src\/setupAutoRefresh');\n\nconst TEST_TOKEN_AUTH: AuthConfig = {\n type: 'token',\n token: 'lorem-ipsum-dolar',\n};\n\nconst TEST_OAUTH_AUTH: OAuthConfig = {\n type: 'oauth',\n callbackUrl: 'https:\/\/example.com\/callback_url',\n clientId: '123456',\n};\n\nconst TEST_OAUTH_TOKEN = 'test-secret-oauth-token';\n\njest.mock('.\/PortChannelAuthProvider');\n\ndescribe('utils\/getAuthProvider', () => {\n useFakeBroadcastChannel();\n\n const configWithAuth = (auth?: AuthConfig) => ({\n ...createConfig(),\n auth,\n });\n\n it('returns undefined with undefined auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(undefined) });\n\n expect(provider).toBeUndefined();\n });\n\n it('returns token provider with token auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_TOKEN_AUTH) });\n\n const actual = await provider?.getToken();\n\n expect(provider).not.toBeUndefined();\n expect(actual).toEqual(TEST_TOKEN_AUTH.token);\n });\n\n it('returns oauth provider with oauth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n jest.mocked(oauthClientInstance.getToken).mockResolvedValue({\n accessToken: TEST_OAUTH_TOKEN,\n expiresAt: 0,\n });\n\n const actual = await provider?.getToken();\n\n expect(oauthClientInstance.onTokenChange).not.toHaveBeenCalled();\n expect(provider).not.toBeUndefined();\n expect(actual).toBe(TEST_OAUTH_TOKEN);\n });\n\n it('with oauth, registers onTokenChange listener', async () => {\n const spy = jest.fn();\n\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH), onTokenChange: spy });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledTimes(1);\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledWith(spy);\n });\n\n it('with oauth, calls setupAutoRefresh', async () => {\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(setupAutoRefresh).toHaveBeenCalledTimes(1);\n expect(setupAutoRefresh).toHaveBeenCalledWith(oauthClientInstance);\n });\n\n it.each`\n authType | config | expectedClass\n ${'oauth'} | ${TEST_OAUTH_AUTH} | ${PortChannelAuthProvider}\n ${'access token'} | ${TEST_TOKEN_AUTH} | ${DefaultAuthProvider}\n `(\n 'with $authType and with windowChannel, returns a $expectedClass',\n async ({ config, expectedClass }) => {\n const fakePortChannel = createFakePartial({});\n const windowChannel = createFakeCrossWindowChannel();\n\n jest.mocked(windowChannel.requestRemotePortChannel).mockResolvedValue(fakePortChannel);\n\n const onTokenChange = jest.fn();\n const provider = await getAuthProvider({\n config: configWithAuth(config),\n windowChannel,\n onTokenChange,\n });\n\n expect(provider).toBeInstanceOf(expectedClass);\n },\n );\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"fde31a42-fc53-44fd-83e4-e31c94f1fbb6","name":"utils\/getAuthProvider","imports":"[{'import_name': ['createConfig', 'createFakeCrossWindowChannel', 'createFakePartial', 'useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['AuthConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['DefaultOAuthClient', 'setupAutoRefresh'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['PortChannel'], 'import_path': '@gitlab\/cross-origin-channel'}, {'import_name': ['DefaultAuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"describe('utils\/getAuthProvider', () => {\n useFakeBroadcastChannel();\n\n const configWithAuth = (auth?: AuthConfig) => ({\n ...createConfig(),\n auth,\n });\n\n it('returns undefined with undefined auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(undefined) });\n\n expect(provider).toBeUndefined();\n });\n\n it('returns token provider with token auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_TOKEN_AUTH) });\n\n const actual = await provider?.getToken();\n\n expect(provider).not.toBeUndefined();\n expect(actual).toEqual(TEST_TOKEN_AUTH.token);\n });\n\n it('returns oauth provider with oauth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n jest.mocked(oauthClientInstance.getToken).mockResolvedValue({\n accessToken: TEST_OAUTH_TOKEN,\n expiresAt: 0,\n });\n\n const actual = await provider?.getToken();\n\n expect(oauthClientInstance.onTokenChange).not.toHaveBeenCalled();\n expect(provider).not.toBeUndefined();\n expect(actual).toBe(TEST_OAUTH_TOKEN);\n });\n\n it('with oauth, registers onTokenChange listener', async () => {\n const spy = jest.fn();\n\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH), onTokenChange: spy });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledTimes(1);\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledWith(spy);\n });\n\n it('with oauth, calls setupAutoRefresh', async () => {\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(setupAutoRefresh).toHaveBeenCalledTimes(1);\n expect(setupAutoRefresh).toHaveBeenCalledWith(oauthClientInstance);\n });\n\n it.each`\n authType | config | expectedClass\n ${'oauth'} | ${TEST_OAUTH_AUTH} | ${PortChannelAuthProvider}\n ${'access token'} | ${TEST_TOKEN_AUTH} | ${DefaultAuthProvider}\n `(\n 'with $authType and with windowChannel, returns a $expectedClass',\n async ({ config, expectedClass }) => {\n const fakePortChannel = createFakePartial({});\n const windowChannel = createFakeCrossWindowChannel();\n\n jest.mocked(windowChannel.requestRemotePortChannel).mockResolvedValue(fakePortChannel);\n\n const onTokenChange = jest.fn();\n const provider = await getAuthProvider({\n config: configWithAuth(config),\n windowChannel,\n onTokenChange,\n });\n\n expect(provider).toBeInstanceOf(expectedClass);\n },\n );\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"3ded0c21-0d52-4693-a292-6393a7b27f68","name":"returns undefined with undefined auth","imports":"[{'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"it('returns undefined with undefined auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(undefined) });\n\n expect(provider).toBeUndefined();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"00572770-bd7a-44f6-b5cc-2b65fccaaa24","name":"returns token provider with token auth","imports":"[{'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"it('returns token provider with token auth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_TOKEN_AUTH) });\n\n const actual = await provider?.getToken();\n\n expect(provider).not.toBeUndefined();\n expect(actual).toEqual(TEST_TOKEN_AUTH.token);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"e3a5c4e5-2331-44ca-ab06-bf0054461b47","name":"returns oauth provider with oauth","imports":"[{'import_name': ['DefaultOAuthClient'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"it('returns oauth provider with oauth', async () => {\n const provider = await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n jest.mocked(oauthClientInstance.getToken).mockResolvedValue({\n accessToken: TEST_OAUTH_TOKEN,\n expiresAt: 0,\n });\n\n const actual = await provider?.getToken();\n\n expect(oauthClientInstance.onTokenChange).not.toHaveBeenCalled();\n expect(provider).not.toBeUndefined();\n expect(actual).toBe(TEST_OAUTH_TOKEN);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"b178fe05-c068-48fd-a609-77998b22e73c","name":"with oauth, registers onTokenChange listener","imports":"[{'import_name': ['DefaultOAuthClient'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"it('with oauth, registers onTokenChange listener', async () => {\n const spy = jest.fn();\n\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH), onTokenChange: spy });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledTimes(1);\n expect(oauthClientInstance.onTokenChange).toHaveBeenCalledWith(spy);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c4c2862f-b7ad-408e-b7e6-a6979a040d39","name":"with oauth, calls setupAutoRefresh","imports":"[{'import_name': ['DefaultOAuthClient', 'setupAutoRefresh'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['getAuthProvider'], 'import_path': '.\/getAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.test.ts","code":"it('with oauth, calls setupAutoRefresh', async () => {\n await getAuthProvider({ config: configWithAuth(TEST_OAUTH_AUTH) });\n\n const oauthClientInstance = jest.mocked(DefaultOAuthClient).mock.instances[0];\n\n expect(setupAutoRefresh).toHaveBeenCalledTimes(1);\n expect(setupAutoRefresh).toHaveBeenCalledWith(oauthClientInstance);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f019be58-5298-41ad-bc9b-2dfeb94f94d3","name":"getAuthProvider.ts","imports":"[{'import_name': ['CrossWindowChannel'], 'import_path': '@gitlab\/cross-origin-channel'}, {'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['DefaultAuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['asOAuthProvider', 'createOAuthClient', 'setupAutoRefresh'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['WebIdeConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.ts","code":"import type { CrossWindowChannel } from '@gitlab\/cross-origin-channel';\nimport type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport { DefaultAuthProvider } from '@gitlab\/gitlab-api-client';\nimport { asOAuthProvider, createOAuthClient, setupAutoRefresh } from '@gitlab\/oauth-client';\nimport type { WebIdeConfig } from '@gitlab\/web-ide-types';\nimport { PortChannelAuthProvider } from '.\/PortChannelAuthProvider';\n\ninterface GetAuthProviderOptions {\n config: WebIdeConfig;\n windowChannel?: CrossWindowChannel;\n onTokenChange?: () => void;\n}\n\nexport const getAuthProvider = async ({\n config,\n windowChannel,\n onTokenChange,\n}: GetAuthProviderOptions): Promise => {\n if (config.auth?.type === 'token') {\n return new DefaultAuthProvider(config.auth.token);\n }\n\n if (config.auth?.type === 'oauth') {\n if (windowChannel) {\n const portChannel = await windowChannel.requestRemotePortChannel('auth-port');\n\n return new PortChannelAuthProvider({\n portChannel,\n onTokenChange,\n });\n }\n\n \/\/ TODO: Delete createOAuthClient along with the dedicatedWebIDEOrigin feature flag\n const client = createOAuthClient({\n oauthConfig: config.auth,\n gitlabUrl: config.gitlabUrl,\n owner: config.username,\n });\n\n setupAutoRefresh(client);\n\n if (onTokenChange) {\n client.onTokenChange(onTokenChange);\n }\n\n return asOAuthProvider(client);\n }\n\n return undefined;\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"cdb97dc7-c266-4038-8b49-77deadbb399f","name":"getAuthProvider","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['DefaultAuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['asOAuthProvider', 'createOAuthClient', 'setupAutoRefresh'], 'import_path': '@gitlab\/oauth-client'}, {'import_name': ['PortChannelAuthProvider'], 'import_path': '.\/PortChannelAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/getAuthProvider.ts","code":"async ({\n config,\n windowChannel,\n onTokenChange,\n}: GetAuthProviderOptions): Promise => {\n if (config.auth?.type === 'token') {\n return new DefaultAuthProvider(config.auth.token);\n }\n\n if (config.auth?.type === 'oauth') {\n if (windowChannel) {\n const portChannel = await windowChannel.requestRemotePortChannel('auth-port');\n\n return new PortChannelAuthProvider({\n portChannel,\n onTokenChange,\n });\n }\n\n \/\/ TODO: Delete createOAuthClient along with the dedicatedWebIDEOrigin feature flag\n const client = createOAuthClient({\n oauthConfig: config.auth,\n gitlabUrl: config.gitlabUrl,\n owner: config.username,\n });\n\n setupAutoRefresh(client);\n\n if (onTokenChange) {\n client.onTokenChange(onTokenChange);\n }\n\n return asOAuthProvider(client);\n }\n\n return undefined;\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0ea1fca1-c7a2-40cd-9b9b-ba86c461195d","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client-factory\/src\/index.ts","code":"export * from '.\/createGitLabClient';\nexport * from '.\/getAuthHeadersProvider';\nexport * from '.\/getAuthProvider';\nexport { createPrivateTokenHeadersProvider } from '.\/DefaultAuthHeadersProvider';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"102716fb-d5f6-47af-b2d0-e7b44471b0a3","name":"DefaultAuthProvider.test.ts","imports":"[{'import_name': ['DefaultAuthProvider'], 'import_path': '.\/DefaultAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.test.ts","code":"import { DefaultAuthProvider } from '.\/DefaultAuthProvider';\n\nconst TEST_TOKEN = '123ABC';\n\ndescribe('DefaultAuthProvider', () => {\n let subject: DefaultAuthProvider;\n\n beforeEach(() => {\n subject = new DefaultAuthProvider(TEST_TOKEN);\n });\n\n it('getToken - returns expected token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"03910d6e-cbcf-4a31-9813-f12277fa2e36","name":"DefaultAuthProvider","imports":"[{'import_name': ['DefaultAuthProvider'], 'import_path': '.\/DefaultAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.test.ts","code":"describe('DefaultAuthProvider', () => {\n let subject: DefaultAuthProvider;\n\n beforeEach(() => {\n subject = new DefaultAuthProvider(TEST_TOKEN);\n });\n\n it('getToken - returns expected token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"7b36b11d-0ff9-44f2-a820-5f3bcd4b4592","name":"getToken - returns expected token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.test.ts","code":"it('getToken - returns expected token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"b28bc573-2b59-4ac5-9242-65486f63b8be","name":"DefaultAuthProvider.ts","imports":"[{'import_name': ['AuthProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.ts","code":"import type { AuthProvider } from '.\/types';\n\nexport class DefaultAuthProvider implements AuthProvider {\n readonly #token: string;\n\n constructor(token: string) {\n this.#token = token;\n }\n\n getToken(): Promise {\n return Promise.resolve(this.#token);\n }\n}\n\nexport const NOOP_AUTH_PROVIDER = new DefaultAuthProvider('');\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"be8768f9-856e-44ff-9743-b569e141b915","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.ts","code":"constructor(token: string) {\n this.#token = token;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultAuthProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"c10fd5cb-7291-474a-a890-2c83e223269d","name":"getToken","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultAuthProvider.ts","code":"getToken(): Promise {\n return Promise.resolve(this.#token);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultAuthProvider'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0339da6f-7182-43d1-8bee-f06be9523b1f","name":"DefaultGitLabClient.test.ts","imports":"[{'import_name': ['GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}, {'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}, {'import_name': ['DefaultGitLabConfig'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"import type { GetRequest, GraphQLRequest, PostRequest } from '@gitlab\/web-ide-interop';\nimport * as graphqlRequestModule from 'graphql-request';\nimport 'whatwg-fetch';\nimport { createHeadersProvider } from '.\/createHeadersProvider';\nimport type { DefaultGitLabConfig } from '.\/DefaultGitLabClient';\nimport { DefaultGitLabClient } from '.\/DefaultGitLabClient';\n\nconst { GraphQLClient, gql } = graphqlRequestModule;\n\nconst TEST_AUTH_TOKEN = '123456';\nconst TEST_AUTH_TOKEN_HEADERS = {\n 'PRIVATE-TOKEN': TEST_AUTH_TOKEN,\n};\n\/\/ why: Test that relative URL works\nconst TEST_BASE_URL = 'https:\/\/gdk.test\/test';\nconst TEST_RESPONSE_OBJ = { msg: 'test response' };\n\ndescribe('DefaultGitLabClient', () => {\n let fetchSpy: jest.SpiedFunction;\n let gqlClientSpy: jest.SpyInstance;\n let gqlRequestSpy: jest.SpyInstance>;\n let subject: DefaultGitLabClient;\n\n const createSubject = (config?: Partial) => {\n subject = new DefaultGitLabClient({\n auth: createHeadersProvider({ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN }),\n baseUrl: TEST_BASE_URL,\n ...config,\n });\n };\n\n const mockResponse = (response: Response) =>\n fetchSpy.mockImplementation(() => Promise.resolve(response));\n\n beforeEach(() => {\n gqlRequestSpy = jest.spyOn(GraphQLClient.prototype, 'request').mockResolvedValue(undefined);\n gqlClientSpy = jest\n .spyOn(graphqlRequestModule, 'GraphQLClient')\n .mockImplementation((...args) => new GraphQLClient(...args));\n fetchSpy = jest.spyOn(window, 'fetch');\n\n mockResponse(\n new Response(JSON.stringify(TEST_RESPONSE_OBJ), { status: 200, statusText: 'OK' }),\n );\n });\n\n describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe('fetchFromApi', () => {\n describe('GetRequest', () => {\n const getRequest: GetRequest = {\n type: 'rest',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: { test: 'value' },\n };\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n });\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('PostRequest', () => {\n const postRequest: PostRequest = {\n type: 'rest',\n method: 'POST',\n path: 'code_suggestions\/tokens',\n body: { test: 'body' },\n };\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n });\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('GraphQLRequest', () => {\n const graphQLRequest: GraphQLRequest = {\n type: 'graphql',\n query: gql`\n query GetProject($namespaceWithPath: ID!) {\n project(fullPath: $namespaceWithPath) {\n name\n description\n }\n }\n `,\n variables: {\n fullPath: 'gitlab-org\/gitlab',\n },\n };\n\n const project = { name: 'test name', description: 'test description' };\n\n it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n });\n\n it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n });\n });\n });\n\n describe('fetchBufferFromApi', () => {\n it('returns buffer of data response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const expectedResponse = new Uint8Array(\n new TextEncoder().encode(JSON.stringify(TEST_RESPONSE_OBJ)),\n );\n\n const actual = await subject.fetchBufferFromApi({\n type: 'rest-buffer',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: {\n test: 'value',\n },\n });\n const actualByteArray = new Uint8Array(actual);\n\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n headers: TEST_AUTH_TOKEN_HEADERS,\n method: 'GET',\n });\n expect(actualByteArray).toEqual(expectedResponse);\n });\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"95ded9c7-2063-4e02-8ff9-6ff90fe7e8ee","name":"DefaultGitLabClient","imports":"[{'import_name': ['GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}, {'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}, {'import_name': ['DefaultGitLabConfig'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('DefaultGitLabClient', () => {\n let fetchSpy: jest.SpiedFunction;\n let gqlClientSpy: jest.SpyInstance;\n let gqlRequestSpy: jest.SpyInstance>;\n let subject: DefaultGitLabClient;\n\n const createSubject = (config?: Partial) => {\n subject = new DefaultGitLabClient({\n auth: createHeadersProvider({ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN }),\n baseUrl: TEST_BASE_URL,\n ...config,\n });\n };\n\n const mockResponse = (response: Response) =>\n fetchSpy.mockImplementation(() => Promise.resolve(response));\n\n beforeEach(() => {\n gqlRequestSpy = jest.spyOn(GraphQLClient.prototype, 'request').mockResolvedValue(undefined);\n gqlClientSpy = jest\n .spyOn(graphqlRequestModule, 'GraphQLClient')\n .mockImplementation((...args) => new GraphQLClient(...args));\n fetchSpy = jest.spyOn(window, 'fetch');\n\n mockResponse(\n new Response(JSON.stringify(TEST_RESPONSE_OBJ), { status: 200, statusText: 'OK' }),\n );\n });\n\n describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe('fetchFromApi', () => {\n describe('GetRequest', () => {\n const getRequest: GetRequest = {\n type: 'rest',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: { test: 'value' },\n };\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n });\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('PostRequest', () => {\n const postRequest: PostRequest = {\n type: 'rest',\n method: 'POST',\n path: 'code_suggestions\/tokens',\n body: { test: 'body' },\n };\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n });\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('GraphQLRequest', () => {\n const graphQLRequest: GraphQLRequest = {\n type: 'graphql',\n query: gql`\n query GetProject($namespaceWithPath: ID!) {\n project(fullPath: $namespaceWithPath) {\n name\n description\n }\n }\n `,\n variables: {\n fullPath: 'gitlab-org\/gitlab',\n },\n };\n\n const project = { name: 'test name', description: 'test description' };\n\n it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n });\n\n it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n });\n });\n });\n\n describe('fetchBufferFromApi', () => {\n it('returns buffer of data response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const expectedResponse = new Uint8Array(\n new TextEncoder().encode(JSON.stringify(TEST_RESPONSE_OBJ)),\n );\n\n const actual = await subject.fetchBufferFromApi({\n type: 'rest-buffer',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: {\n test: 'value',\n },\n });\n const actualByteArray = new Uint8Array(actual);\n\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n headers: TEST_AUTH_TOKEN_HEADERS,\n method: 'GET',\n });\n expect(actualByteArray).toEqual(expectedResponse);\n });\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ed83d107-1e7c-415f-a2b6-3b370a5849aa","name":"default","imports":"[{'import_name': ['GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe('fetchFromApi', () => {\n describe('GetRequest', () => {\n const getRequest: GetRequest = {\n type: 'rest',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: { test: 'value' },\n };\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n });\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('PostRequest', () => {\n const postRequest: PostRequest = {\n type: 'rest',\n method: 'POST',\n path: 'code_suggestions\/tokens',\n body: { test: 'body' },\n };\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n });\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('GraphQLRequest', () => {\n const graphQLRequest: GraphQLRequest = {\n type: 'graphql',\n query: gql`\n query GetProject($namespaceWithPath: ID!) {\n project(fullPath: $namespaceWithPath) {\n name\n description\n }\n }\n `,\n variables: {\n fullPath: 'gitlab-org\/gitlab',\n },\n };\n\n const project = { name: 'test name', description: 'test description' };\n\n it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n });\n\n it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n });\n });\n });\n\n describe('fetchBufferFromApi', () => {\n it('returns buffer of data response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const expectedResponse = new Uint8Array(\n new TextEncoder().encode(JSON.stringify(TEST_RESPONSE_OBJ)),\n );\n\n const actual = await subject.fetchBufferFromApi({\n type: 'rest-buffer',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: {\n test: 'value',\n },\n });\n const actualByteArray = new Uint8Array(actual);\n\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n headers: TEST_AUTH_TOKEN_HEADERS,\n method: 'GET',\n });\n expect(actualByteArray).toEqual(expectedResponse);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"4bf5e08a-3d84-43f5-8686-dd7b6d84d6a4","name":"fetchFromApi","imports":"[{'import_name': ['GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('fetchFromApi', () => {\n describe('GetRequest', () => {\n const getRequest: GetRequest = {\n type: 'rest',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: { test: 'value' },\n };\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n });\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('PostRequest', () => {\n const postRequest: PostRequest = {\n type: 'rest',\n method: 'POST',\n path: 'code_suggestions\/tokens',\n body: { test: 'body' },\n };\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n });\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe('GraphQLRequest', () => {\n const graphQLRequest: GraphQLRequest = {\n type: 'graphql',\n query: gql`\n query GetProject($namespaceWithPath: ID!) {\n project(fullPath: $namespaceWithPath) {\n name\n description\n }\n }\n `,\n variables: {\n fullPath: 'gitlab-org\/gitlab',\n },\n };\n\n const project = { name: 'test name', description: 'test description' };\n\n it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n });\n\n it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"022ac642-6dea-4365-a091-5a6f150efb62","name":"GetRequest","imports":"[{'import_name': ['GetRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('GetRequest', () => {\n const getRequest: GetRequest = {\n type: 'rest',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: { test: 'value' },\n };\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n });\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ea80808b-6489-4287-8457-ecd8c0b05b94","name":"with custom headers","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"417e8ff3-5769-4cf6-a2fa-05314ac0f6d5","name":"PostRequest","imports":"[{'import_name': ['PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('PostRequest', () => {\n const postRequest: PostRequest = {\n type: 'rest',\n method: 'POST',\n path: 'code_suggestions\/tokens',\n body: { test: 'body' },\n };\n\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n });\n\n describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"24a2d8bc-0eca-41aa-8120-5215e6fe04ff","name":"with custom headers","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('with custom headers', () => {\n it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f88ea881-7530-48eb-856a-e6f3e5b14f78","name":"GraphQLRequest","imports":"[{'import_name': ['GraphQLRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('GraphQLRequest', () => {\n const graphQLRequest: GraphQLRequest = {\n type: 'graphql',\n query: gql`\n query GetProject($namespaceWithPath: ID!) {\n project(fullPath: $namespaceWithPath) {\n name\n description\n }\n }\n `,\n variables: {\n fullPath: 'gitlab-org\/gitlab',\n },\n };\n\n const project = { name: 'test name', description: 'test description' };\n\n it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n });\n\n it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ecb3cbd4-6954-4e88-8853-d2ad55f1fb80","name":"fetchBufferFromApi","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"describe('fetchBufferFromApi', () => {\n it('returns buffer of data response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const expectedResponse = new Uint8Array(\n new TextEncoder().encode(JSON.stringify(TEST_RESPONSE_OBJ)),\n );\n\n const actual = await subject.fetchBufferFromApi({\n type: 'rest-buffer',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: {\n test: 'value',\n },\n });\n const actualByteArray = new Uint8Array(actual);\n\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n headers: TEST_AUTH_TOKEN_HEADERS,\n method: 'GET',\n });\n expect(actualByteArray).toEqual(expectedResponse);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"cfb3c8d5-b504-4552-bcd6-da4af3cdb5aa","name":"creates graphql client","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"a4da3b34-9f10-4dc6-b55b-e25d752430fc","name":"returns successful response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi({\n ...getRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n custom: 'test',\n },\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"2923bb86-623e-4f35-9364-9f3459282be5","name":"returns successful response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const actual = await subject.fetchFromApi(getRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'GET',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n },\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1fe127ac-9bc5-412a-9adc-4336ae57fac5","name":"if response fails, throws","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(getRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"0e43f3db-5c03-4538-93ba-492a98351490","name":"returns successful response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi(postRequest);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"8b327f51-33e9-4950-909d-954792b41c62","name":"returns successful response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns successful response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/code_suggestions\/tokens`;\n const actual = await subject.fetchFromApi({\n ...postRequest,\n headers: { custom: 'test' },\n });\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n method: 'POST',\n body: '{\"test\":\"body\"}',\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n custom: 'test',\n },\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"0016ce47-bf95-4838-9dae-10177a7fc043","name":"if response fails, throws","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(subject.fetchFromApi(postRequest)).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"00e89821-98ff-4d53-9b4b-401fcf6a3a85","name":"returns successful response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns successful response', async () => {\n gqlRequestSpy.mockResolvedValue({ project });\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await subject.fetchFromApi(graphQLRequest);\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n graphQLRequest.query,\n graphQLRequest.variables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual({ project });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"72a570be-bee4-41ac-a468-c7be59ea0607","name":"if response fails, throws","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('if response fails, throws', async () => {\n gqlRequestSpy.mockRejectedValue(new Error('test'));\n\n await expect(subject.fetchFromApi(graphQLRequest)).rejects.toThrowError();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"268a41a4-bf26-4286-b7ea-3cb03e396d5e","name":"returns buffer of data response","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.test.ts","code":"it('returns buffer of data response', async () => {\n const expectedUrl = `${TEST_BASE_URL}\/api\/v4\/projects\/gitlab-org%2fgitlab?test=value`;\n const expectedResponse = new Uint8Array(\n new TextEncoder().encode(JSON.stringify(TEST_RESPONSE_OBJ)),\n );\n\n const actual = await subject.fetchBufferFromApi({\n type: 'rest-buffer',\n method: 'GET',\n path: 'projects\/gitlab-org%2fgitlab',\n searchParams: {\n test: 'value',\n },\n });\n const actualByteArray = new Uint8Array(actual);\n\n expect(fetchSpy).toHaveBeenCalledWith(expectedUrl, {\n headers: TEST_AUTH_TOKEN_HEADERS,\n method: 'GET',\n });\n expect(actualByteArray).toEqual(expectedResponse);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"1aaaf4da-030a-4ece-bb80-cac9f18577ef","name":"DefaultGitLabClient.ts","imports":"[{'import_name': ['GraphQLClient'], 'import_path': 'graphql-request'}, {'import_name': ['joinPaths'], 'import_path': '@gitlab\/utils-path'}, {'import_name': ['ApiRequest', 'GetBufferRequest', 'GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}, {'import_name': ['NOOP_AUTH_HEADERS_PROVIDER'], 'import_path': '.\/createHeadersProvider'}, {'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['AuthHeadersProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"import { GraphQLClient } from 'graphql-request';\nimport { joinPaths } from '@gitlab\/utils-path';\nimport type {\n ApiRequest,\n GetBufferRequest,\n GetRequest,\n GraphQLRequest,\n PostRequest,\n} from '@gitlab\/web-ide-interop';\nimport { NOOP_AUTH_HEADERS_PROVIDER } from '.\/createHeadersProvider';\nimport { createResponseError } from '.\/createResponseError';\nimport type { AuthHeadersProvider } from '.\/types';\n\nconst withParams = (baseUrl: string, params: Record) => {\n const paramEntries = Object.entries(params);\n\n if (!paramEntries.length) {\n return baseUrl;\n }\n\n const url = new URL(baseUrl);\n\n paramEntries.forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n\n return url.toString();\n};\n\nexport interface DefaultGitLabConfig {\n baseUrl: string;\n auth?: AuthHeadersProvider;\n httpHeaders?: Record;\n}\n\nexport class DefaultGitLabClient {\n readonly #baseUrl: string;\n\n readonly #httpHeaders: Record;\n\n readonly #auth: AuthHeadersProvider;\n\n readonly #graphqlClient: GraphQLClient;\n\n constructor(config: DefaultGitLabConfig) {\n this.#baseUrl = config.baseUrl;\n this.#httpHeaders = config.httpHeaders || {};\n this.#auth = config.auth || NOOP_AUTH_HEADERS_PROVIDER;\n\n const graphqlUrl = joinPaths(this.#baseUrl, 'api', 'graphql');\n this.#graphqlClient = new GraphQLClient(graphqlUrl);\n }\n\n async fetchBufferFromApi(request: GetBufferRequest): Promise {\n return this.#makeGetBufferRequest(request);\n }\n\n async fetchFromApi(request: ApiRequest): Promise {\n if (request.type === 'rest' && request.method === 'GET') {\n return this.#makeGetRequest(request);\n }\n if (request.type === 'rest' && request.method === 'POST') {\n return this.#makePostRequest(request);\n }\n if (request.type === 'graphql') {\n return this.#makeGraphQLRequest(request);\n }\n throw new Error(`Unknown request type: ${(request as ApiRequest).type}`);\n }\n\n async #makePostRequest(request: PostRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n return this.#fetchPostJson(url, request.body, request.headers);\n }\n\n async #makeGetRequest(request: GetRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n\n return this.#fetchGetJson(url, request.searchParams, request.headers);\n }\n\n async #makeGetBufferRequest(request: GetBufferRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n\n return this.#fetchGetBuffer(url, request.searchParams, request.headers);\n }\n\n #appendPathToBaseApiUrl(path: string) {\n return joinPaths(this.#baseUrl, 'api', 'v4', path);\n }\n\n async #fetchPostJson(\n url: string,\n body: TBody,\n headers?: Record,\n ): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n const response = await fetch(url, {\n method: 'POST',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n ...commonHeaders,\n ...headers,\n 'Content-Type': 'application\/json',\n },\n });\n\n if (!response.ok) {\n throw await createResponseError(response);\n }\n\n return >response.json();\n }\n\n async #fetchGetJson(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const response = await this.#fetchGetResponse(url, params, headers);\n\n return (await response.json()) as T;\n }\n\n async #fetchGetBuffer(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const response = await this.#fetchGetResponse(url, params, headers);\n\n return response.arrayBuffer();\n }\n\n async #fetchGetResponse(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n const response = await fetch(withParams(url, params), {\n method: 'GET',\n headers: {\n ...commonHeaders,\n ...headers,\n },\n });\n\n if (!response.ok) {\n throw await createResponseError(response);\n }\n\n return response;\n }\n\n async #makeGraphQLRequest(request: GraphQLRequest): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n return this.#graphqlClient.request(request.query, request.variables, commonHeaders);\n }\n\n async #getCommonHeaders(): Promise> {\n const authHeaders = await this.#auth.getHeaders();\n\n return {\n ...this.#httpHeaders,\n ...authHeaders,\n };\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ab6581b1-e63a-4a7d-943c-6a2246671928","name":"withParams","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"(baseUrl: string, params: Record) => {\n const paramEntries = Object.entries(params);\n\n if (!paramEntries.length) {\n return baseUrl;\n }\n\n const url = new URL(baseUrl);\n\n paramEntries.forEach(([key, value]) => {\n url.searchParams.append(key, value);\n });\n\n return url.toString();\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9f9ece5d-d5b2-4a0d-bf15-8a8d2edd5c22","name":"constructor","imports":"[{'import_name': ['GraphQLClient'], 'import_path': 'graphql-request'}, {'import_name': ['joinPaths'], 'import_path': '@gitlab\/utils-path'}, {'import_name': ['NOOP_AUTH_HEADERS_PROVIDER'], 'import_path': '.\/createHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"constructor(config: DefaultGitLabConfig) {\n this.#baseUrl = config.baseUrl;\n this.#httpHeaders = config.httpHeaders || {};\n this.#auth = config.auth || NOOP_AUTH_HEADERS_PROVIDER;\n\n const graphqlUrl = joinPaths(this.#baseUrl, 'api', 'graphql');\n this.#graphqlClient = new GraphQLClient(graphqlUrl);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"74229dc5-0888-4a13-8af5-10443d1182fa","name":"fetchBufferFromApi","imports":"[{'import_name': ['GetBufferRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async fetchBufferFromApi(request: GetBufferRequest): Promise {\n return this.#makeGetBufferRequest(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"43e4b484-bea2-4a27-b6cc-75139061ce41","name":"fetchFromApi","imports":"[{'import_name': ['ApiRequest', 'GetRequest', 'GraphQLRequest', 'PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async fetchFromApi(request: ApiRequest): Promise {\n if (request.type === 'rest' && request.method === 'GET') {\n return this.#makeGetRequest(request);\n }\n if (request.type === 'rest' && request.method === 'POST') {\n return this.#makePostRequest(request);\n }\n if (request.type === 'graphql') {\n return this.#makeGraphQLRequest(request);\n }\n throw new Error(`Unknown request type: ${(request as ApiRequest).type}`);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d4d20c51-9122-477e-bd1f-9fdfa2fd992e","name":"#makePostRequest","imports":"[{'import_name': ['PostRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #makePostRequest(request: PostRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n return this.#fetchPostJson(url, request.body, request.headers);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e8457bd5-7c50-4f60-a1c7-273cd216331b","name":"#makeGetRequest","imports":"[{'import_name': ['GetRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #makeGetRequest(request: GetRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n\n return this.#fetchGetJson(url, request.searchParams, request.headers);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9028d537-c669-47b5-bb5b-e73ab56c2df4","name":"#makeGetBufferRequest","imports":"[{'import_name': ['GetBufferRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #makeGetBufferRequest(request: GetBufferRequest): Promise {\n const url = this.#appendPathToBaseApiUrl(request.path);\n\n return this.#fetchGetBuffer(url, request.searchParams, request.headers);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ee4f3bb4-e0d3-4223-8ce4-1bc0029fd935","name":"#appendPathToBaseApiUrl","imports":"[{'import_name': ['joinPaths'], 'import_path': '@gitlab\/utils-path'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"#appendPathToBaseApiUrl(path: string) {\n return joinPaths(this.#baseUrl, 'api', 'v4', path);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f81ea9e5-022c-4c6f-b709-5a1b518e47bb","name":"#fetchPostJson","imports":"[{'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #fetchPostJson(\n url: string,\n body: TBody,\n headers?: Record,\n ): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n const response = await fetch(url, {\n method: 'POST',\n body: body ? JSON.stringify(body) : undefined,\n headers: {\n ...commonHeaders,\n ...headers,\n 'Content-Type': 'application\/json',\n },\n });\n\n if (!response.ok) {\n throw await createResponseError(response);\n }\n\n return >response.json();\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"98f7a790-121a-4e51-97ca-b2043bf8073c","name":"#fetchGetJson","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #fetchGetJson(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const response = await this.#fetchGetResponse(url, params, headers);\n\n return (await response.json()) as T;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"725fb2a3-c1c2-4fda-a6b5-f06cfadeb511","name":"#fetchGetBuffer","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #fetchGetBuffer(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const response = await this.#fetchGetResponse(url, params, headers);\n\n return response.arrayBuffer();\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"771231ca-4ec2-4a09-95bd-4915929e7386","name":"#fetchGetResponse","imports":"[{'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #fetchGetResponse(\n url: string,\n params: Record = {},\n headers: Record = {},\n ): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n const response = await fetch(withParams(url, params), {\n method: 'GET',\n headers: {\n ...commonHeaders,\n ...headers,\n },\n });\n\n if (!response.ok) {\n throw await createResponseError(response);\n }\n\n return response;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"66bff01b-cd62-4485-999e-c182a6a3609a","name":"#makeGraphQLRequest","imports":"[{'import_name': ['GraphQLRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #makeGraphQLRequest(request: GraphQLRequest): Promise {\n const commonHeaders = await this.#getCommonHeaders();\n\n return this.#graphqlClient.request(request.query, request.variables, commonHeaders);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"0a71ee27-1fe2-4b63-8a2c-e21d2e2c1c8f","name":"#getCommonHeaders","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DefaultGitLabClient.ts","code":"async #getCommonHeaders(): Promise> {\n const authHeaders = await this.#auth.getHeaders();\n\n return {\n ...this.#httpHeaders,\n ...authHeaders,\n };\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultGitLabClient'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"ff3be7c0-983d-456e-a3fe-b76bdb16e322","name":"DeprecatedGitLabClient.test.ts","imports":"[{'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}, {'import_name': ['DeprecatedGitLabClient', 'GitLabClient'], 'import_path': '.\/DeprecatedGitLabClient'}, {'import_name': ['DefaultGitLabConfig'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['createProjectBranchMutation', 'getMergeRequestDiffStatsQuery', 'getProjectUserPermissionsQuery', 'getRefMetadataQuery', 'searchProjectBranchesQuery'], 'import_path': '.\/graphql'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"import * as graphqlRequestModule from 'graphql-request';\nimport 'whatwg-fetch';\n\nimport { createHeadersProvider } from '.\/createHeadersProvider';\nimport { DeprecatedGitLabClient as GitLabClient } from '.\/DeprecatedGitLabClient';\nimport type { DefaultGitLabConfig } from '.\/DefaultGitLabClient';\nimport { DefaultGitLabClient } from '.\/DefaultGitLabClient';\nimport type { gitlab } from '.\/types';\nimport {\n createProjectBranchMutation,\n getMergeRequestDiffStatsQuery,\n getProjectUserPermissionsQuery,\n getRefMetadataQuery,\n searchProjectBranchesQuery,\n} from '.\/graphql';\nimport * as mockVariables from '..\/test-utils\/graphql\/mockVariables';\nimport * as mockResponses from '..\/test-utils\/graphql\/mockResponses';\n\nconst { GraphQLClient } = graphqlRequestModule;\n\nconst TEST_AUTH_TOKEN = '123456';\nconst TEST_AUTH_TOKEN_HEADERS = {\n 'PRIVATE-TOKEN': TEST_AUTH_TOKEN,\n};\n\/\/ why: Test that relative URL works\nconst TEST_BASE_URL = 'https:\/\/gdk.test\/test';\nconst TEST_RESPONSE_OBJ = { msg: 'test response' };\nconst TEST_EXTRA_HEADERS = {\n Extra: 'Header-Value',\n test: '123',\n};\n\ndescribe('DeprecatedGitLabClient', () => {\n let gqlClientSpy: jest.SpyInstance;\n let gqlRequestSpy: jest.SpyInstance>;\n let fetchSpy: jest.SpiedFunction;\n let subject: GitLabClient;\n\n const createSubject = (config?: Partial) => {\n const defaultClient = new DefaultGitLabClient({\n auth: createHeadersProvider({ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN }),\n baseUrl: TEST_BASE_URL,\n ...config,\n });\n subject = new GitLabClient(defaultClient);\n };\n\n const mockResponse = (response: Response) =>\n fetchSpy.mockImplementation(() => Promise.resolve(response));\n\n beforeEach(() => {\n gqlRequestSpy = jest.spyOn(GraphQLClient.prototype, 'request').mockResolvedValue(undefined);\n gqlClientSpy = jest\n .spyOn(graphqlRequestModule, 'GraphQLClient')\n .mockImplementation((...args) => new GraphQLClient(...args));\n fetchSpy = jest.spyOn(window, 'fetch');\n\n mockResponse(\n new Response(JSON.stringify(TEST_RESPONSE_OBJ), { status: 200, statusText: 'OK' }),\n );\n });\n\n describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe.each([\n [\n 'fetchProject',\n () => subject.fetchProject('lorem\/ipsum'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum`,\n ],\n [\n 'fetchProjectBranch',\n () => subject.fetchProjectBranch('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/branches\/test%2Fref`,\n ],\n [\n 'fetchMergeRequest',\n () => subject.fetchMergeRequest('lorem\/ipsum', '2'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/merge_requests\/2`,\n ],\n [\n 'fetchTree',\n () => subject.fetchTree('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/tree?ref=test%2Fref&recursive=true&pagination=none`,\n ],\n ])('%s', (_, act, expectedURL) => {\n it('fetches from GitLab API', async () => {\n const actual = await act();\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedURL, {\n method: 'GET',\n headers: TEST_AUTH_TOKEN_HEADERS,\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(act()).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe.each([\n {\n description: 'fetchMergeRequestDiffStats',\n act: () => subject.fetchMergeRequestDiffStats({ mergeRequestId: '7' }),\n response: mockResponses.getMergeRequestDiffStats,\n expectedQuery: getMergeRequestDiffStatsQuery,\n expectedVariables: { gid: 'gid:\/\/gitlab\/MergeRequest\/7' },\n expectedReturn: mockResponses.getMergeRequestDiffStats.mergeRequest.diffStats,\n },\n {\n description: 'fetchProjectUserPermissions',\n act: () => subject.fetchProjectUserPermissions('lorem\/ipsum'),\n response: mockResponses.getProjectUserPermissions,\n expectedQuery: getProjectUserPermissionsQuery,\n expectedVariables: { projectPath: 'lorem\/ipsum' },\n expectedReturn: mockResponses.getProjectUserPermissions.project.userPermissions,\n },\n {\n description: 'fetchProjectBranches',\n act: () => subject.fetchProjectBranches(mockVariables.searchProjectBranches),\n response: mockResponses.searchProjectBranches,\n expectedQuery: searchProjectBranchesQuery,\n expectedVariables: mockVariables.searchProjectBranches,\n expectedReturn: mockResponses.searchProjectBranches.project.repository.branchNames,\n },\n {\n description: 'createProjectBranch',\n act: () => subject.createProjectBranch(mockVariables.createProjectBranch),\n response: mockResponses.createProjectBranch,\n expectedQuery: createProjectBranchMutation,\n expectedVariables: mockVariables.createProjectBranch,\n expectedReturn: mockResponses.createProjectBranch.createBranch,\n },\n {\n description: 'fetchRefMetadata',\n act: () => subject.fetchRefMetadata(mockVariables.getRefMetadata),\n response: mockResponses.getRefMetadata,\n expectedQuery: getRefMetadataQuery,\n expectedVariables: mockVariables.getRefMetadata,\n expectedReturn: mockResponses.getRefMetadata.project.repository,\n },\n ])('$description', ({ act, response, expectedQuery, expectedVariables, expectedReturn }) => {\n it('makes graphql request', async () => {\n gqlRequestSpy.mockResolvedValue(response);\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await act();\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n expectedQuery,\n expectedVariables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual(expectedReturn);\n });\n });\n\n describe('fetchFileRaw', () => {\n it('fetched buffer from GitLab API', async () => {\n const expectedBuffer = Buffer.from('Hello world!');\n mockResponse(new Response(expectedBuffer, { status: 200, statusText: 'OK' }));\n\n const actual = await subject.fetchFileRaw('lorem\/ipsum', 'test\/ref', 'docs\/README.md');\n\n expect(Buffer.from(actual)).toEqual(expectedBuffer);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/files\/docs%2FREADME.md\/raw?ref=test%2Fref`,\n { method: 'GET', headers: TEST_AUTH_TOKEN_HEADERS },\n );\n });\n });\n\n describe('commit', () => {\n it('posts commit to GitLab API', async () => {\n const TEST_COMMIT_PAYLOAD: gitlab.CommitPayload = {\n branch: 'main-test-patch',\n start_sha: '',\n commit_message: 'Hello world!',\n actions: [],\n };\n\n const actual = await subject.commit('lorem\/ipsum', TEST_COMMIT_PAYLOAD);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/commits`,\n {\n method: 'POST',\n body: JSON.stringify(TEST_COMMIT_PAYLOAD),\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n },\n );\n });\n });\n });\n\n it.each`\n desc | options | expectedHeaders\n ${'without authToken'} | ${{ auth: undefined }} | ${{}}\n ${'with httpHeaders'} | ${{ httpHeaders: TEST_EXTRA_HEADERS }} | ${{ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN, ...TEST_EXTRA_HEADERS }}\n `('$desc, headers will be $expectedHeaders', async ({ options, expectedHeaders }) => {\n createSubject(options);\n\n await subject.fetchProjectBranch('lorem\/ipsum', 'test\/ref');\n\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/branches\/test%2Fref`,\n { method: 'GET', headers: expectedHeaders },\n );\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"36f1a2fb-fbe6-42f9-8ef0-0bfadfc4d4e2","name":"DeprecatedGitLabClient","imports":"[{'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}, {'import_name': ['DeprecatedGitLabClient', 'GitLabClient'], 'import_path': '.\/DeprecatedGitLabClient'}, {'import_name': ['DefaultGitLabConfig'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}, {'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['createProjectBranchMutation', 'getMergeRequestDiffStatsQuery', 'getProjectUserPermissionsQuery', 'getRefMetadataQuery', 'searchProjectBranchesQuery'], 'import_path': '.\/graphql'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"describe('DeprecatedGitLabClient', () => {\n let gqlClientSpy: jest.SpyInstance;\n let gqlRequestSpy: jest.SpyInstance>;\n let fetchSpy: jest.SpiedFunction;\n let subject: GitLabClient;\n\n const createSubject = (config?: Partial) => {\n const defaultClient = new DefaultGitLabClient({\n auth: createHeadersProvider({ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN }),\n baseUrl: TEST_BASE_URL,\n ...config,\n });\n subject = new GitLabClient(defaultClient);\n };\n\n const mockResponse = (response: Response) =>\n fetchSpy.mockImplementation(() => Promise.resolve(response));\n\n beforeEach(() => {\n gqlRequestSpy = jest.spyOn(GraphQLClient.prototype, 'request').mockResolvedValue(undefined);\n gqlClientSpy = jest\n .spyOn(graphqlRequestModule, 'GraphQLClient')\n .mockImplementation((...args) => new GraphQLClient(...args));\n fetchSpy = jest.spyOn(window, 'fetch');\n\n mockResponse(\n new Response(JSON.stringify(TEST_RESPONSE_OBJ), { status: 200, statusText: 'OK' }),\n );\n });\n\n describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe.each([\n [\n 'fetchProject',\n () => subject.fetchProject('lorem\/ipsum'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum`,\n ],\n [\n 'fetchProjectBranch',\n () => subject.fetchProjectBranch('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/branches\/test%2Fref`,\n ],\n [\n 'fetchMergeRequest',\n () => subject.fetchMergeRequest('lorem\/ipsum', '2'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/merge_requests\/2`,\n ],\n [\n 'fetchTree',\n () => subject.fetchTree('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/tree?ref=test%2Fref&recursive=true&pagination=none`,\n ],\n ])('%s', (_, act, expectedURL) => {\n it('fetches from GitLab API', async () => {\n const actual = await act();\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedURL, {\n method: 'GET',\n headers: TEST_AUTH_TOKEN_HEADERS,\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(act()).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe.each([\n {\n description: 'fetchMergeRequestDiffStats',\n act: () => subject.fetchMergeRequestDiffStats({ mergeRequestId: '7' }),\n response: mockResponses.getMergeRequestDiffStats,\n expectedQuery: getMergeRequestDiffStatsQuery,\n expectedVariables: { gid: 'gid:\/\/gitlab\/MergeRequest\/7' },\n expectedReturn: mockResponses.getMergeRequestDiffStats.mergeRequest.diffStats,\n },\n {\n description: 'fetchProjectUserPermissions',\n act: () => subject.fetchProjectUserPermissions('lorem\/ipsum'),\n response: mockResponses.getProjectUserPermissions,\n expectedQuery: getProjectUserPermissionsQuery,\n expectedVariables: { projectPath: 'lorem\/ipsum' },\n expectedReturn: mockResponses.getProjectUserPermissions.project.userPermissions,\n },\n {\n description: 'fetchProjectBranches',\n act: () => subject.fetchProjectBranches(mockVariables.searchProjectBranches),\n response: mockResponses.searchProjectBranches,\n expectedQuery: searchProjectBranchesQuery,\n expectedVariables: mockVariables.searchProjectBranches,\n expectedReturn: mockResponses.searchProjectBranches.project.repository.branchNames,\n },\n {\n description: 'createProjectBranch',\n act: () => subject.createProjectBranch(mockVariables.createProjectBranch),\n response: mockResponses.createProjectBranch,\n expectedQuery: createProjectBranchMutation,\n expectedVariables: mockVariables.createProjectBranch,\n expectedReturn: mockResponses.createProjectBranch.createBranch,\n },\n {\n description: 'fetchRefMetadata',\n act: () => subject.fetchRefMetadata(mockVariables.getRefMetadata),\n response: mockResponses.getRefMetadata,\n expectedQuery: getRefMetadataQuery,\n expectedVariables: mockVariables.getRefMetadata,\n expectedReturn: mockResponses.getRefMetadata.project.repository,\n },\n ])('$description', ({ act, response, expectedQuery, expectedVariables, expectedReturn }) => {\n it('makes graphql request', async () => {\n gqlRequestSpy.mockResolvedValue(response);\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await act();\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n expectedQuery,\n expectedVariables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual(expectedReturn);\n });\n });\n\n describe('fetchFileRaw', () => {\n it('fetched buffer from GitLab API', async () => {\n const expectedBuffer = Buffer.from('Hello world!');\n mockResponse(new Response(expectedBuffer, { status: 200, statusText: 'OK' }));\n\n const actual = await subject.fetchFileRaw('lorem\/ipsum', 'test\/ref', 'docs\/README.md');\n\n expect(Buffer.from(actual)).toEqual(expectedBuffer);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/files\/docs%2FREADME.md\/raw?ref=test%2Fref`,\n { method: 'GET', headers: TEST_AUTH_TOKEN_HEADERS },\n );\n });\n });\n\n describe('commit', () => {\n it('posts commit to GitLab API', async () => {\n const TEST_COMMIT_PAYLOAD: gitlab.CommitPayload = {\n branch: 'main-test-patch',\n start_sha: '',\n commit_message: 'Hello world!',\n actions: [],\n };\n\n const actual = await subject.commit('lorem\/ipsum', TEST_COMMIT_PAYLOAD);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/commits`,\n {\n method: 'POST',\n body: JSON.stringify(TEST_COMMIT_PAYLOAD),\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n },\n );\n });\n });\n });\n\n it.each`\n desc | options | expectedHeaders\n ${'without authToken'} | ${{ auth: undefined }} | ${{}}\n ${'with httpHeaders'} | ${{ httpHeaders: TEST_EXTRA_HEADERS }} | ${{ 'PRIVATE-TOKEN': TEST_AUTH_TOKEN, ...TEST_EXTRA_HEADERS }}\n `('$desc, headers will be $expectedHeaders', async ({ options, expectedHeaders }) => {\n createSubject(options);\n\n await subject.fetchProjectBranch('lorem\/ipsum', 'test\/ref');\n\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/branches\/test%2Fref`,\n { method: 'GET', headers: expectedHeaders },\n );\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"15a45936-06aa-4f28-91f5-18ba72e9c592","name":"default","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['createProjectBranchMutation', 'getMergeRequestDiffStatsQuery', 'getProjectUserPermissionsQuery', 'getRefMetadataQuery', 'searchProjectBranchesQuery'], 'import_path': '.\/graphql'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"describe('default', () => {\n beforeEach(() => {\n createSubject();\n });\n\n it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n });\n\n describe.each([\n [\n 'fetchProject',\n () => subject.fetchProject('lorem\/ipsum'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum`,\n ],\n [\n 'fetchProjectBranch',\n () => subject.fetchProjectBranch('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/branches\/test%2Fref`,\n ],\n [\n 'fetchMergeRequest',\n () => subject.fetchMergeRequest('lorem\/ipsum', '2'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/merge_requests\/2`,\n ],\n [\n 'fetchTree',\n () => subject.fetchTree('lorem\/ipsum', 'test\/ref'),\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/tree?ref=test%2Fref&recursive=true&pagination=none`,\n ],\n ])('%s', (_, act, expectedURL) => {\n it('fetches from GitLab API', async () => {\n const actual = await act();\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedURL, {\n method: 'GET',\n headers: TEST_AUTH_TOKEN_HEADERS,\n });\n });\n\n it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(act()).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n });\n });\n\n describe.each([\n {\n description: 'fetchMergeRequestDiffStats',\n act: () => subject.fetchMergeRequestDiffStats({ mergeRequestId: '7' }),\n response: mockResponses.getMergeRequestDiffStats,\n expectedQuery: getMergeRequestDiffStatsQuery,\n expectedVariables: { gid: 'gid:\/\/gitlab\/MergeRequest\/7' },\n expectedReturn: mockResponses.getMergeRequestDiffStats.mergeRequest.diffStats,\n },\n {\n description: 'fetchProjectUserPermissions',\n act: () => subject.fetchProjectUserPermissions('lorem\/ipsum'),\n response: mockResponses.getProjectUserPermissions,\n expectedQuery: getProjectUserPermissionsQuery,\n expectedVariables: { projectPath: 'lorem\/ipsum' },\n expectedReturn: mockResponses.getProjectUserPermissions.project.userPermissions,\n },\n {\n description: 'fetchProjectBranches',\n act: () => subject.fetchProjectBranches(mockVariables.searchProjectBranches),\n response: mockResponses.searchProjectBranches,\n expectedQuery: searchProjectBranchesQuery,\n expectedVariables: mockVariables.searchProjectBranches,\n expectedReturn: mockResponses.searchProjectBranches.project.repository.branchNames,\n },\n {\n description: 'createProjectBranch',\n act: () => subject.createProjectBranch(mockVariables.createProjectBranch),\n response: mockResponses.createProjectBranch,\n expectedQuery: createProjectBranchMutation,\n expectedVariables: mockVariables.createProjectBranch,\n expectedReturn: mockResponses.createProjectBranch.createBranch,\n },\n {\n description: 'fetchRefMetadata',\n act: () => subject.fetchRefMetadata(mockVariables.getRefMetadata),\n response: mockResponses.getRefMetadata,\n expectedQuery: getRefMetadataQuery,\n expectedVariables: mockVariables.getRefMetadata,\n expectedReturn: mockResponses.getRefMetadata.project.repository,\n },\n ])('$description', ({ act, response, expectedQuery, expectedVariables, expectedReturn }) => {\n it('makes graphql request', async () => {\n gqlRequestSpy.mockResolvedValue(response);\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await act();\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n expectedQuery,\n expectedVariables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual(expectedReturn);\n });\n });\n\n describe('fetchFileRaw', () => {\n it('fetched buffer from GitLab API', async () => {\n const expectedBuffer = Buffer.from('Hello world!');\n mockResponse(new Response(expectedBuffer, { status: 200, statusText: 'OK' }));\n\n const actual = await subject.fetchFileRaw('lorem\/ipsum', 'test\/ref', 'docs\/README.md');\n\n expect(Buffer.from(actual)).toEqual(expectedBuffer);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/files\/docs%2FREADME.md\/raw?ref=test%2Fref`,\n { method: 'GET', headers: TEST_AUTH_TOKEN_HEADERS },\n );\n });\n });\n\n describe('commit', () => {\n it('posts commit to GitLab API', async () => {\n const TEST_COMMIT_PAYLOAD: gitlab.CommitPayload = {\n branch: 'main-test-patch',\n start_sha: '',\n commit_message: 'Hello world!',\n actions: [],\n };\n\n const actual = await subject.commit('lorem\/ipsum', TEST_COMMIT_PAYLOAD);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/commits`,\n {\n method: 'POST',\n body: JSON.stringify(TEST_COMMIT_PAYLOAD),\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n },\n );\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"38be5e82-858d-46ca-ab30-4ba9177d8abe","name":"fetchFileRaw","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"describe('fetchFileRaw', () => {\n it('fetched buffer from GitLab API', async () => {\n const expectedBuffer = Buffer.from('Hello world!');\n mockResponse(new Response(expectedBuffer, { status: 200, statusText: 'OK' }));\n\n const actual = await subject.fetchFileRaw('lorem\/ipsum', 'test\/ref', 'docs\/README.md');\n\n expect(Buffer.from(actual)).toEqual(expectedBuffer);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/files\/docs%2FREADME.md\/raw?ref=test%2Fref`,\n { method: 'GET', headers: TEST_AUTH_TOKEN_HEADERS },\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"06c8610b-41b4-4569-8a18-f20377b5f779","name":"commit","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"describe('commit', () => {\n it('posts commit to GitLab API', async () => {\n const TEST_COMMIT_PAYLOAD: gitlab.CommitPayload = {\n branch: 'main-test-patch',\n start_sha: '',\n commit_message: 'Hello world!',\n actions: [],\n };\n\n const actual = await subject.commit('lorem\/ipsum', TEST_COMMIT_PAYLOAD);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/commits`,\n {\n method: 'POST',\n body: JSON.stringify(TEST_COMMIT_PAYLOAD),\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n },\n );\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"3110a4e0-b699-4205-ad06-36bb40135dbf","name":"creates graphql client","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('creates graphql client', () => {\n expect(gqlClientSpy).toHaveBeenCalledWith(`${TEST_BASE_URL}\/api\/graphql`);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"6936c526-0513-4c2c-8552-5a7c18ecc1f9","name":"fetches from GitLab API","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('fetches from GitLab API', async () => {\n const actual = await act();\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(expectedURL, {\n method: 'GET',\n headers: TEST_AUTH_TOKEN_HEADERS,\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"53cb1d83-b03b-41db-97b8-cabf83e41d8d","name":"if response fails, throws","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('if response fails, throws', async () => {\n const resp = new Response('', { status: 404 });\n mockResponse(resp);\n\n await expect(act()).rejects.toStrictEqual(\n \/\/ why: We use `objectContaining` to test the actual props of the error objects. Otherwise, Jest just tests the message.\n expect.objectContaining(new Error(JSON.stringify({ status: 404 }))),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"359a0861-6847-409c-a2be-1b7adb66ab5b","name":"makes graphql request","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('makes graphql request', async () => {\n gqlRequestSpy.mockResolvedValue(response);\n expect(gqlRequestSpy).not.toHaveBeenCalled();\n\n const result = await act();\n\n expect(gqlRequestSpy).toHaveBeenCalledWith(\n expectedQuery,\n expectedVariables,\n TEST_AUTH_TOKEN_HEADERS,\n );\n expect(result).toEqual(expectedReturn);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"2a9de642-b9a6-4ef4-80b1-f54680fec63c","name":"fetched buffer from GitLab API","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('fetched buffer from GitLab API', async () => {\n const expectedBuffer = Buffer.from('Hello world!');\n mockResponse(new Response(expectedBuffer, { status: 200, statusText: 'OK' }));\n\n const actual = await subject.fetchFileRaw('lorem\/ipsum', 'test\/ref', 'docs\/README.md');\n\n expect(Buffer.from(actual)).toEqual(expectedBuffer);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/files\/docs%2FREADME.md\/raw?ref=test%2Fref`,\n { method: 'GET', headers: TEST_AUTH_TOKEN_HEADERS },\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"13f45237-595a-4a23-b1a2-8e72d7914941","name":"posts commit to GitLab API","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.test.ts","code":"it('posts commit to GitLab API', async () => {\n const TEST_COMMIT_PAYLOAD: gitlab.CommitPayload = {\n branch: 'main-test-patch',\n start_sha: '',\n commit_message: 'Hello world!',\n actions: [],\n };\n\n const actual = await subject.commit('lorem\/ipsum', TEST_COMMIT_PAYLOAD);\n\n expect(actual).toEqual(TEST_RESPONSE_OBJ);\n expect(fetchSpy).toHaveBeenCalledWith(\n `${TEST_BASE_URL}\/api\/v4\/projects\/lorem%2Fipsum\/repository\/commits`,\n {\n method: 'POST',\n body: JSON.stringify(TEST_COMMIT_PAYLOAD),\n headers: {\n ...TEST_AUTH_TOKEN_HEADERS,\n 'Content-Type': 'application\/json',\n },\n },\n );\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"c0b69ffd-dabf-4897-ae39-58e4ecdc69a8","name":"DeprecatedGitLabClient.ts","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['CreateProjectBranchResult', 'CreateProjectBranchVariables', 'GetMergeRequestDiffStatsResult', 'GetMergeRequestDiffStatsVariables', 'GetProjectUserPermissionsResult', 'GetProjectUserPermissionsVariables', 'GetRefMetadataResult', 'GetRefMetadataVariables', 'SearchProjectBranchesResult', 'SearchProjectBranchesVariables'], 'import_path': '.\/graphql'}, {'import_name': ['createProjectBranchMutation', 'getMergeRequestDiffStatsQuery', 'getProjectUserPermissionsQuery', 'getRefMetadataQuery', 'searchProjectBranchesQuery'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}, {'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"import type { gitlab } from '.\/types';\nimport type {\n CreateProjectBranchResult,\n CreateProjectBranchVariables,\n GetMergeRequestDiffStatsResult,\n GetMergeRequestDiffStatsVariables,\n GetProjectUserPermissionsResult,\n GetProjectUserPermissionsVariables,\n GetRefMetadataResult,\n GetRefMetadataVariables,\n SearchProjectBranchesResult,\n SearchProjectBranchesVariables,\n} from '.\/graphql';\nimport {\n createProjectBranchMutation,\n getMergeRequestDiffStatsQuery,\n getProjectUserPermissionsQuery,\n getRefMetadataQuery,\n searchProjectBranchesQuery,\n} from '.\/graphql';\nimport { createGraphQLRequest } from '.\/createGraphQLRequest';\nimport type { DefaultGitLabClient } from '.\/DefaultGitLabClient';\nimport * as gitlabApi from '.\/gitlabApi';\n\n\/**\n * @deprecated\n *\/\nexport class DeprecatedGitLabClient {\n readonly #client: DefaultGitLabClient;\n\n constructor(client: DefaultGitLabClient) {\n this.#client = client;\n }\n\n get defaultClient() {\n return this.#client;\n }\n\n async fetchRefMetadata(params: GetRefMetadataVariables) {\n const request = createGraphQLRequest(\n getRefMetadataQuery,\n params,\n );\n\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.repository;\n }\n\n async fetchProjectUserPermissions(projectPath: string) {\n const request = createGraphQLRequest<\n GetProjectUserPermissionsResult,\n GetProjectUserPermissionsVariables\n >(getProjectUserPermissionsQuery, {\n projectPath,\n });\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.userPermissions;\n }\n\n async fetchProjectBranches(params: SearchProjectBranchesVariables) {\n const request = createGraphQLRequest<\n SearchProjectBranchesResult,\n SearchProjectBranchesVariables\n >(searchProjectBranchesQuery, params);\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.repository.branchNames || [];\n }\n\n async createProjectBranch(params: CreateProjectBranchVariables) {\n const request = createGraphQLRequest(\n createProjectBranchMutation,\n params,\n );\n const result = await this.#client.fetchFromApi(request);\n\n return result.createBranch;\n }\n\n async fetchMergeRequestDiffStats({ mergeRequestId }: { mergeRequestId: string }) {\n const gid = `gid:\/\/gitlab\/MergeRequest\/${mergeRequestId}`;\n\n const request = createGraphQLRequest<\n GetMergeRequestDiffStatsResult,\n GetMergeRequestDiffStatsVariables\n >(getMergeRequestDiffStatsQuery, { gid });\n const result = await this.#client.fetchFromApi(request);\n\n return result.mergeRequest.diffStats;\n }\n\n fetchProject(projectId: string): Promise {\n const request = gitlabApi.getProject.createRequest({\n projectId,\n });\n\n return this.#client.fetchFromApi(request);\n }\n\n fetchMergeRequest(projectId: string, mrId: string): Promise {\n const request = gitlabApi.getMergeRequest.createRequest({\n projectId,\n mrId,\n });\n\n return this.#client.fetchFromApi(request);\n }\n\n fetchProjectBranch(projectId: string, branchName: string): Promise {\n const request = gitlabApi.getProjectBranch.createRequest({\n projectId,\n branchName,\n });\n\n return this.#client.fetchFromApi(request);\n }\n\n fetchTree(projectId: string, ref: string): Promise {\n const request = gitlabApi.getProjectRepositoryTree.createRequest({\n projectId,\n ref,\n recursive: 'true',\n pagination: 'none',\n });\n\n return this.#client.fetchFromApi(request);\n }\n\n commit(projectId: string, payload: gitlab.CommitPayload): Promise {\n const request = gitlabApi.postProjectCommit.createRequest(\n {\n projectId,\n },\n payload,\n );\n\n return this.#client.fetchFromApi(request);\n }\n\n async fetchFileRaw(projectId: string, ref: string, path: string): Promise {\n const request = gitlabApi.getRawFile.createRequest({\n projectId,\n ref,\n path,\n });\n\n return this.#client.fetchBufferFromApi(request);\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b9182ed9-bb05-4134-8e6a-5450208f0467","name":"constructor","imports":"[{'import_name': ['DefaultGitLabClient'], 'import_path': '.\/DefaultGitLabClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"constructor(client: DefaultGitLabClient) {\n this.#client = client;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"abf9d694-2246-4e79-84d3-f453916cd15c","name":"defaultClient","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"get defaultClient() {\n return this.#client;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e7e3b453-20c0-4f67-8fc3-c50a15137857","name":"fetchRefMetadata","imports":"[{'import_name': ['GetRefMetadataResult', 'GetRefMetadataVariables'], 'import_path': '.\/graphql'}, {'import_name': ['getRefMetadataQuery'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async fetchRefMetadata(params: GetRefMetadataVariables) {\n const request = createGraphQLRequest(\n getRefMetadataQuery,\n params,\n );\n\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.repository;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"df52a245-4d16-453c-98ad-ad30c4e405bb","name":"fetchProjectUserPermissions","imports":"[{'import_name': ['GetProjectUserPermissionsResult', 'GetProjectUserPermissionsVariables'], 'import_path': '.\/graphql'}, {'import_name': ['getProjectUserPermissionsQuery'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async fetchProjectUserPermissions(projectPath: string) {\n const request = createGraphQLRequest<\n GetProjectUserPermissionsResult,\n GetProjectUserPermissionsVariables\n >(getProjectUserPermissionsQuery, {\n projectPath,\n });\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.userPermissions;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"489a31ca-60d0-4b72-b441-f68ac1d8c57e","name":"fetchProjectBranches","imports":"[{'import_name': ['SearchProjectBranchesResult', 'SearchProjectBranchesVariables'], 'import_path': '.\/graphql'}, {'import_name': ['searchProjectBranchesQuery'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async fetchProjectBranches(params: SearchProjectBranchesVariables) {\n const request = createGraphQLRequest<\n SearchProjectBranchesResult,\n SearchProjectBranchesVariables\n >(searchProjectBranchesQuery, params);\n const result = await this.#client.fetchFromApi(request);\n\n return result.project.repository.branchNames || [];\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"72f0732e-896d-48fa-bc3c-db6eafc12f98","name":"createProjectBranch","imports":"[{'import_name': ['CreateProjectBranchResult', 'CreateProjectBranchVariables'], 'import_path': '.\/graphql'}, {'import_name': ['createProjectBranchMutation'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async createProjectBranch(params: CreateProjectBranchVariables) {\n const request = createGraphQLRequest(\n createProjectBranchMutation,\n params,\n );\n const result = await this.#client.fetchFromApi(request);\n\n return result.createBranch;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"1bcdad8c-dd37-405c-b4d3-aaa364cb5294","name":"fetchMergeRequestDiffStats","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['GetMergeRequestDiffStatsResult', 'GetMergeRequestDiffStatsVariables'], 'import_path': '.\/graphql'}, {'import_name': ['getMergeRequestDiffStatsQuery'], 'import_path': '.\/graphql'}, {'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async fetchMergeRequestDiffStats({ mergeRequestId }: { mergeRequestId: string }) {\n const gid = `gid:\/\/gitlab\/MergeRequest\/${mergeRequestId}`;\n\n const request = createGraphQLRequest<\n GetMergeRequestDiffStatsResult,\n GetMergeRequestDiffStatsVariables\n >(getMergeRequestDiffStatsQuery, { gid });\n const result = await this.#client.fetchFromApi(request);\n\n return result.mergeRequest.diffStats;\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"536c275b-3f87-4006-bb0f-3842452b2b73","name":"fetchProject","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"fetchProject(projectId: string): Promise {\n const request = gitlabApi.getProject.createRequest({\n projectId,\n });\n\n return this.#client.fetchFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"1f3c1fb4-bac6-4c36-8d49-e92f01de9b42","name":"fetchMergeRequest","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"fetchMergeRequest(projectId: string, mrId: string): Promise {\n const request = gitlabApi.getMergeRequest.createRequest({\n projectId,\n mrId,\n });\n\n return this.#client.fetchFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"7f90348f-c3e3-427c-a553-6d679e4b0c7e","name":"fetchProjectBranch","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"fetchProjectBranch(projectId: string, branchName: string): Promise {\n const request = gitlabApi.getProjectBranch.createRequest({\n projectId,\n branchName,\n });\n\n return this.#client.fetchFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f36b42df-9937-44cf-baf5-df7eeb903f45","name":"fetchTree","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"fetchTree(projectId: string, ref: string): Promise {\n const request = gitlabApi.getProjectRepositoryTree.createRequest({\n projectId,\n ref,\n recursive: 'true',\n pagination: 'none',\n });\n\n return this.#client.fetchFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"73c89aa5-7551-499c-a2d7-a8714a9be713","name":"commit","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"commit(projectId: string, payload: gitlab.CommitPayload): Promise {\n const request = gitlabApi.postProjectCommit.createRequest(\n {\n projectId,\n },\n payload,\n );\n\n return this.#client.fetchFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"5b9bca63-1034-481f-a7b3-24b4cfc96a1f","name":"fetchFileRaw","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/DeprecatedGitLabClient.ts","code":"async fetchFileRaw(projectId: string, ref: string, path: string): Promise {\n const request = gitlabApi.getRawFile.createRequest({\n projectId,\n ref,\n path,\n });\n\n return this.#client.fetchBufferFromApi(request);\n }","parent":"{'type': 'class_declaration', 'name': 'DeprecatedGitLabClient'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"4f4bfcaa-b60e-4302-8b2c-f18505db3272","name":"createGraphQLRequest.test.ts","imports":"[{'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createGraphQLRequest.test.ts","code":"import { createGraphQLRequest } from '.\/createGraphQLRequest';\n\ntype TestResult = {\n project: {\n count: number;\n };\n};\ntype TestVariables = {\n projectId: string;\n search: string;\n};\n\nconst TEST_QUERY = 'query foo { }';\n\ndescribe('createGraphQLRequest', () => {\n it('returns a GraphQLRequest', () => {\n const variables = {\n projectId: '123\/456',\n search: 'meaning',\n };\n\n expect(createGraphQLRequest(TEST_QUERY, variables)).toEqual({\n type: 'graphql',\n query: TEST_QUERY,\n variables,\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8752cd84-9246-4f7d-953b-718ed127e786","name":"createGraphQLRequest","imports":"[{'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createGraphQLRequest.test.ts","code":"describe('createGraphQLRequest', () => {\n it('returns a GraphQLRequest', () => {\n const variables = {\n projectId: '123\/456',\n search: 'meaning',\n };\n\n expect(createGraphQLRequest(TEST_QUERY, variables)).toEqual({\n type: 'graphql',\n query: TEST_QUERY,\n variables,\n });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"575ed8c4-c309-41bf-8a91-5dc4ec3551f4","name":"returns a GraphQLRequest","imports":"[{'import_name': ['createGraphQLRequest'], 'import_path': '.\/createGraphQLRequest'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createGraphQLRequest.test.ts","code":"it('returns a GraphQLRequest', () => {\n const variables = {\n projectId: '123\/456',\n search: 'meaning',\n };\n\n expect(createGraphQLRequest(TEST_QUERY, variables)).toEqual({\n type: 'graphql',\n query: TEST_QUERY,\n variables,\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"84ff3bdd-eea5-4792-acab-aedbe4d413c6","name":"createGraphQLRequest.ts","imports":"[{'import_name': ['GraphQLRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createGraphQLRequest.ts","code":"import type { GraphQLRequest } from '@gitlab\/web-ide-interop';\n\n\/**\n * Helps create a GraphQLRequest that co-locates the:\n *\n * - Result type\n * - Variables type\n *\n * @returns a GraphQLRequest\n *\/\nexport const createGraphQLRequest = (\n query: string,\n variables: TVariables,\n): GraphQLRequest => ({\n type: 'graphql',\n query,\n \/\/ We recieve a *specific* type for `variables`, but we have to transform\n \/\/ it to the expected generic type.\n variables: variables as unknown as Record,\n});\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6612b925-734c-41e7-a730-9b663d56b7ff","name":"createGraphQLRequest","imports":"[{'import_name': ['GraphQLRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createGraphQLRequest.ts","code":"(\n query: string,\n variables: TVariables,\n): GraphQLRequest => ({\n type: 'graphql',\n query,\n \/\/ We recieve a *specific* type for `variables`, but we have to transform\n \/\/ it to the expected generic type.\n variables: variables as unknown as Record,\n})","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d746894d-200e-42b0-989f-5b1f492fd56b","name":"createHeadersProvider.test.ts","imports":"[{'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createHeadersProvider.test.ts","code":"import { createHeadersProvider } from '.\/createHeadersProvider';\n\ndescribe('DefaultAuthHeadersProvider', () => {\n it('creates a headers provider that returns expected headers', async () => {\n const headers = { 'TEST-HEADER': '123456' };\n\n const authHeadersProvider = createHeadersProvider(headers);\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(headers);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"b3f4b7f0-59dd-46a9-992b-98e00e07363d","name":"DefaultAuthHeadersProvider","imports":"[{'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createHeadersProvider.test.ts","code":"describe('DefaultAuthHeadersProvider', () => {\n it('creates a headers provider that returns expected headers', async () => {\n const headers = { 'TEST-HEADER': '123456' };\n\n const authHeadersProvider = createHeadersProvider(headers);\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(headers);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"ea2aa2d3-9d76-4360-8931-cd1b553b1fa4","name":"creates a headers provider that returns expected headers","imports":"[{'import_name': ['createHeadersProvider'], 'import_path': '.\/createHeadersProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createHeadersProvider.test.ts","code":"it('creates a headers provider that returns expected headers', async () => {\n const headers = { 'TEST-HEADER': '123456' };\n\n const authHeadersProvider = createHeadersProvider(headers);\n\n const actual = await authHeadersProvider.getHeaders();\n\n expect(actual).toEqual(headers);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"261197ae-1470-4492-adef-afdf2fcfd00a","name":"createHeadersProvider.ts","imports":"[{'import_name': ['AuthHeadersProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createHeadersProvider.ts","code":"import type { AuthHeadersProvider } from '.\/types';\n\nexport const createHeadersProvider = (headers: Record): AuthHeadersProvider => ({\n getHeaders: () => Promise.resolve(headers),\n});\n\nexport const NOOP_AUTH_HEADERS_PROVIDER = createHeadersProvider({});\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"316d2a67-f022-46ba-b69a-a1daf70ab915","name":"createHeadersProvider","imports":"[{'import_name': ['AuthHeadersProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createHeadersProvider.ts","code":"(headers: Record): AuthHeadersProvider => ({\n getHeaders: () => Promise.resolve(headers),\n})","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"de2fb1a9-8e4e-4d9f-b4b0-65a1e45762c7","name":"createResponseError.test.ts","imports":"[{'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['FetchError'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.test.ts","code":"import 'whatwg-fetch';\nimport { createResponseError } from '.\/createResponseError';\nimport { FetchError } from '.\/types';\n\ndescribe('createResponseError', () => {\n describe('default', () => {\n it.each`\n description | contentType | body | expectedMessage\n ${'handles an error response with a json body'} | ${'application\/json'} | ${'{ \"bar\": \"foo\" }'} | ${{ status: 423, body: { bar: 'foo' } }}\n ${'handles an error response with a malformed json'} | ${'application\/json'} | ${'{ \"bar\":'} | ${{ status: 423, body: '' }}\n ${'handles an error response with a text body'} | ${'text\/plain'} | ${'bar foo'} | ${{ status: 423, body: 'bar foo' }}\n `('$description', async ({ contentType, body, expectedMessage }) => {\n const error = await createResponseError(\n new Response(body, {\n headers: new Headers({ 'Content-Type': contentType }),\n status: 423,\n }),\n );\n\n expect(error).toBeInstanceOf(FetchError);\n expect(error.message).toBe(JSON.stringify(expectedMessage));\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"12b11533-e7eb-4e1a-acd9-f2a8fe8c047c","name":"createResponseError","imports":"[{'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['FetchError'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.test.ts","code":"describe('createResponseError', () => {\n describe('default', () => {\n it.each`\n description | contentType | body | expectedMessage\n ${'handles an error response with a json body'} | ${'application\/json'} | ${'{ \"bar\": \"foo\" }'} | ${{ status: 423, body: { bar: 'foo' } }}\n ${'handles an error response with a malformed json'} | ${'application\/json'} | ${'{ \"bar\":'} | ${{ status: 423, body: '' }}\n ${'handles an error response with a text body'} | ${'text\/plain'} | ${'bar foo'} | ${{ status: 423, body: 'bar foo' }}\n `('$description', async ({ contentType, body, expectedMessage }) => {\n const error = await createResponseError(\n new Response(body, {\n headers: new Headers({ 'Content-Type': contentType }),\n status: 423,\n }),\n );\n\n expect(error).toBeInstanceOf(FetchError);\n expect(error.message).toBe(JSON.stringify(expectedMessage));\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8e9e37f0-3930-4335-b8ce-74a9d32117bd","name":"default","imports":"[{'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['FetchError'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.test.ts","code":"describe('default', () => {\n it.each`\n description | contentType | body | expectedMessage\n ${'handles an error response with a json body'} | ${'application\/json'} | ${'{ \"bar\": \"foo\" }'} | ${{ status: 423, body: { bar: 'foo' } }}\n ${'handles an error response with a malformed json'} | ${'application\/json'} | ${'{ \"bar\":'} | ${{ status: 423, body: '' }}\n ${'handles an error response with a text body'} | ${'text\/plain'} | ${'bar foo'} | ${{ status: 423, body: 'bar foo' }}\n `('$description', async ({ contentType, body, expectedMessage }) => {\n const error = await createResponseError(\n new Response(body, {\n headers: new Headers({ 'Content-Type': contentType }),\n status: 423,\n }),\n );\n\n expect(error).toBeInstanceOf(FetchError);\n expect(error.message).toBe(JSON.stringify(expectedMessage));\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"4832e106-34db-4c32-b0e8-246f18320260","name":"createResponseError.ts","imports":"[{'import_name': ['FetchError'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.ts","code":"import { FetchError } from '.\/types';\n\nasync function getResponseBody(response: Response): Promise {\n try {\n if (response.headers.get('Content-Type') === 'application\/json') {\n return await response.json();\n }\n\n \/\/ note: Let's just return a text representation of the response as a sensible default\n return await response.text();\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error(`Failed to parse response body of ${response.url}`, e);\n\n return '';\n }\n}\n\nexport async function createResponseError(response: Response) {\n const body = await getResponseBody(response);\n\n return new FetchError(response, body);\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"417a0e3c-f0e2-48ec-9d15-6ed1eb4b908b","name":"getResponseBody","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.ts","code":"async function getResponseBody(response: Response): Promise {\n try {\n if (response.headers.get('Content-Type') === 'application\/json') {\n return await response.json();\n }\n\n \/\/ note: Let's just return a text representation of the response as a sensible default\n return await response.text();\n } catch (e) {\n \/\/ eslint-disable-next-line no-console\n console.error(`Failed to parse response body of ${response.url}`, e);\n\n return '';\n }\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b94b7b05-009d-49f6-b58f-05a133883c5c","name":"createResponseError","imports":"[{'import_name': ['FetchError'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/createResponseError.ts","code":"async function createResponseError(response: Response) {\n const body = await getResponseBody(response);\n\n return new FetchError(response, body);\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"71c83f5c-f07b-4862-b99a-fef97293c3b4","name":"declareEndpoint.test.ts","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"import { declareEndpoint } from '.\/declareEndpoint';\n\nconst TEST_PATH = 'foo\/:id\/test\/foo';\n\ndescribe('declareEndpoint', () => {\n it('GET endpoint with params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('GET endpoint with params then buffer', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .withBufferReturnType()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('GET endpoint with buffer then params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withBufferReturnType()\n .withPathParams<{ id: string; search: string }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('POST endpoint with params', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withBodyType()\n .withReturnType<{ count: [] }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' }, [1, 2, 3])).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n body: [1, 2, 3],\n });\n });\n\n it('POST endpoint with custom headers', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string }>()\n .withBodyType<{ data: string }>()\n .withReturnType<{ success: boolean }>()\n .build();\n\n const headers = { 'Content-Type': 'application\/json' };\n const result = endpoint.createRequest({ id: '123' }, { data: 'test' }, headers);\n\n expect(result).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123\/test\/foo',\n body: { data: 'test' },\n headers: { 'Content-Type': 'application\/json' },\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"24ff610f-950b-4641-bda3-1301a707bc9a","name":"declareEndpoint","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"describe('declareEndpoint', () => {\n it('GET endpoint with params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('GET endpoint with params then buffer', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .withBufferReturnType()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('GET endpoint with buffer then params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withBufferReturnType()\n .withPathParams<{ id: string; search: string }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n });\n\n it('POST endpoint with params', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withBodyType()\n .withReturnType<{ count: [] }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' }, [1, 2, 3])).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n body: [1, 2, 3],\n });\n });\n\n it('POST endpoint with custom headers', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string }>()\n .withBodyType<{ data: string }>()\n .withReturnType<{ success: boolean }>()\n .build();\n\n const headers = { 'Content-Type': 'application\/json' };\n const result = endpoint.createRequest({ id: '123' }, { data: 'test' }, headers);\n\n expect(result).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123\/test\/foo',\n body: { data: 'test' },\n headers: { 'Content-Type': 'application\/json' },\n });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"7b3f7620-757d-47bb-8e26-98ab74d13639","name":"GET endpoint with params","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"it('GET endpoint with params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"eebc1799-1f19-49c5-89dc-419f1d2381fa","name":"GET endpoint with params then buffer","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"it('GET endpoint with params then buffer', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withReturnType<{ result: number }>()\n .withBufferReturnType()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"160196f0-ade8-411e-8ede-893e7ef2770f","name":"GET endpoint with buffer then params","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"it('GET endpoint with buffer then params', () => {\n const endpoint = declareEndpoint('GET', TEST_PATH)\n .withBufferReturnType()\n .withPathParams<{ id: string; search: string }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' })).toEqual({\n method: 'GET',\n type: 'rest-buffer',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"8b4fa846-91e6-45ad-8e40-4789979044e2","name":"POST endpoint with params","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"it('POST endpoint with params', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string; search: string }>()\n .withBodyType()\n .withReturnType<{ count: [] }>()\n .build();\n\n expect(endpoint.createRequest({ id: '123\/456', search: 'meaning' }, [1, 2, 3])).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123%2F456\/test\/foo?search=meaning',\n body: [1, 2, 3],\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"38b91cba-5b73-4c7a-95ad-06c63973ef9f","name":"POST endpoint with custom headers","imports":"[{'import_name': ['declareEndpoint'], 'import_path': '.\/declareEndpoint'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.test.ts","code":"it('POST endpoint with custom headers', () => {\n const endpoint = declareEndpoint('POST', TEST_PATH)\n .withPathParams<{ id: string }>()\n .withBodyType<{ data: string }>()\n .withReturnType<{ success: boolean }>()\n .build();\n\n const headers = { 'Content-Type': 'application\/json' };\n const result = endpoint.createRequest({ id: '123' }, { data: 'test' }, headers);\n\n expect(result).toEqual({\n method: 'POST',\n type: 'rest',\n path: 'foo\/123\/test\/foo',\n body: { data: 'test' },\n headers: { 'Content-Type': 'application\/json' },\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"9cdffa25-aab8-4db3-a9be-af271e2914bd","name":"declareEndpoint.ts","imports":"[{'import_name': ['EndpointMethod', 'DefaultPathParams', 'PathParams', 'DefaultReturnType', 'DefaultBodyParams', 'GetEndpoint', 'GetBufferEndpoint', 'PostEndpoint'], 'import_path': '..\/types'}, {'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"\/* eslint-disable max-classes-per-file *\/\nimport type {\n EndpointMethod,\n DefaultPathParams,\n PathParams,\n DefaultReturnType,\n DefaultBodyParams,\n GetEndpoint,\n GetBufferEndpoint,\n PostEndpoint,\n} from '..\/types';\nimport { resolvePathParams } from '.\/resolvePathParams';\n\n\/\/ region: builder classes ---------------------------------------------\n\nclass BaseEndpointBuilder {\n protected path: string;\n\n constructor(path: string) {\n this.path = path;\n }\n}\n\n\/\/ region: builder classes (POST) --------------------------------------\n\nclass PostEndpointBuilder<\n TReturnType = DefaultReturnType,\n TPathParams extends PathParams = DefaultPathParams,\n TBodyParams = DefaultBodyParams,\n> extends BaseEndpointBuilder {\n withReturnType(): PostEndpointBuilder {\n return this;\n }\n\n withPathParams(): PostEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as PostEndpointBuilder;\n }\n\n withBodyType(): PostEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as PostEndpointBuilder;\n }\n\n build(): PostEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams, body: TBodyParams, headers?: Record) {\n return {\n type: 'rest',\n method: 'POST',\n path: resolvePathParams(path, params),\n body,\n ...(headers && { headers }),\n };\n },\n };\n }\n}\n\n\/\/ region: builder classes (GET BUFFER) --------------------------------\n\nclass GetBufferEndpointBuilder<\n TPathParams extends PathParams = DefaultPathParams,\n> extends BaseEndpointBuilder {\n withPathParams(): GetBufferEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as GetBufferEndpointBuilder;\n }\n\n build(): GetBufferEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams) {\n return {\n type: 'rest-buffer',\n method: 'GET',\n path: resolvePathParams(path, params),\n };\n },\n };\n }\n}\n\n\/\/ region: builder classes (GET) ---------------------------------------\n\nclass GetEndpointBuilder<\n TReturnType = DefaultReturnType,\n TPathParams extends PathParams = DefaultPathParams,\n> extends BaseEndpointBuilder {\n withReturnType(): GetEndpointBuilder {\n return this;\n }\n\n withBufferReturnType(): GetBufferEndpointBuilder {\n return new GetBufferEndpointBuilder(this.path);\n }\n\n withPathParams(): GetEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as GetEndpointBuilder;\n }\n\n build(): GetEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams) {\n return {\n type: 'rest',\n method: 'GET',\n path: resolvePathParams(path, params),\n };\n },\n };\n }\n}\n\n\/\/ region: export ------------------------------------------------------\n\nexport function declareEndpoint(method: 'POST', path: string): PostEndpointBuilder;\nexport function declareEndpoint(method: 'GET', path: string): GetEndpointBuilder;\nexport function declareEndpoint(\n method: EndpointMethod,\n path: string,\n): PostEndpointBuilder | GetEndpointBuilder {\n if (method === 'GET') {\n return new GetEndpointBuilder(path);\n }\n\n if (method === 'POST') {\n return new PostEndpointBuilder(path);\n }\n\n throw new Error(`Unexpected method found! ${method}`);\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"a3cb3450-5b16-4a16-a969-b5507cc39c62","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"constructor(path: string) {\n this.path = path;\n }","parent":"{'type': 'class_declaration', 'name': 'BaseEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d9487144-f641-4797-b420-f567ba8d8900","name":"withReturnType","imports":"[{'import_name': ['PathParams', 'PostEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withReturnType(): PostEndpointBuilder {\n return this;\n }","parent":"{'type': 'class_declaration', 'name': 'PostEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b3284f21-93cb-4dbf-97f5-7e808d573e22","name":"withPathParams","imports":"[{'import_name': ['PathParams', 'PostEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withPathParams(): PostEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as PostEndpointBuilder;\n }","parent":"{'type': 'class_declaration', 'name': 'PostEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bca55229-962b-444d-a16e-18c37ba66aad","name":"withBodyType","imports":"[{'import_name': ['PathParams', 'PostEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withBodyType(): PostEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as PostEndpointBuilder;\n }","parent":"{'type': 'class_declaration', 'name': 'PostEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b9f152b8-be45-4037-a821-54957a65a1ed","name":"build","imports":"[{'import_name': ['PathParams', 'PostEndpoint'], 'import_path': '..\/types'}, {'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"build(): PostEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams, body: TBodyParams, headers?: Record) {\n return {\n type: 'rest',\n method: 'POST',\n path: resolvePathParams(path, params),\n body,\n ...(headers && { headers }),\n };\n },\n };\n }","parent":"{'type': 'class_declaration', 'name': 'PostEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fd5c3532-9b11-45a5-9c56-b9485687a94e","name":"withPathParams","imports":"[{'import_name': ['PathParams', 'GetBufferEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withPathParams(): GetBufferEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as GetBufferEndpointBuilder;\n }","parent":"{'type': 'class_declaration', 'name': 'GetBufferEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6b26bd98-086e-47bd-8550-22dc75f5e8f2","name":"build","imports":"[{'import_name': ['PathParams', 'GetBufferEndpoint'], 'import_path': '..\/types'}, {'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"build(): GetBufferEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams) {\n return {\n type: 'rest-buffer',\n method: 'GET',\n path: resolvePathParams(path, params),\n };\n },\n };\n }","parent":"{'type': 'class_declaration', 'name': 'GetBufferEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"4f59a69f-0bc5-4bec-b87a-08500bc6c05e","name":"withReturnType","imports":"[{'import_name': ['PathParams', 'GetEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withReturnType(): GetEndpointBuilder {\n return this;\n }","parent":"{'type': 'class_declaration', 'name': 'GetEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"a908a5c4-14a0-4c08-a0ad-e05e23c2ff86","name":"withBufferReturnType","imports":"[{'import_name': ['PathParams', 'GetBufferEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withBufferReturnType(): GetBufferEndpointBuilder {\n return new GetBufferEndpointBuilder(this.path);\n }","parent":"{'type': 'class_declaration', 'name': 'GetEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9f351788-1ce4-45ce-b67a-d1aa172a87f9","name":"withPathParams","imports":"[{'import_name': ['PathParams', 'GetEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"withPathParams(): GetEndpointBuilder {\n \/\/ what: Cast to unknown first since TS doesn't like us changing a generic.\n \/\/ why: This is safe because we don't actually \"use\" the generic until \"build\".\n return this as unknown as GetEndpointBuilder;\n }","parent":"{'type': 'class_declaration', 'name': 'GetEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"021ac800-3d9b-4b4d-b77c-d66d1e850686","name":"build","imports":"[{'import_name': ['PathParams', 'GetEndpoint'], 'import_path': '..\/types'}, {'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"build(): GetEndpoint {\n \/\/ what: Pull variables out of `this` so they are owned by createRequest closure\n const { path } = this;\n\n return {\n createRequest(params: TPathParams) {\n return {\n type: 'rest',\n method: 'GET',\n path: resolvePathParams(path, params),\n };\n },\n };\n }","parent":"{'type': 'class_declaration', 'name': 'GetEndpointBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"36bd1763-84c1-4151-bc07-6c3d662d4923","name":"declareEndpoint","imports":"[{'import_name': ['EndpointMethod', 'GetEndpoint', 'PostEndpoint'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/declareEndpoint.ts","code":"function declareEndpoint(\n method: EndpointMethod,\n path: string,\n): PostEndpointBuilder | GetEndpointBuilder {\n if (method === 'GET') {\n return new GetEndpointBuilder(path);\n }\n\n if (method === 'POST') {\n return new PostEndpointBuilder(path);\n }\n\n throw new Error(`Unexpected method found! ${method}`);\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"faff8d23-69d8-4f2e-bfd9-8373608260f5","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/index.ts","code":"export * from '.\/declareEndpoint';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"ab7c6566-d845-4086-93d8-866e85196ef7","name":"resolvePathParams.test.ts","imports":"[{'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.test.ts","code":"import { resolvePathParams } from '.\/resolvePathParams';\n\ndescribe('resolvePathParams', () => {\n it.each`\n path | params | expectation\n ${''} | ${{}} | ${''}\n ${'\/foo'} | ${{}} | ${'\/foo'}\n ${'\/foo\/:id\/bar'} | ${{}} | ${'\/foo\/:id\/bar'}\n ${'\/foo\/:id\/bar'} | ${{ id: '123' }} | ${'\/foo\/123\/bar'}\n ${'\/foo\/:id\/bar\/:id_test'} | ${{ id: '123' }} | ${'\/foo\/123\/bar\/:id_test'}\n ${'\/foo\/:id\/bar\/:id_2'} | ${{ id: '123', id_2: 'z' }} | ${'\/foo\/123\/bar\/z'}\n ${'\/foo\/:projectId\/bar'} | ${{ projectId: 'gitlab-org\/gitlab' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar'}\n ${'\/foo\/:projectId\/bar'} | ${{ projectId: 'gitlab-org\/gitlab', ref: '000111', extra: '123&456' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar?ref=000111&extra=123%26456'}\n ${'\/foo\/:projectId\/bar\/:(skipEncode)path'} | ${{ projectId: 'gitlab-org\/gitlab', path: 'src\/main.ts' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar\/src\/main.ts'}\n ${'\/foo\/:projectId\/bar\/:(dne)path'} | ${{ projectId: 'gitlab-org\/gitlab', path: 'src\/main.ts' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar\/src%2Fmain.ts'}\n `(\n 'with path=$path and params=$params, should be $expectation',\n ({ path, params, expectation }) => {\n const actual = resolvePathParams(path, params);\n\n expect(actual).toBe(expectation);\n },\n );\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"fde90f46-2819-49d6-9b69-1994f3028cb8","name":"resolvePathParams","imports":"[{'import_name': ['resolvePathParams'], 'import_path': '.\/resolvePathParams'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.test.ts","code":"describe('resolvePathParams', () => {\n it.each`\n path | params | expectation\n ${''} | ${{}} | ${''}\n ${'\/foo'} | ${{}} | ${'\/foo'}\n ${'\/foo\/:id\/bar'} | ${{}} | ${'\/foo\/:id\/bar'}\n ${'\/foo\/:id\/bar'} | ${{ id: '123' }} | ${'\/foo\/123\/bar'}\n ${'\/foo\/:id\/bar\/:id_test'} | ${{ id: '123' }} | ${'\/foo\/123\/bar\/:id_test'}\n ${'\/foo\/:id\/bar\/:id_2'} | ${{ id: '123', id_2: 'z' }} | ${'\/foo\/123\/bar\/z'}\n ${'\/foo\/:projectId\/bar'} | ${{ projectId: 'gitlab-org\/gitlab' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar'}\n ${'\/foo\/:projectId\/bar'} | ${{ projectId: 'gitlab-org\/gitlab', ref: '000111', extra: '123&456' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar?ref=000111&extra=123%26456'}\n ${'\/foo\/:projectId\/bar\/:(skipEncode)path'} | ${{ projectId: 'gitlab-org\/gitlab', path: 'src\/main.ts' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar\/src\/main.ts'}\n ${'\/foo\/:projectId\/bar\/:(dne)path'} | ${{ projectId: 'gitlab-org\/gitlab', path: 'src\/main.ts' }} | ${'\/foo\/gitlab-org%2Fgitlab\/bar\/src%2Fmain.ts'}\n `(\n 'with path=$path and params=$params, should be $expectation',\n ({ path, params, expectation }) => {\n const actual = resolvePathParams(path, params);\n\n expect(actual).toBe(expectation);\n },\n );\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"53e5091f-28af-4a9e-b958-44deb3c56561","name":"resolvePathParams.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.ts","code":"const VAR_OPTION_SKIP_ENCODE = 'skipEncode';\n\nconst getQueryParams = (params: Record, keys: Set) => {\n if (keys.size === 0) {\n return '';\n }\n\n const urlSearchParams = new URLSearchParams();\n keys.forEach(key => {\n urlSearchParams.append(key, params[key]);\n });\n\n return `?${urlSearchParams.toString()}`;\n};\n\nconst parsePathVariableOptions = (pathVarOptionsStr: string): string[] => {\n if (pathVarOptionsStr) {\n \/\/ Strip wrapping parenthesis and split on `,`\n return pathVarOptionsStr.substring(1, pathVarOptionsStr.length - 1).split(',');\n }\n\n return [];\n};\n\nexport const resolvePathParams = (path: string, params: Record = {}) => {\n const remainingKeys = new Set(Object.keys(params));\n\n const pathWithParams = path.replace(\n \/:(\\(.+?\\))?([\\w_]+)\/g,\n (substring: string, pathVarOptionsStr: string, pathVar: string) => {\n if (pathVar in params) {\n remainingKeys.delete(pathVar);\n\n const value = params[pathVar];\n const pathVarOptions = parsePathVariableOptions(pathVarOptionsStr);\n const shouldEncode = !pathVarOptions.includes(VAR_OPTION_SKIP_ENCODE);\n\n return shouldEncode ? encodeURIComponent(value) : value;\n }\n\n return substring;\n },\n );\n\n const query = getQueryParams(params, remainingKeys);\n\n return `${pathWithParams}${query}`;\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8a4f9b17-ce7f-428c-9c56-7b82b27bc37d","name":"getQueryParams","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.ts","code":"(params: Record, keys: Set) => {\n if (keys.size === 0) {\n return '';\n }\n\n const urlSearchParams = new URLSearchParams();\n keys.forEach(key => {\n urlSearchParams.append(key, params[key]);\n });\n\n return `?${urlSearchParams.toString()}`;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"778cd502-5658-4989-a93d-2d634ecb0811","name":"parsePathVariableOptions","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.ts","code":"(pathVarOptionsStr: string): string[] => {\n if (pathVarOptionsStr) {\n \/\/ Strip wrapping parenthesis and split on `,`\n return pathVarOptionsStr.substring(1, pathVarOptionsStr.length - 1).split(',');\n }\n\n return [];\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"5b4f02e2-a3c9-4594-851c-eb4e0879d77e","name":"resolvePathParams","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/endpoints\/resolvePathParams.ts","code":"(path: string, params: Record = {}) => {\n const remainingKeys = new Set(Object.keys(params));\n\n const pathWithParams = path.replace(\n \/:(\\(.+?\\))?([\\w_]+)\/g,\n (substring: string, pathVarOptionsStr: string, pathVar: string) => {\n if (pathVar in params) {\n remainingKeys.delete(pathVar);\n\n const value = params[pathVar];\n const pathVarOptions = parsePathVariableOptions(pathVarOptionsStr);\n const shouldEncode = !pathVarOptions.includes(VAR_OPTION_SKIP_ENCODE);\n\n return shouldEncode ? encodeURIComponent(value) : value;\n }\n\n return substring;\n },\n );\n\n const query = getQueryParams(params, remainingKeys);\n\n return `${pathWithParams}${query}`;\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"4941e676-2628-4f44-a268-267be61651aa","name":"gitlabApi.ts","imports":"[{'import_name': ['gitlab'], 'import_path': '.\/types'}, {'import_name': ['declareEndpoint'], 'import_path': '.\/endpoints'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/gitlabApi.ts","code":"import type { gitlab } from '.\/types';\nimport { declareEndpoint } from '.\/endpoints';\n\nexport const getProject = declareEndpoint('GET', 'projects\/:projectId')\n .withPathParams<{ projectId: string }>()\n .withReturnType()\n .build();\n\nexport const getProjectPushRules = declareEndpoint('GET', 'projects\/:projectId\/push_rule')\n .withPathParams<{ projectId: string }>()\n .withReturnType()\n .build();\n\nexport const getMergeRequest = declareEndpoint('GET', 'projects\/:projectId\/merge_requests\/:mrId')\n .withPathParams<{ projectId: string; mrId: string }>()\n .withReturnType()\n .build();\n\nexport const getProjectBranch = declareEndpoint(\n 'GET',\n 'projects\/:projectId\/repository\/branches\/:branchName',\n)\n .withPathParams<{ projectId: string; branchName: string }>()\n .withReturnType()\n .build();\n\nexport const getProjectRepositoryTree = declareEndpoint(\n 'GET',\n 'projects\/:projectId\/repository\/tree',\n)\n .withPathParams<{ projectId: string; ref: string; recursive: string; pagination: string }>()\n .withReturnType()\n .build();\n\nexport const postProjectCommit = declareEndpoint('POST', 'projects\/:projectId\/repository\/commits')\n .withPathParams<{ projectId: string }>()\n .withBodyType()\n .withReturnType()\n .build();\n\nexport const getRawFile = declareEndpoint('GET', 'projects\/:projectId\/repository\/files\/:path\/raw')\n .withPathParams<{ projectId: string; path: string; ref: string }>()\n .withBufferReturnType()\n .build();\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"e8e4c92c-fb3a-4e49-988b-197672523bf7","name":"createProjectBranch.mutation.ts","imports":"[{'import_name': ['gql'], 'import_path': 'graphql-request'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/createProjectBranch.mutation.ts","code":"import { gql } from 'graphql-request';\n\nexport const createProjectBranchMutation = gql`\n mutation createProjectBranch($projectPath: ID!, $name: String!, $ref: String!) {\n createBranch(input: { projectPath: $projectPath, name: $name, ref: $ref }) {\n errors\n branch {\n name\n }\n }\n }\n`;\n\nexport interface CreateProjectBranchVariables {\n projectPath: string;\n name: string;\n ref: string;\n}\n\nexport interface CreateProjectBranchResult {\n createBranch: {\n errors: string[];\n branch: {\n name: string;\n };\n };\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"5a41b598-3bcb-46c7-87e5-084d98250098","name":"getMergeRequestDiffStats.query.ts","imports":"[{'import_name': ['gql'], 'import_path': 'graphql-request'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/getMergeRequestDiffStats.query.ts","code":"import { gql } from 'graphql-request';\n\nexport const getMergeRequestDiffStatsQuery = gql`\n query getMergeRequestDiffStats($gid: MergeRequestID!) {\n mergeRequest(id: $gid) {\n diffStats {\n path\n additions\n deletions\n }\n }\n }\n`;\n\nexport interface GetMergeRequestDiffStatsVariables {\n gid: string;\n}\n\nexport interface GetMergeRequestDiffStatsResult {\n mergeRequest: {\n diffStats: { path: string; additions: number; deletions: number }[];\n };\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"8a37b426-09ec-474b-ab19-b179778331ce","name":"getProjectUserPermissions.query.ts","imports":"[{'import_name': ['gql'], 'import_path': 'graphql-request'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/getProjectUserPermissions.query.ts","code":"import { gql } from 'graphql-request';\n\nexport const getProjectUserPermissionsQuery = gql`\n query getProjectUserPermissions($projectPath: ID!) {\n project(fullPath: $projectPath) {\n userPermissions {\n createMergeRequestIn\n readMergeRequest\n pushCode\n }\n }\n }\n`;\n\nexport interface GetProjectUserPermissionsVariables {\n projectPath: string;\n}\n\nexport interface ProjectUserPermissions {\n createMergeRequestIn: boolean;\n readMergeRequest: boolean;\n pushCode: boolean;\n}\n\nexport interface GetProjectUserPermissionsResult {\n project: {\n userPermissions: ProjectUserPermissions;\n };\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d2cfac4e-32c9-45c1-b057-5bb023d5c760","name":"getRefMetadata.query.ts","imports":"[{'import_name': ['gql'], 'import_path': 'graphql-request'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/getRefMetadata.query.ts","code":"import { gql } from 'graphql-request';\n\nexport const getRefMetadataQuery = gql`\n query getRefMetadata($ref: String!, $projectPath: ID!) {\n project(fullPath: $projectPath) {\n repository {\n tree(ref: $ref) {\n lastCommit {\n sha\n }\n }\n }\n }\n }\n`;\n\nexport interface GetRefMetadataVariables {\n ref: string;\n projectPath: string;\n}\n\nexport interface GetRefMetadataResult {\n project: {\n repository: {\n tree: {\n lastCommit: null | {\n sha: string;\n };\n };\n };\n };\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"62da8a60-2976-4d75-a05d-eec849b70fa4","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/index.ts","code":"export * from '.\/createProjectBranch.mutation';\nexport * from '.\/getMergeRequestDiffStats.query';\nexport * from '.\/getProjectUserPermissions.query';\nexport * from '.\/getRefMetadata.query';\nexport * from '.\/searchProjectBranches.query';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"bfbd09f4-d17d-41c2-97ca-a07c955260e3","name":"searchProjectBranches.query.ts","imports":"[{'import_name': ['gql'], 'import_path': 'graphql-request'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/graphql\/searchProjectBranches.query.ts","code":"import { gql } from 'graphql-request';\n\nexport const searchProjectBranchesQuery = gql`\n query searchProjectBranches(\n $projectPath: ID!\n $searchPattern: String!\n $limit: Int!\n $offset: Int!\n ) {\n project(fullPath: $projectPath) {\n repository {\n branchNames(searchPattern: $searchPattern, limit: $limit, offset: $offset)\n }\n }\n }\n`;\n\nexport interface SearchProjectBranchesVariables {\n projectPath: string;\n searchPattern: string;\n limit: number;\n offset: number;\n}\n\nexport interface SearchProjectBranchesResult {\n project: {\n repository: {\n branchNames: string[] | null;\n };\n };\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"83a75ce5-6676-4b99-bd44-516cdfe45878","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/index.ts","code":"export * from '.\/DeprecatedGitLabClient';\nexport * from '.\/DefaultGitLabClient';\nexport * from '.\/DefaultAuthProvider';\nexport * from '.\/types';\nexport * as gitlabApi from '.\/gitlabApi';\nexport * from '.\/is404Error';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"ed71d694-4b8f-4cca-8fb2-c8813aeaa610","name":"is404Error.test.ts","imports":"[{'import_name': ['createFakeResponse'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['is404Error'], 'import_path': '.\/is404Error'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/is404Error.test.ts","code":"import { createFakeResponse } from '@gitlab\/utils-test';\nimport { createResponseError } from '.\/createResponseError';\nimport { is404Error } from '.\/is404Error';\n\ndescribe('is404Error', () => {\n it.each`\n desc | factory | expectation\n ${'regular error'} | ${() => new Error('Blow up!')} | ${false}\n ${'error with 404 message'} | ${() => new Error('Something is 404-ish here')} | ${true}\n ${'response error with 404'} | ${() => createResponseError(createFakeResponse(404))} | ${true}\n ${'response error with 403'} | ${() => createResponseError(createFakeResponse(403))} | ${false}\n `('$desc = $expectation', async ({ factory, expectation }) => {\n const error = await factory();\n\n const actual = is404Error(error);\n\n expect(actual).toBe(expectation);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"be2e2c6a-37cd-45f8-a066-77d2110a4874","name":"is404Error","imports":"[{'import_name': ['createFakeResponse'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['createResponseError'], 'import_path': '.\/createResponseError'}, {'import_name': ['is404Error'], 'import_path': '.\/is404Error'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/is404Error.test.ts","code":"describe('is404Error', () => {\n it.each`\n desc | factory | expectation\n ${'regular error'} | ${() => new Error('Blow up!')} | ${false}\n ${'error with 404 message'} | ${() => new Error('Something is 404-ish here')} | ${true}\n ${'response error with 404'} | ${() => createResponseError(createFakeResponse(404))} | ${true}\n ${'response error with 403'} | ${() => createResponseError(createFakeResponse(403))} | ${false}\n `('$desc = $expectation', async ({ factory, expectation }) => {\n const error = await factory();\n\n const actual = is404Error(error);\n\n expect(actual).toBe(expectation);\n });\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"97a23571-aba5-42e4-b3c7-90fa258369ca","name":"is404Error.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/is404Error.ts","code":"const isRecord = (err: unknown): err is Record =>\n Boolean(err && typeof err === 'object');\n\nexport const is404Error = (err: unknown): boolean => {\n if (!isRecord(err)) {\n return false;\n }\n\n \/\/ note: Let's intentionally be resilient here and check for both 'status' and 'message'\n if ('status' in err) {\n return String(err.status) === '404';\n }\n\n if ('message' in err) {\n return \/404\/.test(String(err.message));\n }\n\n return false;\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"4f824f11-0635-4628-8cd8-558af968d44d","name":"isRecord","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/is404Error.ts","code":"(err: unknown): err is Record =>\n Boolean(err && typeof err === 'object')","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"259942c5-4508-489d-903a-c75cb1ec7523","name":"is404Error","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/is404Error.ts","code":"(err: unknown): boolean => {\n if (!isRecord(err)) {\n return false;\n }\n\n \/\/ note: Let's intentionally be resilient here and check for both 'status' and 'message'\n if ('status' in err) {\n return String(err.status) === '404';\n }\n\n if ('message' in err) {\n return \/404\/.test(String(err.message));\n }\n\n return false;\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"99974da5-d4e7-41c0-9287-8a5cc8768b0a","name":"client.ts","imports":"[{'import_name': ['GetRequest', 'PostRequest', 'GetBufferRequest'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/types\/client.ts","code":"import type { GetRequest, PostRequest, GetBufferRequest } from '@gitlab\/web-ide-interop';\n\nexport type EndpointMethod = GetRequest['method'] | PostRequest['method'];\nexport type PathParams = Record;\nexport type DefaultPathParams = Record;\nexport type DefaultBodyParams = never;\nexport type DefaultReturnType = unknown;\n\nexport interface AuthProvider {\n getToken(): Promise;\n}\n\nexport interface AuthHeadersProvider {\n getHeaders(): Promise>;\n}\n\nexport interface ResponseErrorBody {\n status: number;\n body?: unknown;\n}\n\nexport interface GetEndpoint {\n createRequest(params: TPathParams): GetRequest;\n}\n\nexport interface GetBufferEndpoint {\n createRequest(params: TPathParams): GetBufferRequest;\n}\n\nexport interface PostEndpoint {\n createRequest(\n pathParams: TPathParams,\n bodyParams: TBodyParams,\n headers?: Record,\n ): PostRequest;\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"a7064850-a3b9-410d-aaef-3ecc0f826789","name":"error.ts","imports":"[{'import_name': ['ResponseError'], 'import_path': '@gitlab\/web-ide-interop'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/types\/error.ts","code":"import type { ResponseError } from '@gitlab\/web-ide-interop';\n\nexport class FetchError extends Error implements ResponseError {\n status: number;\n\n constructor(response: Response, body?: unknown) {\n \/\/ note: The message **must** be JSON. This is the only way for us to pass exception\n \/\/ data from MediatorCommands ---> ExtensionHost since VSCode intercepts and wraps\n \/\/ any exception thrown from a command.\n \/\/ Once we completely remove MediatorCommands we can have a more sensible error object here.\n const { status } = response;\n const message = JSON.stringify({ status, body });\n\n super(message);\n\n this.status = response.status;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ce54b975-496d-402b-8e02-9be971505e91","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/types\/error.ts","code":"constructor(response: Response, body?: unknown) {\n \/\/ note: The message **must** be JSON. This is the only way for us to pass exception\n \/\/ data from MediatorCommands ---> ExtensionHost since VSCode intercepts and wraps\n \/\/ any exception thrown from a command.\n \/\/ Once we completely remove MediatorCommands we can have a more sensible error object here.\n const { status } = response;\n const message = JSON.stringify({ status, body });\n\n super(message);\n\n this.status = response.status;\n }","parent":"{'type': 'class_declaration', 'name': 'FetchError'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"369979a6-8daf-45ef-aa38-14656a0920d8","name":"gitlab.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/types\/gitlab.ts","code":"\/* eslint-disable-next-line @typescript-eslint\/no-namespace *\/\nexport namespace gitlab {\n export interface Commit {\n id: string;\n short_id: string;\n created_at: string;\n title: string;\n message: string;\n web_url: string;\n }\n\n export interface Branch {\n name: string;\n commit: Commit;\n web_url: string;\n can_push: boolean;\n protected: boolean;\n default: boolean;\n }\n\n \/\/ https:\/\/docs.gitlab.com\/ee\/api\/projects.html#get-single-project\n export interface Project {\n id: number;\n default_branch: string;\n web_url: string;\n name: string;\n can_create_merge_request_in: boolean;\n empty_repo: boolean;\n path_with_namespace: string;\n }\n\n \/\/ https:\/\/docs.gitlab.com\/ee\/api\/projects.html#push-rules\n export interface ProjectPushRules {\n id: number;\n project_id: number;\n commit_message_regex: string;\n commit_message_negative_regex: string;\n branch_name_regex: string;\n deny_delete_tag: false;\n created_at: string;\n member_check: boolean;\n prevent_secrets: boolean;\n author_email_regex: string;\n file_name_regex: string;\n max_file_size: number;\n commit_committer_check: boolean;\n commit_committer_name_check: boolean;\n reject_unsigned_commits: boolean;\n reject_non_dco_commits: boolean;\n }\n\n \/\/ https:\/\/docs.gitlab.com\/ee\/api\/merge_requests.html#response\n export interface MergeRequest {\n id: number;\n iid: number;\n source_branch: string;\n source_project_id: number;\n target_branch: string;\n target_project_id: number;\n web_url: string;\n diff_refs: { base_sha: string; head_sha: string; start_sha: string };\n }\n\n export interface File {\n id: string;\n last_commit_sha: string;\n path: string;\n name: string;\n extension: string;\n size: number;\n mime_type: string;\n binary: boolean;\n simple_viewer: string;\n rich_viewer: string;\n show_viewer_switcher: string;\n render_error?: string;\n raw_path: string;\n blame_path: string;\n commits_path: string;\n tree_path: string;\n permalink: string;\n }\n\n \/\/ https:\/\/docs.gitlab.com\/ee\/api\/repositories.html#list-repository-tree\n export interface RepositoryTreeItem {\n id: string;\n name: string;\n type: 'tree' | 'blob';\n path: string;\n mode: string;\n }\n\n \/\/ https:\/\/docs.gitlab.com\/ee\/api\/commits.html#create-a-commit-with-multiple-files-and-actions\n export interface CommitActionPayload {\n action: 'move' | 'create' | 'delete' | 'update';\n file_path: string;\n previous_path?: string;\n content?: string;\n encoding?: 'base64' | 'text';\n last_commit_id?: string;\n }\n\n export interface CommitPayload {\n branch: string;\n commit_message: string;\n actions: CommitActionPayload[];\n start_sha?: string;\n }\n}\n\nexport type { ProjectUserPermissions } from '..\/graphql\/getProjectUserPermissions.query';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"689d68f4-0c5f-4c43-82a0-277ff85e4f1a","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/src\/types\/index.ts","code":"export * from '.\/client';\nexport * from '.\/gitlab';\nexport * from '.\/error';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"27762ff1-2bde-47a2-9c7e-f76e08a1c87a","name":"mockResponses.ts","imports":"[{'import_name': ['CreateProjectBranchResult', 'GetMergeRequestDiffStatsResult', 'GetProjectUserPermissionsResult', 'GetRefMetadataResult', 'SearchProjectBranchesResult'], 'import_path': '..\/..\/src\/graphql'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/test-utils\/graphql\/mockResponses.ts","code":"import type {\n CreateProjectBranchResult,\n GetMergeRequestDiffStatsResult,\n GetProjectUserPermissionsResult,\n GetRefMetadataResult,\n SearchProjectBranchesResult,\n} from '..\/..\/src\/graphql';\n\nexport const createProjectBranch: CreateProjectBranchResult = {\n createBranch: {\n branch: {\n name: 'new-branch-test',\n },\n errors: [],\n },\n};\n\nexport const getMergeRequestDiffStats: GetMergeRequestDiffStatsResult = {\n mergeRequest: {\n diffStats: [\n {\n path: 'README.md',\n additions: 7,\n deletions: 77,\n },\n ],\n },\n};\n\nexport const getProjectUserPermissions: GetProjectUserPermissionsResult = {\n project: {\n userPermissions: {\n createMergeRequestIn: true,\n pushCode: false,\n readMergeRequest: true,\n },\n },\n};\n\nexport const getRefMetadata: GetRefMetadataResult = {\n project: {\n repository: {\n tree: {\n lastCommit: {\n sha: '121000',\n },\n },\n },\n },\n};\n\nexport const searchProjectBranches: SearchProjectBranchesResult = {\n project: {\n repository: {\n branchNames: ['foo', 'bar'],\n },\n },\n};\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"088d0244-6d5c-41da-832d-ab127c7b64cf","name":"mockVariables.ts","imports":"[{'import_name': ['CreateProjectBranchVariables', 'GetRefMetadataVariables', 'SearchProjectBranchesVariables'], 'import_path': '..\/..\/src\/graphql'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/gitlab-api-client\/test-utils\/graphql\/mockVariables.ts","code":"import type {\n CreateProjectBranchVariables,\n GetRefMetadataVariables,\n SearchProjectBranchesVariables,\n} from '..\/..\/src\/graphql';\n\nexport const createProjectBranch: CreateProjectBranchVariables = {\n name: 'new-branch-test',\n projectPath: 'lorem\/ipsum',\n ref: '111000',\n};\n\nexport const getRefMetadata: GetRefMetadataVariables = {\n projectPath: 'lorem\/ipsum',\n ref: '121000',\n};\n\nexport const searchProjectBranches: SearchProjectBranchesVariables = {\n limit: 100,\n offset: 0,\n projectPath: 'lorem\/ipsum',\n searchPattern: 'foo-*',\n};\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"fd77377e-92aa-43f4-9480-72db02c08c0e","name":"ConsoeLogWriter.test.ts","imports":"[{'import_name': ['ConsoleLogWriter'], 'import_path': '.\/ConsoleLogWriter'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/ConsoeLogWriter.test.ts","code":"import { ConsoleLogWriter } from '.\/ConsoleLogWriter';\nimport { LogLevel } from '.\/types';\n\nconst TEST_MESSAGE = ['Hello', new Error('Boom!')];\n\ndescribe('ConsoleLogWriter', () => {\n let consoleSpy: jest.Mock;\n\n beforeEach(() => {\n consoleSpy = jest.fn();\n\n (['trace', 'debug', 'info', 'warn', 'error', 'log'] as const).forEach(x => {\n jest.spyOn(console, x).mockImplementation((...args) => consoleSpy(x, args));\n });\n });\n\n it.each`\n logLevel | method\n ${LogLevel.Trace} | ${'trace'}\n ${LogLevel.Debug} | ${'debug'}\n ${LogLevel.Info} | ${'info'}\n ${LogLevel.Warn} | ${'warn'}\n ${LogLevel.Error} | ${'error'}\n `('with level=$logLevel, should call console.$method', ({ logLevel, method }) => {\n const writer = new ConsoleLogWriter();\n\n expect(consoleSpy).not.toHaveBeenCalled();\n\n writer.log(logLevel, ...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith(method, TEST_MESSAGE);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"18f81ee9-a502-4aad-9d5c-285bb3ae90e7","name":"ConsoleLogWriter","imports":"[{'import_name': ['ConsoleLogWriter'], 'import_path': '.\/ConsoleLogWriter'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/ConsoeLogWriter.test.ts","code":"describe('ConsoleLogWriter', () => {\n let consoleSpy: jest.Mock;\n\n beforeEach(() => {\n consoleSpy = jest.fn();\n\n (['trace', 'debug', 'info', 'warn', 'error', 'log'] as const).forEach(x => {\n jest.spyOn(console, x).mockImplementation((...args) => consoleSpy(x, args));\n });\n });\n\n it.each`\n logLevel | method\n ${LogLevel.Trace} | ${'trace'}\n ${LogLevel.Debug} | ${'debug'}\n ${LogLevel.Info} | ${'info'}\n ${LogLevel.Warn} | ${'warn'}\n ${LogLevel.Error} | ${'error'}\n `('with level=$logLevel, should call console.$method', ({ logLevel, method }) => {\n const writer = new ConsoleLogWriter();\n\n expect(consoleSpy).not.toHaveBeenCalled();\n\n writer.log(logLevel, ...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith(method, TEST_MESSAGE);\n });\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"47ca1ece-a197-47a2-b626-1d3c36706c86","name":"ConsoleLogWriter.ts","imports":"[{'import_name': ['LogWriter'], 'import_path': '.\/types'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/ConsoleLogWriter.ts","code":"\/* eslint-disable no-console *\/\nimport type { LogWriter } from '.\/types';\nimport { LogLevel } from '.\/types';\n\nexport class ConsoleLogWriter implements LogWriter {\n \/\/ eslint-disable-next-line class-methods-use-this\n log(level: LogLevel, ...message: unknown[]): void {\n switch (level) {\n case LogLevel.Trace:\n console.trace(...message);\n break;\n case LogLevel.Debug:\n console.debug(...message);\n break;\n case LogLevel.Info:\n console.info(...message);\n break;\n case LogLevel.Warn:\n console.warn(...message);\n break;\n case LogLevel.Error:\n console.error(...message);\n break;\n default:\n console.log(...message);\n break;\n }\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"46f80aa6-00ca-4261-91f0-bc5f4f72b894","name":"log","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/ConsoleLogWriter.ts","code":"log(level: LogLevel, ...message: unknown[]): void {\n switch (level) {\n case LogLevel.Trace:\n console.trace(...message);\n break;\n case LogLevel.Debug:\n console.debug(...message);\n break;\n case LogLevel.Info:\n console.info(...message);\n break;\n case LogLevel.Warn:\n console.warn(...message);\n break;\n case LogLevel.Error:\n console.error(...message);\n break;\n default:\n console.log(...message);\n break;\n }\n }","parent":"{'type': 'class_declaration', 'name': 'ConsoleLogWriter'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2d6875fb-9db7-4e44-ab9a-5e6bc9a8e462","name":"Logger.test.ts","imports":"[{'import_name': ['LogWriter'], 'import_path': '.\/types'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.test.ts","code":"import type { LogWriter } from '.\/types';\nimport { LogLevel } from '.\/types';\nimport { Logger } from '.\/Logger';\n\nconst TEST_MESSAGE = ['Hello', new Error('BOOM!')];\n\ndescribe('Logger', () => {\n let spyWriter: LogWriter;\n\n beforeEach(() => {\n spyWriter = {\n log: jest.fn(),\n };\n });\n\n it.each`\n minLogLevel | method | expectedCalls\n ${LogLevel.Debug} | ${'trace'} | ${[]}\n ${LogLevel.Debug} | ${'debug'} | ${[[LogLevel.Debug, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'info'} | ${[[LogLevel.Info, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'trace'} | ${[]}\n ${LogLevel.Info} | ${'debug'} | ${[]}\n ${LogLevel.Info} | ${'info'} | ${[[LogLevel.Info, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Warn} | ${'trace'} | ${[]}\n ${LogLevel.Warn} | ${'debug'} | ${[]}\n ${LogLevel.Warn} | ${'info'} | ${[]}\n ${LogLevel.Warn} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Warn} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Error} | ${'trace'} | ${[]}\n ${LogLevel.Error} | ${'debug'} | ${[]}\n ${LogLevel.Error} | ${'info'} | ${[]}\n ${LogLevel.Error} | ${'warn'} | ${[]}\n ${LogLevel.Error} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n `(\n 'with minLogLevel=$minLogLevel, calling $method should have $expectedCalls.length',\n ({\n minLogLevel,\n method,\n expectedCalls,\n }: {\n minLogLevel: LogLevel;\n method: keyof Logger;\n expectedCalls: unknown;\n }) => {\n const logger = new Logger({ minLevel: minLogLevel, writer: spyWriter });\n\n expect(spyWriter.log).not.toHaveBeenCalled();\n\n logger[method](...TEST_MESSAGE);\n\n expect(jest.mocked(spyWriter.log).mock.calls).toEqual(expectedCalls);\n },\n );\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"6164fd91-26e2-4ffe-b411-71c618a2cd4c","name":"Logger","imports":"[{'import_name': ['LogWriter'], 'import_path': '.\/types'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.test.ts","code":"describe('Logger', () => {\n let spyWriter: LogWriter;\n\n beforeEach(() => {\n spyWriter = {\n log: jest.fn(),\n };\n });\n\n it.each`\n minLogLevel | method | expectedCalls\n ${LogLevel.Debug} | ${'trace'} | ${[]}\n ${LogLevel.Debug} | ${'debug'} | ${[[LogLevel.Debug, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'info'} | ${[[LogLevel.Info, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Debug} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'trace'} | ${[]}\n ${LogLevel.Info} | ${'debug'} | ${[]}\n ${LogLevel.Info} | ${'info'} | ${[[LogLevel.Info, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Info} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Warn} | ${'trace'} | ${[]}\n ${LogLevel.Warn} | ${'debug'} | ${[]}\n ${LogLevel.Warn} | ${'info'} | ${[]}\n ${LogLevel.Warn} | ${'warn'} | ${[[LogLevel.Warn, ...TEST_MESSAGE]]}\n ${LogLevel.Warn} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n ${LogLevel.Error} | ${'trace'} | ${[]}\n ${LogLevel.Error} | ${'debug'} | ${[]}\n ${LogLevel.Error} | ${'info'} | ${[]}\n ${LogLevel.Error} | ${'warn'} | ${[]}\n ${LogLevel.Error} | ${'error'} | ${[[LogLevel.Error, ...TEST_MESSAGE]]}\n `(\n 'with minLogLevel=$minLogLevel, calling $method should have $expectedCalls.length',\n ({\n minLogLevel,\n method,\n expectedCalls,\n }: {\n minLogLevel: LogLevel;\n method: keyof Logger;\n expectedCalls: unknown;\n }) => {\n const logger = new Logger({ minLevel: minLogLevel, writer: spyWriter });\n\n expect(spyWriter.log).not.toHaveBeenCalled();\n\n logger[method](...TEST_MESSAGE);\n\n expect(jest.mocked(spyWriter.log).mock.calls).toEqual(expectedCalls);\n },\n );\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2da135a4-780f-491b-9b07-09c35ffc1650","name":"Logger.ts","imports":"[{'import_name': ['LogWriter'], 'import_path': '.\/types'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"import type { LogWriter } from '.\/types';\nimport { LogLevel } from '.\/types';\n\nexport interface LoggerOptions {\n minLevel?: LogLevel;\n writer: LogWriter;\n}\n\nexport class Logger {\n readonly #minLevel: LogLevel;\n\n readonly #writer: LogWriter;\n\n constructor(options: LoggerOptions) {\n this.#minLevel = options.minLevel === undefined ? LogLevel.Debug : options.minLevel;\n this.#writer = options.writer;\n }\n\n trace(...message: unknown[]): void {\n this.#writeLog(LogLevel.Trace, message);\n }\n\n debug(...message: unknown[]): void {\n this.#writeLog(LogLevel.Debug, message);\n }\n\n info(...message: unknown[]): void {\n this.#writeLog(LogLevel.Info, message);\n }\n\n warn(...message: unknown[]): void {\n this.#writeLog(LogLevel.Warn, message);\n }\n\n error(...message: unknown[]): void {\n this.#writeLog(LogLevel.Error, message);\n }\n\n #writeLog(level: LogLevel, message: unknown[]): void {\n if (level < this.#minLevel) {\n return;\n }\n\n this.#writer.log(level, ...message);\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"835b32d2-f9d9-43e9-9f91-e180badbfbc2","name":"constructor","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"constructor(options: LoggerOptions) {\n this.#minLevel = options.minLevel === undefined ? LogLevel.Debug : options.minLevel;\n this.#writer = options.writer;\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6e911b41-8079-49d6-9478-0ae1f9367354","name":"trace","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"trace(...message: unknown[]): void {\n this.#writeLog(LogLevel.Trace, message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"eb6852ba-56aa-4ca6-befa-4f9a56c641f1","name":"debug","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"debug(...message: unknown[]): void {\n this.#writeLog(LogLevel.Debug, message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"53b3054d-be18-4101-ab77-b702d4156e86","name":"info","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"info(...message: unknown[]): void {\n this.#writeLog(LogLevel.Info, message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8cb5709e-1c8a-4415-8422-878b0231b2c0","name":"warn","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"warn(...message: unknown[]): void {\n this.#writeLog(LogLevel.Warn, message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d19a710a-60f3-4b99-829a-2aca1afff922","name":"error","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"error(...message: unknown[]): void {\n this.#writeLog(LogLevel.Error, message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"135acec4-7b98-4d2d-a79c-9d1309eba03c","name":"#writeLog","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/Logger.ts","code":"#writeLog(level: LogLevel, message: unknown[]): void {\n if (level < this.#minLevel) {\n return;\n }\n\n this.#writer.log(level, ...message);\n }","parent":"{'type': 'class_declaration', 'name': 'Logger'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f2e7ad32-fb87-4b01-b68f-edab9c350e55","name":"constants.ts","imports":"[{'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/constants.ts","code":"import { LogLevel } from '.\/types';\n\nexport const LOG_LEVEL_NAMES: Readonly> = {\n [LogLevel.Trace]: 'trace',\n [LogLevel.Debug]: 'debug',\n [LogLevel.Info]: 'info',\n [LogLevel.Warn]: 'warn',\n [LogLevel.Error]: 'error',\n};\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"18c208df-ae1f-410e-aff9-15ddf4d978a7","name":"factory.test.ts","imports":"[{'import_name': ['createConsoleLogger'], 'import_path': '.\/factory'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.test.ts","code":"import { createConsoleLogger } from '.\/factory';\nimport { Logger } from '.\/Logger';\nimport { LogLevel } from '.\/types';\n\nconst TEST_MESSAGE = ['Hello', new Error('BOOM!')];\n\ndescribe('factory', () => {\n describe('createConsoleLogger', () => {\n it('creates logger that writes to console', () => {\n const consoleSpy = jest.fn();\n jest.spyOn(console, 'warn').mockImplementation((...args) => consoleSpy('warn', args));\n jest.spyOn(console, 'debug').mockImplementation((...args) => consoleSpy('debug', args));\n jest.spyOn(console, 'error').mockImplementation((...args) => consoleSpy('error', args));\n\n const logger = createConsoleLogger({ minLevel: LogLevel.Error });\n\n expect(logger).toBeInstanceOf(Logger);\n expect(consoleSpy).not.toHaveBeenCalled();\n\n logger.warn(...TEST_MESSAGE);\n logger.debug(...TEST_MESSAGE);\n logger.error(...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith('error', TEST_MESSAGE);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f9bb68a1-e51f-405f-b150-20ae192f058e","name":"factory","imports":"[{'import_name': ['createConsoleLogger'], 'import_path': '.\/factory'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.test.ts","code":"describe('factory', () => {\n describe('createConsoleLogger', () => {\n it('creates logger that writes to console', () => {\n const consoleSpy = jest.fn();\n jest.spyOn(console, 'warn').mockImplementation((...args) => consoleSpy('warn', args));\n jest.spyOn(console, 'debug').mockImplementation((...args) => consoleSpy('debug', args));\n jest.spyOn(console, 'error').mockImplementation((...args) => consoleSpy('error', args));\n\n const logger = createConsoleLogger({ minLevel: LogLevel.Error });\n\n expect(logger).toBeInstanceOf(Logger);\n expect(consoleSpy).not.toHaveBeenCalled();\n\n logger.warn(...TEST_MESSAGE);\n logger.debug(...TEST_MESSAGE);\n logger.error(...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith('error', TEST_MESSAGE);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"9ba18681-d030-4d46-b924-69c6c67fb8fa","name":"createConsoleLogger","imports":"[{'import_name': ['createConsoleLogger'], 'import_path': '.\/factory'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.test.ts","code":"describe('createConsoleLogger', () => {\n it('creates logger that writes to console', () => {\n const consoleSpy = jest.fn();\n jest.spyOn(console, 'warn').mockImplementation((...args) => consoleSpy('warn', args));\n jest.spyOn(console, 'debug').mockImplementation((...args) => consoleSpy('debug', args));\n jest.spyOn(console, 'error').mockImplementation((...args) => consoleSpy('error', args));\n\n const logger = createConsoleLogger({ minLevel: LogLevel.Error });\n\n expect(logger).toBeInstanceOf(Logger);\n expect(consoleSpy).not.toHaveBeenCalled();\n\n logger.warn(...TEST_MESSAGE);\n logger.debug(...TEST_MESSAGE);\n logger.error(...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith('error', TEST_MESSAGE);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"cc15aacc-e6f2-4ecc-8fd6-cec206524f73","name":"creates logger that writes to console","imports":"[{'import_name': ['createConsoleLogger'], 'import_path': '.\/factory'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['LogLevel'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.test.ts","code":"it('creates logger that writes to console', () => {\n const consoleSpy = jest.fn();\n jest.spyOn(console, 'warn').mockImplementation((...args) => consoleSpy('warn', args));\n jest.spyOn(console, 'debug').mockImplementation((...args) => consoleSpy('debug', args));\n jest.spyOn(console, 'error').mockImplementation((...args) => consoleSpy('error', args));\n\n const logger = createConsoleLogger({ minLevel: LogLevel.Error });\n\n expect(logger).toBeInstanceOf(Logger);\n expect(consoleSpy).not.toHaveBeenCalled();\n\n logger.warn(...TEST_MESSAGE);\n logger.debug(...TEST_MESSAGE);\n logger.error(...TEST_MESSAGE);\n\n expect(consoleSpy).toHaveBeenCalledTimes(1);\n expect(consoleSpy).toHaveBeenCalledWith('error', TEST_MESSAGE);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"bd1b2a3b-9591-4981-91a1-eba51e09e2a0","name":"factory.ts","imports":"[{'import_name': ['LoggerOptions'], 'import_path': '.\/Logger'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['ConsoleLogWriter'], 'import_path': '.\/ConsoleLogWriter'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.ts","code":"import type { LoggerOptions } from '.\/Logger';\nimport { Logger } from '.\/Logger';\nimport { ConsoleLogWriter } from '.\/ConsoleLogWriter';\n\ntype ConsoleLoggerOptions = Omit;\n\nexport const createConsoleLogger = (options: ConsoleLoggerOptions = {}) =>\n new Logger({\n ...options,\n writer: new ConsoleLogWriter(),\n });\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e18b5896-cbb9-4393-83f0-9e03ec139fda","name":"createConsoleLogger","imports":"[{'import_name': ['LoggerOptions'], 'import_path': '.\/Logger'}, {'import_name': ['Logger'], 'import_path': '.\/Logger'}, {'import_name': ['ConsoleLogWriter'], 'import_path': '.\/ConsoleLogWriter'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/factory.ts","code":"(options: ConsoleLoggerOptions = {}) =>\n new Logger({\n ...options,\n writer: new ConsoleLogWriter(),\n })","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"96fcf256-4ef5-4d76-bb78-929ea92bd9fe","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/index.ts","code":"export * from '.\/constants';\nexport * from '.\/factory';\nexport * from '.\/Logger';\nexport * from '.\/types';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"c6088c92-20cb-4ce7-b4ca-09b94b028b44","name":"types.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/logger\/src\/types.ts","code":"export enum LogLevel {\n Trace = 1,\n Debug = 2,\n Info = 3,\n Warn = 4,\n Error = 5,\n}\n\nexport interface LogWriter {\n log(level: LogLevel, ...message: unknown[]): void;\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d0e70b7d-f28c-434f-ac1f-4918dce44d49","name":"async.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/__mocks__\/nanoid\/async.ts","code":"export const customAlphabet = jest\n .fn()\n .mockImplementation(letters => (size: number) => Promise.resolve(`${size}-${letters}`));\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7acc55d5-403b-4f5f-8d8a-278f28ff1f00","name":"DefaultOAuthStateBroadcaster.test.ts","imports":"[{'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['DefaultOAuthStateBroadcaster', 'CHANNEL_NAME', 'TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"import { useFakeBroadcastChannel } from '@gitlab\/utils-test';\nimport {\n DefaultOAuthStateBroadcaster,\n CHANNEL_NAME,\n TOKEN_CHANGE_MESSAGE,\n} from '.\/DefaultOAuthStateBroadcaster';\n\ndescribe('DefaultOAuthStateBroadcaster', () => {\n let subject: DefaultOAuthStateBroadcaster;\n let bc: jest.MockedObject;\n\n useFakeBroadcastChannel();\n\n const triggerMessageListener = (data: string) => {\n const evt = new MessageEvent('message', { data });\n const handler = bc.addEventListener.mock.calls[0][1];\n\n if ('handleEvent' in handler) {\n handler.handleEvent(evt);\n } else {\n handler(evt);\n }\n };\n\n describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthStateBroadcaster();\n bc = jest.mocked(jest.mocked(BroadcastChannel).mock.instances[0]);\n });\n\n it('creates new BroadcastChannel', () => {\n expect(BroadcastChannel).toHaveBeenCalledTimes(1);\n expect(BroadcastChannel).toHaveBeenCalledWith(CHANNEL_NAME);\n });\n\n describe('notifyTokenChange', () => {\n it('posts message to channel', () => {\n expect(bc.postMessage).not.toHaveBeenCalled();\n\n subject.notifyTokenChange();\n\n expect(bc.postMessage).toHaveBeenCalledTimes(1);\n expect(bc.postMessage).toHaveBeenCalledWith(TOKEN_CHANGE_MESSAGE);\n });\n });\n\n describe('dispose', () => {\n it('calls close', () => {\n expect(bc.close).not.toHaveBeenCalled();\n\n subject.dispose();\n\n expect(bc.close).toHaveBeenCalled();\n });\n });\n\n describe('onTokenChange', () => {\n it('registers handler that is called only when expected message is received', () => {\n expect(bc.addEventListener).not.toHaveBeenCalled();\n\n const spy = jest.fn();\n subject.onTokenChange(spy);\n\n expect(bc.addEventListener).toHaveBeenCalledTimes(1);\n expect(bc.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));\n\n triggerMessageListener('bogus');\n expect(spy).not.toHaveBeenCalled();\n\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener('bogus');\n expect(spy).toHaveBeenCalledTimes(2);\n });\n\n it('returns returns function that will removeEventListener', () => {\n const spy = jest.fn();\n const stop = subject.onTokenChange(spy);\n const handler = bc.addEventListener.mock.calls[0][1];\n\n expect(bc.removeEventListener).not.toHaveBeenCalled();\n\n stop();\n\n expect(bc.removeEventListener).toHaveBeenCalledTimes(1);\n expect(bc.removeEventListener).toHaveBeenCalledWith('message', handler);\n });\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"46571081-936f-4690-a111-8437109d57ae","name":"DefaultOAuthStateBroadcaster","imports":"[{'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['DefaultOAuthStateBroadcaster', 'CHANNEL_NAME', 'TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"describe('DefaultOAuthStateBroadcaster', () => {\n let subject: DefaultOAuthStateBroadcaster;\n let bc: jest.MockedObject;\n\n useFakeBroadcastChannel();\n\n const triggerMessageListener = (data: string) => {\n const evt = new MessageEvent('message', { data });\n const handler = bc.addEventListener.mock.calls[0][1];\n\n if ('handleEvent' in handler) {\n handler.handleEvent(evt);\n } else {\n handler(evt);\n }\n };\n\n describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthStateBroadcaster();\n bc = jest.mocked(jest.mocked(BroadcastChannel).mock.instances[0]);\n });\n\n it('creates new BroadcastChannel', () => {\n expect(BroadcastChannel).toHaveBeenCalledTimes(1);\n expect(BroadcastChannel).toHaveBeenCalledWith(CHANNEL_NAME);\n });\n\n describe('notifyTokenChange', () => {\n it('posts message to channel', () => {\n expect(bc.postMessage).not.toHaveBeenCalled();\n\n subject.notifyTokenChange();\n\n expect(bc.postMessage).toHaveBeenCalledTimes(1);\n expect(bc.postMessage).toHaveBeenCalledWith(TOKEN_CHANGE_MESSAGE);\n });\n });\n\n describe('dispose', () => {\n it('calls close', () => {\n expect(bc.close).not.toHaveBeenCalled();\n\n subject.dispose();\n\n expect(bc.close).toHaveBeenCalled();\n });\n });\n\n describe('onTokenChange', () => {\n it('registers handler that is called only when expected message is received', () => {\n expect(bc.addEventListener).not.toHaveBeenCalled();\n\n const spy = jest.fn();\n subject.onTokenChange(spy);\n\n expect(bc.addEventListener).toHaveBeenCalledTimes(1);\n expect(bc.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));\n\n triggerMessageListener('bogus');\n expect(spy).not.toHaveBeenCalled();\n\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener('bogus');\n expect(spy).toHaveBeenCalledTimes(2);\n });\n\n it('returns returns function that will removeEventListener', () => {\n const spy = jest.fn();\n const stop = subject.onTokenChange(spy);\n const handler = bc.addEventListener.mock.calls[0][1];\n\n expect(bc.removeEventListener).not.toHaveBeenCalled();\n\n stop();\n\n expect(bc.removeEventListener).toHaveBeenCalledTimes(1);\n expect(bc.removeEventListener).toHaveBeenCalledWith('message', handler);\n });\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"09beaf32-8c4b-4da4-bed9-cb2a99edb6cf","name":"default","imports":"[{'import_name': ['DefaultOAuthStateBroadcaster', 'CHANNEL_NAME', 'TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthStateBroadcaster();\n bc = jest.mocked(jest.mocked(BroadcastChannel).mock.instances[0]);\n });\n\n it('creates new BroadcastChannel', () => {\n expect(BroadcastChannel).toHaveBeenCalledTimes(1);\n expect(BroadcastChannel).toHaveBeenCalledWith(CHANNEL_NAME);\n });\n\n describe('notifyTokenChange', () => {\n it('posts message to channel', () => {\n expect(bc.postMessage).not.toHaveBeenCalled();\n\n subject.notifyTokenChange();\n\n expect(bc.postMessage).toHaveBeenCalledTimes(1);\n expect(bc.postMessage).toHaveBeenCalledWith(TOKEN_CHANGE_MESSAGE);\n });\n });\n\n describe('dispose', () => {\n it('calls close', () => {\n expect(bc.close).not.toHaveBeenCalled();\n\n subject.dispose();\n\n expect(bc.close).toHaveBeenCalled();\n });\n });\n\n describe('onTokenChange', () => {\n it('registers handler that is called only when expected message is received', () => {\n expect(bc.addEventListener).not.toHaveBeenCalled();\n\n const spy = jest.fn();\n subject.onTokenChange(spy);\n\n expect(bc.addEventListener).toHaveBeenCalledTimes(1);\n expect(bc.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));\n\n triggerMessageListener('bogus');\n expect(spy).not.toHaveBeenCalled();\n\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener('bogus');\n expect(spy).toHaveBeenCalledTimes(2);\n });\n\n it('returns returns function that will removeEventListener', () => {\n const spy = jest.fn();\n const stop = subject.onTokenChange(spy);\n const handler = bc.addEventListener.mock.calls[0][1];\n\n expect(bc.removeEventListener).not.toHaveBeenCalled();\n\n stop();\n\n expect(bc.removeEventListener).toHaveBeenCalledTimes(1);\n expect(bc.removeEventListener).toHaveBeenCalledWith('message', handler);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"07c95e0d-8590-444a-910a-a72353ff9e48","name":"notifyTokenChange","imports":"[{'import_name': ['TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"describe('notifyTokenChange', () => {\n it('posts message to channel', () => {\n expect(bc.postMessage).not.toHaveBeenCalled();\n\n subject.notifyTokenChange();\n\n expect(bc.postMessage).toHaveBeenCalledTimes(1);\n expect(bc.postMessage).toHaveBeenCalledWith(TOKEN_CHANGE_MESSAGE);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"23a8e684-1138-422c-8d32-fe0cdcb52696","name":"dispose","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"describe('dispose', () => {\n it('calls close', () => {\n expect(bc.close).not.toHaveBeenCalled();\n\n subject.dispose();\n\n expect(bc.close).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"7b5fe975-4f55-4cf2-ad03-1b6be2e13cf8","name":"onTokenChange","imports":"[{'import_name': ['TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"describe('onTokenChange', () => {\n it('registers handler that is called only when expected message is received', () => {\n expect(bc.addEventListener).not.toHaveBeenCalled();\n\n const spy = jest.fn();\n subject.onTokenChange(spy);\n\n expect(bc.addEventListener).toHaveBeenCalledTimes(1);\n expect(bc.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));\n\n triggerMessageListener('bogus');\n expect(spy).not.toHaveBeenCalled();\n\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener('bogus');\n expect(spy).toHaveBeenCalledTimes(2);\n });\n\n it('returns returns function that will removeEventListener', () => {\n const spy = jest.fn();\n const stop = subject.onTokenChange(spy);\n const handler = bc.addEventListener.mock.calls[0][1];\n\n expect(bc.removeEventListener).not.toHaveBeenCalled();\n\n stop();\n\n expect(bc.removeEventListener).toHaveBeenCalledTimes(1);\n expect(bc.removeEventListener).toHaveBeenCalledWith('message', handler);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"55db1668-0441-4f07-91eb-bf773a9f8484","name":"creates new BroadcastChannel","imports":"[{'import_name': ['CHANNEL_NAME'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"it('creates new BroadcastChannel', () => {\n expect(BroadcastChannel).toHaveBeenCalledTimes(1);\n expect(BroadcastChannel).toHaveBeenCalledWith(CHANNEL_NAME);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"7b583632-a428-4d59-92ff-3ce7064aeb1e","name":"posts message to channel","imports":"[{'import_name': ['TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"it('posts message to channel', () => {\n expect(bc.postMessage).not.toHaveBeenCalled();\n\n subject.notifyTokenChange();\n\n expect(bc.postMessage).toHaveBeenCalledTimes(1);\n expect(bc.postMessage).toHaveBeenCalledWith(TOKEN_CHANGE_MESSAGE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"9030f345-dd89-4656-96c4-7baa978e8dd2","name":"calls close","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"it('calls close', () => {\n expect(bc.close).not.toHaveBeenCalled();\n\n subject.dispose();\n\n expect(bc.close).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"9429a03e-a91d-4e19-b5fd-d595a383cb94","name":"registers handler that is called only when expected message is received","imports":"[{'import_name': ['TOKEN_CHANGE_MESSAGE'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"it('registers handler that is called only when expected message is received', () => {\n expect(bc.addEventListener).not.toHaveBeenCalled();\n\n const spy = jest.fn();\n subject.onTokenChange(spy);\n\n expect(bc.addEventListener).toHaveBeenCalledTimes(1);\n expect(bc.addEventListener).toHaveBeenCalledWith('message', expect.any(Function));\n\n triggerMessageListener('bogus');\n expect(spy).not.toHaveBeenCalled();\n\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener(TOKEN_CHANGE_MESSAGE);\n triggerMessageListener('bogus');\n expect(spy).toHaveBeenCalledTimes(2);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"43564e20-421c-4a7c-8bfa-fb87b038ab52","name":"returns returns function that will removeEventListener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.test.ts","code":"it('returns returns function that will removeEventListener', () => {\n const spy = jest.fn();\n const stop = subject.onTokenChange(spy);\n const handler = bc.addEventListener.mock.calls[0][1];\n\n expect(bc.removeEventListener).not.toHaveBeenCalled();\n\n stop();\n\n expect(bc.removeEventListener).toHaveBeenCalledTimes(1);\n expect(bc.removeEventListener).toHaveBeenCalledWith('message', handler);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"094caf3d-b019-49ef-8b62-69a5cb39f113","name":"DefaultOAuthStateBroadcaster.ts","imports":"[{'import_name': ['OAuthStateBroadcaster'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.ts","code":"import type { OAuthStateBroadcaster } from '.\/types';\n\nexport const CHANNEL_NAME = 'gitlab_web_ide_oauth';\nexport const TOKEN_CHANGE_MESSAGE = 'token change';\n\nexport class DefaultOAuthStateBroadcaster implements OAuthStateBroadcaster {\n readonly #bc: BroadcastChannel;\n\n constructor() {\n this.#bc = new BroadcastChannel(CHANNEL_NAME);\n }\n\n notifyTokenChange(): void {\n this.#bc.postMessage(TOKEN_CHANGE_MESSAGE);\n }\n\n onTokenChange(callback: () => void) {\n const handler = (event: MessageEvent) => {\n if (event.data === TOKEN_CHANGE_MESSAGE) {\n callback();\n }\n };\n\n this.#bc.addEventListener('message', handler);\n\n return () => this.#bc.removeEventListener('message', handler);\n }\n\n dispose(): void {\n this.#bc.close();\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bbe91a65-79be-479f-8995-a9058059c7da","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.ts","code":"constructor() {\n this.#bc = new BroadcastChannel(CHANNEL_NAME);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthStateBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d968dbeb-b00e-4a18-aaf6-3d89b84c4d64","name":"notifyTokenChange","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.ts","code":"notifyTokenChange(): void {\n this.#bc.postMessage(TOKEN_CHANGE_MESSAGE);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthStateBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"5ffc7041-2e2f-47cb-8c62-3a770d0a00ee","name":"onTokenChange","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.ts","code":"onTokenChange(callback: () => void) {\n const handler = (event: MessageEvent) => {\n if (event.data === TOKEN_CHANGE_MESSAGE) {\n callback();\n }\n };\n\n this.#bc.addEventListener('message', handler);\n\n return () => this.#bc.removeEventListener('message', handler);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthStateBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ff0a4a5e-35c8-45fa-860d-ccf2ce1ef621","name":"dispose","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultOAuthStateBroadcaster.ts","code":"dispose(): void {\n this.#bc.close();\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthStateBroadcaster'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"575056a7-a3f7-4ac5-9237-616ea4830211","name":"DefaultStorageValueCache.test.ts","imports":"[{'import_name': ['DefaultStorageValueCache'], 'import_path': '.\/DefaultStorageValueCache'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['InMemoryOAuthStorage'], 'import_path': '..\/test-utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"import { DefaultStorageValueCache } from '.\/DefaultStorageValueCache';\nimport type { OAuthTokenState } from '.\/types';\nimport { InMemoryOAuthStorage } from '..\/test-utils';\n\nconst TEST_KEY = 'test-key-thing';\nconst TEST_VALUE: OAuthTokenState = {\n accessToken: 'access-token-123',\n expiresAt: 7,\n owner: 'root',\n refreshToken: 'refresh-token-123',\n};\n\ndescribe('DefaultStorageValueCache', () => {\n let storage: InMemoryOAuthStorage;\n let subject: DefaultStorageValueCache;\n\n beforeEach(() => {\n storage = new InMemoryOAuthStorage();\n subject = new DefaultStorageValueCache(storage, TEST_KEY);\n\n jest.spyOn(storage, 'get');\n });\n\n describe('getValue', () => {\n it('returns null if no value is set', async () => {\n expect(storage.get).not.toHaveBeenCalled();\n\n expect(await subject.getValue()).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when a value exists in storage, returns the value and caches it', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when called with force=true, always refetches the value', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n\n await storage.remove(TEST_KEY);\n expect(await subject.getValue(true)).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(3);\n });\n });\n\n describe('setValue', () => {\n it('saves value in storage', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await storage.get(TEST_KEY)).toBe(TEST_VALUE);\n });\n\n it('caches value in memory', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(storage.get).not.toHaveBeenCalled();\n });\n });\n\n describe('locking', () => {\n it('locks future operations until setter resolves', async () => {\n const results = Promise.all([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(await results).toEqual([undefined, TEST_VALUE, TEST_VALUE, undefined, null]);\n });\n\n it('unlocks even if storage fails', async () => {\n const setError = new Error('BLOW UP in set!');\n const getError = new Error('BLOW UP in get!');\n\n jest.spyOn(storage, 'set').mockRejectedValue(setError);\n jest.spyOn(storage, 'get').mockRejectedValue(getError);\n\n const results = await Promise.allSettled([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(results).toEqual([\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n ]);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"af072b53-5a12-48bb-8a8f-a604aeca400a","name":"DefaultStorageValueCache","imports":"[{'import_name': ['DefaultStorageValueCache'], 'import_path': '.\/DefaultStorageValueCache'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['InMemoryOAuthStorage'], 'import_path': '..\/test-utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"describe('DefaultStorageValueCache', () => {\n let storage: InMemoryOAuthStorage;\n let subject: DefaultStorageValueCache;\n\n beforeEach(() => {\n storage = new InMemoryOAuthStorage();\n subject = new DefaultStorageValueCache(storage, TEST_KEY);\n\n jest.spyOn(storage, 'get');\n });\n\n describe('getValue', () => {\n it('returns null if no value is set', async () => {\n expect(storage.get).not.toHaveBeenCalled();\n\n expect(await subject.getValue()).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when a value exists in storage, returns the value and caches it', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when called with force=true, always refetches the value', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n\n await storage.remove(TEST_KEY);\n expect(await subject.getValue(true)).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(3);\n });\n });\n\n describe('setValue', () => {\n it('saves value in storage', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await storage.get(TEST_KEY)).toBe(TEST_VALUE);\n });\n\n it('caches value in memory', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(storage.get).not.toHaveBeenCalled();\n });\n });\n\n describe('locking', () => {\n it('locks future operations until setter resolves', async () => {\n const results = Promise.all([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(await results).toEqual([undefined, TEST_VALUE, TEST_VALUE, undefined, null]);\n });\n\n it('unlocks even if storage fails', async () => {\n const setError = new Error('BLOW UP in set!');\n const getError = new Error('BLOW UP in get!');\n\n jest.spyOn(storage, 'set').mockRejectedValue(setError);\n jest.spyOn(storage, 'get').mockRejectedValue(getError);\n\n const results = await Promise.allSettled([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(results).toEqual([\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n ]);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"00bed34c-ab55-4472-a897-a45b4d658e5c","name":"getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"describe('getValue', () => {\n it('returns null if no value is set', async () => {\n expect(storage.get).not.toHaveBeenCalled();\n\n expect(await subject.getValue()).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when a value exists in storage, returns the value and caches it', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n });\n\n it('when called with force=true, always refetches the value', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n\n await storage.remove(TEST_KEY);\n expect(await subject.getValue(true)).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(3);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ddb54f21-7815-4461-ac9c-d8d3bb02ec12","name":"setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"describe('setValue', () => {\n it('saves value in storage', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await storage.get(TEST_KEY)).toBe(TEST_VALUE);\n });\n\n it('caches value in memory', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(storage.get).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"92b1a751-014c-40e9-ad96-4ffca2f72ed9","name":"locking","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"describe('locking', () => {\n it('locks future operations until setter resolves', async () => {\n const results = Promise.all([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(await results).toEqual([undefined, TEST_VALUE, TEST_VALUE, undefined, null]);\n });\n\n it('unlocks even if storage fails', async () => {\n const setError = new Error('BLOW UP in set!');\n const getError = new Error('BLOW UP in get!');\n\n jest.spyOn(storage, 'set').mockRejectedValue(setError);\n jest.spyOn(storage, 'get').mockRejectedValue(getError);\n\n const results = await Promise.allSettled([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(results).toEqual([\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n ]);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"238029f5-a9d4-43c4-b707-68c39f5658a0","name":"returns null if no value is set","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('returns null if no value is set', async () => {\n expect(storage.get).not.toHaveBeenCalled();\n\n expect(await subject.getValue()).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"f92410f6-4519-405a-914d-7c88aea0cb2c","name":"when a value exists in storage, returns the value and caches it","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('when a value exists in storage, returns the value and caches it', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(await subject.getValue()).toBe(TEST_VALUE);\n\n expect(storage.get).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"dae503fc-2844-4146-bfb4-2d402d6d2125","name":"when called with force=true, always refetches the value","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('when called with force=true, always refetches the value', async () => {\n await storage.set(TEST_KEY, TEST_VALUE);\n\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n expect(await subject.getValue(true)).toBe(TEST_VALUE);\n\n await storage.remove(TEST_KEY);\n expect(await subject.getValue(true)).toBeUndefined();\n\n expect(storage.get).toHaveBeenCalledTimes(3);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"7b05e2ce-54d9-41bb-8758-2416d9929fb7","name":"saves value in storage","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('saves value in storage', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await storage.get(TEST_KEY)).toBe(TEST_VALUE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"03d6b262-e01c-4c33-aaf6-bf796749e139","name":"caches value in memory","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('caches value in memory', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(await subject.getValue()).toBe(TEST_VALUE);\n expect(storage.get).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"5c8dfe80-54d7-4c8c-9cbd-f79e88d759f8","name":"locks future operations until setter resolves","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('locks future operations until setter resolves', async () => {\n const results = Promise.all([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(await results).toEqual([undefined, TEST_VALUE, TEST_VALUE, undefined, null]);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"cca8c7fe-c61b-4767-a7aa-f7db8eab667d","name":"unlocks even if storage fails","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.test.ts","code":"it('unlocks even if storage fails', async () => {\n const setError = new Error('BLOW UP in set!');\n const getError = new Error('BLOW UP in get!');\n\n jest.spyOn(storage, 'set').mockRejectedValue(setError);\n jest.spyOn(storage, 'get').mockRejectedValue(getError);\n\n const results = await Promise.allSettled([\n subject.setValue(TEST_VALUE),\n subject.getValue(),\n subject.setValue(null),\n subject.getValue(),\n ]);\n\n expect(results).toEqual([\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n { status: 'rejected', reason: setError },\n { status: 'rejected', reason: getError },\n ]);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7a07ec2b-1f46-4953-b062-8add93ba53b2","name":"DefaultStorageValueCache.ts","imports":"[{'import_name': ['Mutex'], 'import_path': '.\/Mutex'}, {'import_name': ['OAuthStorage', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.ts","code":"import { Mutex } from '.\/Mutex';\nimport type { OAuthStorage, StorageValueCache } from '.\/types';\n\nexport class DefaultStorageValueCache implements StorageValueCache {\n readonly #storage: OAuthStorage;\n\n readonly #key: string;\n\n readonly #mutex: Mutex;\n\n #cachedValue: T | undefined;\n\n constructor(storage: OAuthStorage, key: string) {\n this.#storage = storage;\n this.#key = key;\n this.#mutex = new Mutex();\n this.#cachedValue = undefined;\n }\n\n async getValue(force = false): Promise {\n const unlock = await this.#mutex.lock();\n\n try {\n if (this.#cachedValue !== undefined && !force) {\n return this.#cachedValue;\n }\n\n return await this.#refreshCache();\n } finally {\n unlock();\n }\n }\n\n async setValue(value: T): Promise {\n const unlock = await this.#mutex.lock();\n\n try {\n await this.#storage.set(this.#key, value);\n\n this.#cachedValue = value;\n } finally {\n unlock();\n }\n }\n\n async #refreshCache(): Promise {\n const value = await this.#storage.get(this.#key);\n\n this.#cachedValue = value === null ? undefined : value;\n\n return this.#cachedValue;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b8a56163-042d-4244-8da6-bbafb9444374","name":"constructor","imports":"[{'import_name': ['Mutex'], 'import_path': '.\/Mutex'}, {'import_name': ['OAuthStorage'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.ts","code":"constructor(storage: OAuthStorage, key: string) {\n this.#storage = storage;\n this.#key = key;\n this.#mutex = new Mutex();\n this.#cachedValue = undefined;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultStorageValueCache'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f0c67058-8d4c-47f7-b3d7-e9cd66cf1fcb","name":"getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.ts","code":"async getValue(force = false): Promise {\n const unlock = await this.#mutex.lock();\n\n try {\n if (this.#cachedValue !== undefined && !force) {\n return this.#cachedValue;\n }\n\n return await this.#refreshCache();\n } finally {\n unlock();\n }\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultStorageValueCache'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"995ac69d-3044-4be6-8457-a5574235a1cd","name":"setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.ts","code":"async setValue(value: T): Promise {\n const unlock = await this.#mutex.lock();\n\n try {\n await this.#storage.set(this.#key, value);\n\n this.#cachedValue = value;\n } finally {\n unlock();\n }\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultStorageValueCache'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"702fbfdb-82a4-4379-912b-1bbdd4aaf049","name":"#refreshCache","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/DefaultStorageValueCache.ts","code":"async #refreshCache(): Promise {\n const value = await this.#storage.get(this.#key);\n\n this.#cachedValue = value === null ? undefined : value;\n\n return this.#cachedValue;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultStorageValueCache'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d505d80d-d620-4fd0-b1f7-3ae0b7a0aab6","name":"Mutex.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/Mutex.ts","code":"\/**\n * Lovingly inspired by https:\/\/github.com\/mgtitimoli\/await-mutex\/blob\/d070ae051d4b9b221b2ad1186754a2b8696d813c\/src\/mutex.js\n *\/\nexport class Mutex {\n #locking: Promise;\n\n constructor() {\n this.#locking = Promise.resolve();\n }\n\n lock() {\n let unlockNext: () => void;\n\n const nextLock = new Promise(resolve => {\n unlockNext = () => resolve(undefined);\n });\n\n \/\/ We will return our unlock hook after the current `#locking` promise chain resolves\n const waitForPastLocks = this.#locking.then(() => unlockNext);\n\n \/\/ Add our `nextLock` to the current `#locking` promise chain\n this.#locking = this.#locking.then(() => nextLock);\n\n return waitForPastLocks;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"c10995da-0578-4426-9774-d6482e5843e9","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/Mutex.ts","code":"constructor() {\n this.#locking = Promise.resolve();\n }","parent":"{'type': 'class_declaration', 'name': 'Mutex'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9fb70bc8-d02a-4d71-92ac-5c519f90a657","name":"lock","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/Mutex.ts","code":"lock() {\n let unlockNext: () => void;\n\n const nextLock = new Promise(resolve => {\n unlockNext = () => resolve(undefined);\n });\n\n \/\/ We will return our unlock hook after the current `#locking` promise chain resolves\n const waitForPastLocks = this.#locking.then(() => unlockNext);\n\n \/\/ Add our `nextLock` to the current `#locking` promise chain\n this.#locking = this.#locking.then(() => nextLock);\n\n return waitForPastLocks;\n }","parent":"{'type': 'class_declaration', 'name': 'Mutex'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"1d5402c1-73ef-4237-b372-cd82b0932a80","name":"OAuthClient.test.ts","imports":"[{'import_name': ['useFakeLocation'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['InMemoryOAuthStorage'], 'import_path': '..\/test-utils\/InMemoryOAuthStorage'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthApp', 'OAuthStorage', 'OAuthTokenState', 'OAuthHandshakeState', 'OAuthStateBroadcaster'], 'import_path': '.\/types'}, {'import_name': ['authorizeGrantWithIframe', 'BUFFER_MIN', 'generateAuthorizeUrl', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}, {'import_name': ['createBroadcasterStub'], 'import_path': '..\/test-utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"import { useFakeLocation } from '@gitlab\/utils-test';\nimport { InMemoryOAuthStorage } from '..\/test-utils\/InMemoryOAuthStorage';\nimport { DefaultOAuthClient } from '.\/OAuthClient';\nimport type {\n OAuthApp,\n OAuthStorage,\n OAuthTokenState,\n OAuthHandshakeState,\n OAuthStateBroadcaster,\n} from '.\/types';\nimport {\n authorizeGrantWithIframe,\n BUFFER_MIN,\n generateAuthorizeUrl,\n isCallbackFromIframe,\n notifyParentFromIframe,\n} from '.\/utils';\nimport { createBroadcasterStub } from '..\/test-utils';\n\nimport 'whatwg-fetch';\nimport '@gitlab\/utils-test\/src\/jsdom.d';\n\njest.mock('.\/utils\/iframeAuth');\n\nconst TEST_TIME = new Date('2023-10-10T00:00:00Z');\nconst TEST_TOKEN_KEY = 'gitlab\/web-ide\/oauth\/client_id\/token';\nconst TEST_HANDSHAKE_KEY = 'gitlab\/web-ide\/oauth\/client_id\/handshake';\nconst TEST_OWNER = 'root';\nconst TEST_TOKEN_LIFETIME = 1000;\nconst TEST_APP: OAuthApp = {\n authorizeUrl: 'https:\/\/example.com\/oauth\/authorize',\n callbackUrl: 'https:\/\/example.com\/-\/ide\/callback',\n clientId: 'client_id',\n tokenUrl: 'token_url',\n};\nconst TEST_TOKEN_RESPONSE = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: 72000,\n created_at: TEST_TIME.getTime() \/ 1000,\n};\nconst TEST_TOKEN_NEW = {\n accessToken: TEST_TOKEN_RESPONSE.access_token,\n refreshToken: TEST_TOKEN_RESPONSE.refresh_token,\n expiresAt: TEST_TIME.getTime() + TEST_TOKEN_RESPONSE.expires_in * 1000,\n owner: undefined,\n};\nconst TEST_TOKEN: OAuthTokenState = {\n accessToken: 'test-access-token',\n refreshToken: 'test-refresh-token',\n expiresAt: TEST_TIME.getTime() + 10 * 60 * 1000,\n};\n\ndescribe('OAuthClient', () => {\n jest.useFakeTimers().setSystemTime(TEST_TIME);\n\n let broadcaster: OAuthStateBroadcaster;\n let fetchSpy: jest.SpiedFunction;\n let storage: OAuthStorage;\n let subject: DefaultOAuthClient;\n let testHandshakeState: OAuthHandshakeState;\n let testAuthroizeUrl: string;\n\n const toParamsString = (obj: Record) => {\n const params = new URLSearchParams(obj);\n\n return params.toString();\n };\n\n const setupForHandleCallback = () => {\n beforeEach(() => {\n \/\/ the URL should be a callback url\n const url = new URL(TEST_APP.callbackUrl);\n\n url.searchParams.set('code', 'test-code');\n url.searchParams.set('state', testHandshakeState.state);\n\n dom.reconfigure({ url: url.href });\n });\n\n \/\/ NB: fake location has to be set up after dom.reconfigure\n useFakeLocation();\n };\n\n beforeEach(async () => {\n dom.reconfigure({ url: 'http:\/\/localhost' });\n\n fetchSpy = jest.spyOn(window, 'fetch');\n fetchSpy.mockResolvedValue(new Response(JSON.stringify(TEST_TOKEN_RESPONSE)));\n\n storage = new InMemoryOAuthStorage();\n\n ({ url: testAuthroizeUrl, handshakeState: testHandshakeState } = await generateAuthorizeUrl(\n TEST_APP,\n ));\n\n broadcaster = createBroadcasterStub();\n });\n\n describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n });\n });\n\n describe('getToken', () => {\n it('throws when no token is found', async () => {\n await expect(subject.getToken()).rejects.toThrowError(\/No token\/);\n });\n\n describe('with token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, TEST_TOKEN);\n });\n\n it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n });\n\n it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n\n describe('with expired token and refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n });\n\n it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n\n it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n\n it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n });\n\n it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n\n it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n });\n });\n\n describe('with expired token and no refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n refreshToken: '',\n });\n\n jest.mocked(authorizeGrantWithIframe).mockResolvedValue({\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n });\n });\n\n it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n });\n });\n\n describe('with invalid token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n accessToken: '',\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n token | expectation\n ${null} | ${false}\n ${{}} | ${false}\n ${{ ...TEST_TOKEN, accessToken: '' }} | ${false}\n ${TEST_TOKEN} | ${true}\n `('with token=$token, should return $expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n const result = await subject.checkForValidToken();\n\n expect(result).toBe(expectation);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n it('at first, nothing is fetched or stored', async () => {\n \/\/ base case used to strengthen the upcoming assertions\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n expect(notifyParentFromIframe).not.toHaveBeenCalled();\n });\n\n describe('without handshake state set', () => {\n it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n });\n });\n\n describe('with handshake state set', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n\n await subject.handleCallback();\n });\n\n it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n });\n\n it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n });\n\n it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n });\n\n it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n });\n });\n\n describe('within iframe', () => {\n beforeEach(async () => {\n jest.mocked(isCallbackFromIframe).mockReturnValue(true);\n\n await subject.handleCallback();\n });\n\n it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n });\n });\n\n describe('when token lifetime is less than buffer time', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n const MOCK_RESPONSE_BODY = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: (BUFFER_MIN - 1) * 60,\n created_at: TEST_TIME.getTime() \/ 1000,\n };\n\n fetchSpy.mockResolvedValueOnce(\n new Response(JSON.stringify(MOCK_RESPONSE_BODY), {\n status: 200,\n statusText: 'OK',\n }),\n );\n });\n\n it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n });\n });\n });\n\n describe('redirectToAuthorize', () => {\n useFakeLocation();\n\n it('sets handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n\n await subject.redirectToAuthorize();\n\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toEqual(testHandshakeState);\n });\n\n it('redirects to authorize url', async () => {\n expect(window.location.href).toBe('http:\/\/localhost\/');\n\n await subject.redirectToAuthorize();\n\n expect(window.location.href).toBe(testAuthroizeUrl);\n });\n });\n\n describe('onTokenChange', () => {\n it('returns function to unsubscribe listener', () => {});\n });\n });\n\n describe('with owner', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n owner: TEST_OWNER,\n });\n });\n\n describe('getToken', () => {\n it('returns token if owner matches', async () => {\n const token = { ...TEST_TOKEN, owner: TEST_OWNER };\n await storage.set(TEST_TOKEN_KEY, token);\n\n const actual = await subject.getToken();\n\n expect(actual).toEqual(token);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n });\n\n it('saves current owner with new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n\n await subject.handleCallback();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n owner: TEST_OWNER,\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n desc | token | expectation\n ${'when token has no owner'} | ${TEST_TOKEN} | ${false}\n ${'when token has different owner'} | ${{ ...TEST_TOKEN, owner: 'test' }} | ${false}\n ${'when token has same owner'} | ${{ ...TEST_TOKEN, owner: TEST_OWNER }} | ${true}\n `('$desc, result=$expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n\n expect(await subject.checkForValidToken()).toBe(expectation);\n });\n });\n });\n\n describe('with tokenLifetime', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n tokenLifetime: TEST_TOKEN_LIFETIME,\n });\n });\n\n it('uses the given tokenLifetime when saving new token', async () => {\n \/\/ Save expired token in storage\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n\n await subject.getToken();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n expiresAt: (TEST_TOKEN_RESPONSE.created_at + TEST_TOKEN_LIFETIME) * 1000,\n });\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"1576cec5-28b0-4ea8-b9f9-5de08a72f3db","name":"OAuthClient","imports":"[{'import_name': ['useFakeLocation'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['InMemoryOAuthStorage'], 'import_path': '..\/test-utils\/InMemoryOAuthStorage'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthStorage', 'OAuthHandshakeState', 'OAuthStateBroadcaster'], 'import_path': '.\/types'}, {'import_name': ['authorizeGrantWithIframe', 'BUFFER_MIN', 'generateAuthorizeUrl', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}, {'import_name': ['createBroadcasterStub'], 'import_path': '..\/test-utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('OAuthClient', () => {\n jest.useFakeTimers().setSystemTime(TEST_TIME);\n\n let broadcaster: OAuthStateBroadcaster;\n let fetchSpy: jest.SpiedFunction;\n let storage: OAuthStorage;\n let subject: DefaultOAuthClient;\n let testHandshakeState: OAuthHandshakeState;\n let testAuthroizeUrl: string;\n\n const toParamsString = (obj: Record) => {\n const params = new URLSearchParams(obj);\n\n return params.toString();\n };\n\n const setupForHandleCallback = () => {\n beforeEach(() => {\n \/\/ the URL should be a callback url\n const url = new URL(TEST_APP.callbackUrl);\n\n url.searchParams.set('code', 'test-code');\n url.searchParams.set('state', testHandshakeState.state);\n\n dom.reconfigure({ url: url.href });\n });\n\n \/\/ NB: fake location has to be set up after dom.reconfigure\n useFakeLocation();\n };\n\n beforeEach(async () => {\n dom.reconfigure({ url: 'http:\/\/localhost' });\n\n fetchSpy = jest.spyOn(window, 'fetch');\n fetchSpy.mockResolvedValue(new Response(JSON.stringify(TEST_TOKEN_RESPONSE)));\n\n storage = new InMemoryOAuthStorage();\n\n ({ url: testAuthroizeUrl, handshakeState: testHandshakeState } = await generateAuthorizeUrl(\n TEST_APP,\n ));\n\n broadcaster = createBroadcasterStub();\n });\n\n describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n });\n });\n\n describe('getToken', () => {\n it('throws when no token is found', async () => {\n await expect(subject.getToken()).rejects.toThrowError(\/No token\/);\n });\n\n describe('with token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, TEST_TOKEN);\n });\n\n it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n });\n\n it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n\n describe('with expired token and refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n });\n\n it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n\n it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n\n it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n });\n\n it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n\n it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n });\n });\n\n describe('with expired token and no refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n refreshToken: '',\n });\n\n jest.mocked(authorizeGrantWithIframe).mockResolvedValue({\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n });\n });\n\n it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n });\n });\n\n describe('with invalid token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n accessToken: '',\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n token | expectation\n ${null} | ${false}\n ${{}} | ${false}\n ${{ ...TEST_TOKEN, accessToken: '' }} | ${false}\n ${TEST_TOKEN} | ${true}\n `('with token=$token, should return $expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n const result = await subject.checkForValidToken();\n\n expect(result).toBe(expectation);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n it('at first, nothing is fetched or stored', async () => {\n \/\/ base case used to strengthen the upcoming assertions\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n expect(notifyParentFromIframe).not.toHaveBeenCalled();\n });\n\n describe('without handshake state set', () => {\n it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n });\n });\n\n describe('with handshake state set', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n\n await subject.handleCallback();\n });\n\n it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n });\n\n it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n });\n\n it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n });\n\n it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n });\n });\n\n describe('within iframe', () => {\n beforeEach(async () => {\n jest.mocked(isCallbackFromIframe).mockReturnValue(true);\n\n await subject.handleCallback();\n });\n\n it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n });\n });\n\n describe('when token lifetime is less than buffer time', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n const MOCK_RESPONSE_BODY = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: (BUFFER_MIN - 1) * 60,\n created_at: TEST_TIME.getTime() \/ 1000,\n };\n\n fetchSpy.mockResolvedValueOnce(\n new Response(JSON.stringify(MOCK_RESPONSE_BODY), {\n status: 200,\n statusText: 'OK',\n }),\n );\n });\n\n it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n });\n });\n });\n\n describe('redirectToAuthorize', () => {\n useFakeLocation();\n\n it('sets handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n\n await subject.redirectToAuthorize();\n\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toEqual(testHandshakeState);\n });\n\n it('redirects to authorize url', async () => {\n expect(window.location.href).toBe('http:\/\/localhost\/');\n\n await subject.redirectToAuthorize();\n\n expect(window.location.href).toBe(testAuthroizeUrl);\n });\n });\n\n describe('onTokenChange', () => {\n it('returns function to unsubscribe listener', () => {});\n });\n });\n\n describe('with owner', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n owner: TEST_OWNER,\n });\n });\n\n describe('getToken', () => {\n it('returns token if owner matches', async () => {\n const token = { ...TEST_TOKEN, owner: TEST_OWNER };\n await storage.set(TEST_TOKEN_KEY, token);\n\n const actual = await subject.getToken();\n\n expect(actual).toEqual(token);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n });\n\n it('saves current owner with new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n\n await subject.handleCallback();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n owner: TEST_OWNER,\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n desc | token | expectation\n ${'when token has no owner'} | ${TEST_TOKEN} | ${false}\n ${'when token has different owner'} | ${{ ...TEST_TOKEN, owner: 'test' }} | ${false}\n ${'when token has same owner'} | ${{ ...TEST_TOKEN, owner: TEST_OWNER }} | ${true}\n `('$desc, result=$expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n\n expect(await subject.checkForValidToken()).toBe(expectation);\n });\n });\n });\n\n describe('with tokenLifetime', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n tokenLifetime: TEST_TOKEN_LIFETIME,\n });\n });\n\n it('uses the given tokenLifetime when saving new token', async () => {\n \/\/ Save expired token in storage\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n\n await subject.getToken();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n expiresAt: (TEST_TOKEN_RESPONSE.created_at + TEST_TOKEN_LIFETIME) * 1000,\n });\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"427b7eb5-ca7b-440a-a045-39013345b072","name":"default","imports":"[{'import_name': ['useFakeLocation'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['authorizeGrantWithIframe', 'BUFFER_MIN', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('default', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n });\n });\n\n describe('getToken', () => {\n it('throws when no token is found', async () => {\n await expect(subject.getToken()).rejects.toThrowError(\/No token\/);\n });\n\n describe('with token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, TEST_TOKEN);\n });\n\n it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n });\n\n it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n\n describe('with expired token and refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n });\n\n it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n\n it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n\n it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n });\n\n it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n\n it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n });\n });\n\n describe('with expired token and no refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n refreshToken: '',\n });\n\n jest.mocked(authorizeGrantWithIframe).mockResolvedValue({\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n });\n });\n\n it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n });\n });\n\n describe('with invalid token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n accessToken: '',\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n token | expectation\n ${null} | ${false}\n ${{}} | ${false}\n ${{ ...TEST_TOKEN, accessToken: '' }} | ${false}\n ${TEST_TOKEN} | ${true}\n `('with token=$token, should return $expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n const result = await subject.checkForValidToken();\n\n expect(result).toBe(expectation);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n it('at first, nothing is fetched or stored', async () => {\n \/\/ base case used to strengthen the upcoming assertions\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n expect(notifyParentFromIframe).not.toHaveBeenCalled();\n });\n\n describe('without handshake state set', () => {\n it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n });\n });\n\n describe('with handshake state set', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n\n await subject.handleCallback();\n });\n\n it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n });\n\n it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n });\n\n it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n });\n\n it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n });\n });\n\n describe('within iframe', () => {\n beforeEach(async () => {\n jest.mocked(isCallbackFromIframe).mockReturnValue(true);\n\n await subject.handleCallback();\n });\n\n it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n });\n });\n\n describe('when token lifetime is less than buffer time', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n const MOCK_RESPONSE_BODY = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: (BUFFER_MIN - 1) * 60,\n created_at: TEST_TIME.getTime() \/ 1000,\n };\n\n fetchSpy.mockResolvedValueOnce(\n new Response(JSON.stringify(MOCK_RESPONSE_BODY), {\n status: 200,\n statusText: 'OK',\n }),\n );\n });\n\n it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n });\n });\n });\n\n describe('redirectToAuthorize', () => {\n useFakeLocation();\n\n it('sets handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n\n await subject.redirectToAuthorize();\n\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toEqual(testHandshakeState);\n });\n\n it('redirects to authorize url', async () => {\n expect(window.location.href).toBe('http:\/\/localhost\/');\n\n await subject.redirectToAuthorize();\n\n expect(window.location.href).toBe(testAuthroizeUrl);\n });\n });\n\n describe('onTokenChange', () => {\n it('returns function to unsubscribe listener', () => {});\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"4a146d94-85d7-44e4-b64d-075b2a87a913","name":"getToken","imports":"[{'import_name': ['authorizeGrantWithIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('getToken', () => {\n it('throws when no token is found', async () => {\n await expect(subject.getToken()).rejects.toThrowError(\/No token\/);\n });\n\n describe('with token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, TEST_TOKEN);\n });\n\n it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n });\n\n it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n });\n\n describe('with expired token and refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n });\n\n it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n\n it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n\n it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n });\n\n it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n\n it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n });\n });\n\n describe('with expired token and no refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n refreshToken: '',\n });\n\n jest.mocked(authorizeGrantWithIframe).mockResolvedValue({\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n });\n });\n\n it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n });\n });\n\n describe('with invalid token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n accessToken: '',\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"1df2389d-cbe5-4b6f-b64b-5d2a5066e8c7","name":"with token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, TEST_TOKEN);\n });\n\n it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n });\n\n it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"1984f541-1653-40dd-8763-8e21629473f0","name":"with expired token and refresh token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with expired token and refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n });\n\n it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n\n it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n\n it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n });\n\n it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n });\n\n it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"c44f2dae-65ca-43fb-81aa-7a1ab7d8806d","name":"with expired token and no refresh token","imports":"[{'import_name': ['authorizeGrantWithIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with expired token and no refresh token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n refreshToken: '',\n });\n\n jest.mocked(authorizeGrantWithIframe).mockResolvedValue({\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n });\n });\n\n it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f3ed0c6a-4cef-4b72-a803-656efe8a9bae","name":"with invalid token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with invalid token', () => {\n beforeEach(async () => {\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n accessToken: '',\n });\n });\n\n it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"a90f51b4-3505-437a-a76b-df660784cf3f","name":"checkForValidToken","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('checkForValidToken', () => {\n it.each`\n token | expectation\n ${null} | ${false}\n ${{}} | ${false}\n ${{ ...TEST_TOKEN, accessToken: '' }} | ${false}\n ${TEST_TOKEN} | ${true}\n `('with token=$token, should return $expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n const result = await subject.checkForValidToken();\n\n expect(result).toBe(expectation);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f24645c9-7cb4-4428-b26e-e1a1d653144f","name":"handleCallback","imports":"[{'import_name': ['BUFFER_MIN', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('handleCallback', () => {\n setupForHandleCallback();\n\n it('at first, nothing is fetched or stored', async () => {\n \/\/ base case used to strengthen the upcoming assertions\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n expect(notifyParentFromIframe).not.toHaveBeenCalled();\n });\n\n describe('without handshake state set', () => {\n it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n });\n });\n\n describe('with handshake state set', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n\n await subject.handleCallback();\n });\n\n it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n });\n\n it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n });\n\n it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n });\n\n it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n });\n });\n\n describe('within iframe', () => {\n beforeEach(async () => {\n jest.mocked(isCallbackFromIframe).mockReturnValue(true);\n\n await subject.handleCallback();\n });\n\n it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n });\n });\n\n describe('when token lifetime is less than buffer time', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n const MOCK_RESPONSE_BODY = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: (BUFFER_MIN - 1) * 60,\n created_at: TEST_TIME.getTime() \/ 1000,\n };\n\n fetchSpy.mockResolvedValueOnce(\n new Response(JSON.stringify(MOCK_RESPONSE_BODY), {\n status: 200,\n statusText: 'OK',\n }),\n );\n });\n\n it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"132f3770-dd20-426d-9a48-c8e4e553a9ff","name":"without handshake state set","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('without handshake state set', () => {\n it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f99ba46e-2ea6-4388-a979-2d853054a889","name":"with handshake state set","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with handshake state set', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n\n await subject.handleCallback();\n });\n\n it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n });\n\n it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n });\n\n it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n });\n\n it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"36cd8354-7419-4ee8-869a-9ec45532fb44","name":"within iframe","imports":"[{'import_name': ['isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('within iframe', () => {\n beforeEach(async () => {\n jest.mocked(isCallbackFromIframe).mockReturnValue(true);\n\n await subject.handleCallback();\n });\n\n it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n });\n\n it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"201f22c0-825e-4b46-b1ac-e2fb2cbb1d9d","name":"when token lifetime is less than buffer time","imports":"[{'import_name': ['BUFFER_MIN'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('when token lifetime is less than buffer time', () => {\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n const MOCK_RESPONSE_BODY = {\n access_token: 'test-new-access-token',\n refresh_token: 'test-new-refresh-token',\n expires_in: (BUFFER_MIN - 1) * 60,\n created_at: TEST_TIME.getTime() \/ 1000,\n };\n\n fetchSpy.mockResolvedValueOnce(\n new Response(JSON.stringify(MOCK_RESPONSE_BODY), {\n status: 200,\n statusText: 'OK',\n }),\n );\n });\n\n it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"604f7fc2-4309-433f-8d7c-c573f41f54a2","name":"redirectToAuthorize","imports":"[{'import_name': ['useFakeLocation'], 'import_path': '@gitlab\/utils-test'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('redirectToAuthorize', () => {\n useFakeLocation();\n\n it('sets handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n\n await subject.redirectToAuthorize();\n\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toEqual(testHandshakeState);\n });\n\n it('redirects to authorize url', async () => {\n expect(window.location.href).toBe('http:\/\/localhost\/');\n\n await subject.redirectToAuthorize();\n\n expect(window.location.href).toBe(testAuthroizeUrl);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"2b87c80c-a4fe-4d53-8cb5-9f9c09dbd2c7","name":"onTokenChange","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('onTokenChange', () => {\n it('returns function to unsubscribe listener', () => {});\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"a04edd5f-2c2a-4931-b4b9-1cffccd22582","name":"with owner","imports":"[{'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with owner', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n owner: TEST_OWNER,\n });\n });\n\n describe('getToken', () => {\n it('returns token if owner matches', async () => {\n const token = { ...TEST_TOKEN, owner: TEST_OWNER };\n await storage.set(TEST_TOKEN_KEY, token);\n\n const actual = await subject.getToken();\n\n expect(actual).toEqual(token);\n });\n });\n\n describe('handleCallback', () => {\n setupForHandleCallback();\n\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n });\n\n it('saves current owner with new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n\n await subject.handleCallback();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n owner: TEST_OWNER,\n });\n });\n });\n\n describe('checkForValidToken', () => {\n it.each`\n desc | token | expectation\n ${'when token has no owner'} | ${TEST_TOKEN} | ${false}\n ${'when token has different owner'} | ${{ ...TEST_TOKEN, owner: 'test' }} | ${false}\n ${'when token has same owner'} | ${{ ...TEST_TOKEN, owner: TEST_OWNER }} | ${true}\n `('$desc, result=$expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n\n expect(await subject.checkForValidToken()).toBe(expectation);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"6b2f5929-07de-40e2-a55b-2288289336b9","name":"getToken","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('getToken', () => {\n it('returns token if owner matches', async () => {\n const token = { ...TEST_TOKEN, owner: TEST_OWNER };\n await storage.set(TEST_TOKEN_KEY, token);\n\n const actual = await subject.getToken();\n\n expect(actual).toEqual(token);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"e1ddf462-5f4c-4a38-92a3-839a609a996f","name":"handleCallback","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('handleCallback', () => {\n setupForHandleCallback();\n\n beforeEach(async () => {\n await storage.set(TEST_HANDSHAKE_KEY, testHandshakeState);\n });\n\n it('saves current owner with new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n\n await subject.handleCallback();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n owner: TEST_OWNER,\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"6d4c6b80-bd82-4686-81fe-b82e20c98e3b","name":"checkForValidToken","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('checkForValidToken', () => {\n it.each`\n desc | token | expectation\n ${'when token has no owner'} | ${TEST_TOKEN} | ${false}\n ${'when token has different owner'} | ${{ ...TEST_TOKEN, owner: 'test' }} | ${false}\n ${'when token has same owner'} | ${{ ...TEST_TOKEN, owner: TEST_OWNER }} | ${true}\n `('$desc, result=$expectation', async ({ token, expectation }) => {\n await storage.set(TEST_TOKEN_KEY, token);\n\n expect(await subject.checkForValidToken()).toBe(expectation);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"44066dc3-d553-4a94-a139-4089193af9fe","name":"with tokenLifetime","imports":"[{'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"describe('with tokenLifetime', () => {\n beforeEach(() => {\n subject = new DefaultOAuthClient({\n app: TEST_APP,\n storage,\n broadcaster,\n tokenLifetime: TEST_TOKEN_LIFETIME,\n });\n });\n\n it('uses the given tokenLifetime when saving new token', async () => {\n \/\/ Save expired token in storage\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n\n await subject.getToken();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n expiresAt: (TEST_TOKEN_RESPONSE.created_at + TEST_TOKEN_LIFETIME) * 1000,\n });\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"b4d4dddd-9675-409a-8d96-abed173fd022","name":"throws when no token is found","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('throws when no token is found', async () => {\n await expect(subject.getToken()).rejects.toThrowError(\/No token\/);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"45a0d6a3-fecf-4710-af2b-ae918196b920","name":"returns token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('returns token', async () => {\n const result = await subject.getToken();\n\n expect(result).toEqual(TEST_TOKEN);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"a0596157-d927-42bc-aac2-4fd2bc746cb8","name":"does not trigger callback","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('does not trigger callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"84e987ba-9111-41ad-ad15-9c934f8e104c","name":"refreshes token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('refreshes token', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'refresh_token',\n refresh_token: TEST_TOKEN.refreshToken || '',\n }),\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"8b934f9f-3233-4ab3-b688-5f6ebb1f7580","name":"returns and stores token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"2d1c79fd-efd7-4045-8457-9bd788098839","name":"notifies broadcast","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('notifies broadcast', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"dce1b616-16c5-479b-9a76-d17ca40f8767","name":"triggers onTokenChange callback","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('triggers onTokenChange callback', async () => {\n const callback = jest.fn();\n subject.onTokenChange(callback);\n\n await subject.getToken();\n\n expect(callback).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"70e0ed59-f26a-4f88-a899-44e25a18ed71","name":"when onTokenChange callback disposed, does not trigger callback","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('when onTokenChange callback disposed, does not trigger callback', async () => {\n const callback = jest.fn();\n const dispose = subject.onTokenChange(callback);\n\n dispose();\n await subject.getToken();\n\n expect(callback).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"942343ca-416d-4235-8e02-2b3a125ba6fe","name":"throws if response is not ok","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('throws if response is not ok', async () => {\n fetchSpy.mockResolvedValue(\n new Response(JSON.stringify({ error: 'test-error' }), { status: 400 }),\n );\n\n await expect(subject.getToken()).rejects.toThrow(\n \/Something bad happened while getting OAuth token: {\"error\":\"test-error\"}\/,\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"657075b4-4dcd-4d77-b798-994a704294f4","name":"refreshes token with grant from iframe","imports":"[{'import_name': ['authorizeGrantWithIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('refreshes token with grant from iframe', async () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(authorizeGrantWithIframe).not.toHaveBeenCalled();\n\n await subject.getToken();\n\n expect(authorizeGrantWithIframe).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code-from-iframe',\n code_verifier: 'test-code-verifier',\n }),\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"e204b98f-5eea-48b2-9d9f-7b84f9206bac","name":"returns and stores token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('returns and stores token', async () => {\n const result = await subject.getToken();\n const storedResult = await storage.get(TEST_TOKEN_KEY);\n\n expect(result).toEqual(TEST_TOKEN_NEW);\n expect(storedResult).toEqual(TEST_TOKEN_NEW);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"15196698-1538-4de7-af1b-0e740c893161","name":"at first, nothing is fetched or stored","imports":"[{'import_name': ['notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('at first, nothing is fetched or stored', async () => {\n \/\/ base case used to strengthen the upcoming assertions\n expect(fetchSpy).not.toHaveBeenCalled();\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n expect(notifyParentFromIframe).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"96fb489c-b526-44c4-9ca6-f5069b57f91e","name":"throws error","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('throws error', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\/handshake state not found\/);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c308e6a2-0e47-47eb-99d4-86d2698bb574","name":"requests new token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('requests new token', async () => {\n expect(fetchSpy).toHaveBeenCalledTimes(1);\n expect(fetchSpy).toHaveBeenCalledWith(TEST_APP.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: toParamsString({\n client_id: TEST_APP.clientId,\n redirect_uri: TEST_APP.callbackUrl,\n grant_type: 'authorization_code',\n code: 'test-code',\n code_verifier: '32-0123456789abcdef',\n }),\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"a1da910e-f48b-43aa-848b-1c3207154508","name":"stores new token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('stores new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual(TEST_TOKEN_NEW);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"d8064702-5fd0-438d-8221-b7d59deb6f12","name":"deletes handshake state","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('deletes handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"639451ab-c9db-4ebd-b1ab-7a01019c5aa7","name":"redirects to original url","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('redirects to original url', async () => {\n expect(window.location.href).toBe(testHandshakeState.originalUrl);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"5d7a5375-739d-4779-882d-53c23fd44286","name":"does not fetch anything","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('does not fetch anything', () => {\n expect(fetchSpy).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"ceaf10b8-d246-4bfb-8a48-f6a3676e2af7","name":"notifies parent","imports":"[{'import_name': ['notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('notifies parent', () => {\n expect(notifyParentFromIframe).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"4cd94a8d-f278-4b12-ad92-ab09bcdc9b70","name":"throws error ","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('throws error ', async () => {\n await expect(subject.handleCallback()).rejects.toThrow(\n \/Access token lifetime cannot be less than 5 minutes\/,\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1f509389-3d79-4bbc-91f4-98b3ecd81875","name":"sets handshake state","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('sets handshake state', async () => {\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toBeNull();\n\n await subject.redirectToAuthorize();\n\n expect(await storage.get(TEST_HANDSHAKE_KEY)).toEqual(testHandshakeState);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"35241c24-e787-41ae-a8ed-0e216556d3b9","name":"redirects to authorize url","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('redirects to authorize url', async () => {\n expect(window.location.href).toBe('http:\/\/localhost\/');\n\n await subject.redirectToAuthorize();\n\n expect(window.location.href).toBe(testAuthroizeUrl);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"818df7ea-fab7-4851-a710-473dcbc79ce6","name":"returns function to unsubscribe listener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('returns function to unsubscribe listener', () => {})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"3f376430-391e-4a89-930b-fd38ad0beb13","name":"returns token if owner matches","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('returns token if owner matches', async () => {\n const token = { ...TEST_TOKEN, owner: TEST_OWNER };\n await storage.set(TEST_TOKEN_KEY, token);\n\n const actual = await subject.getToken();\n\n expect(actual).toEqual(token);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"86c3a015-d505-4e36-8d63-77c47dde59e4","name":"saves current owner with new token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('saves current owner with new token', async () => {\n expect(await storage.get(TEST_TOKEN_KEY)).toBeNull();\n\n await subject.handleCallback();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n owner: TEST_OWNER,\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"907c5063-d172-4829-b235-17a26ec44c4b","name":"uses the given tokenLifetime when saving new token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.test.ts","code":"it('uses the given tokenLifetime when saving new token', async () => {\n \/\/ Save expired token in storage\n await storage.set(TEST_TOKEN_KEY, {\n ...TEST_TOKEN,\n expiresAt: TEST_TIME.getTime(),\n });\n\n await subject.getToken();\n\n expect(await storage.get(TEST_TOKEN_KEY)).toEqual({\n ...TEST_TOKEN_NEW,\n expiresAt: (TEST_TOKEN_RESPONSE.created_at + TEST_TOKEN_LIFETIME) * 1000,\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"c6e7757f-a175-4800-be73-7993dc6e04d4","name":"OAuthClient.ts","imports":"[{'import_name': ['OAuthApp', 'OAuthStateBroadcaster', 'OAuthStorage', 'OAuthTokenState', 'OAuthHandshakeState', 'StorageValueCache', 'TokenProvider', 'OAuthTokenGrant'], 'import_path': '.\/types'}, {'import_name': ['authorizeGrantWithIframe', 'BUFFER_MIN', 'generateAuthorizeUrl', 'getGrantFromCallbackUrl', 'getGrantFromRefreshToken', 'isCallbackFromIframe', 'isExpiredToken', 'isValidToken', 'notifyParentFromIframe'], 'import_path': '.\/utils'}, {'import_name': ['StorageValueCacheBuilder'], 'import_path': '.\/StorageValueCacheBuilder'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"import type {\n OAuthApp,\n OAuthStateBroadcaster,\n OAuthStorage,\n OAuthTokenState,\n OAuthHandshakeState,\n StorageValueCache,\n TokenProvider,\n OAuthTokenGrant,\n} from '.\/types';\nimport {\n authorizeGrantWithIframe,\n BUFFER_MIN,\n generateAuthorizeUrl,\n getGrantFromCallbackUrl,\n getGrantFromRefreshToken,\n isCallbackFromIframe,\n isExpiredToken,\n isValidToken,\n notifyParentFromIframe,\n} from '.\/utils';\nimport { StorageValueCacheBuilder } from '.\/StorageValueCacheBuilder';\n\nexport const STORAGE_KEY_PREFIX = 'gitlab\/web-ide\/oauth';\nconst EVENT_TYPE = 'oauth_change';\n\ninterface OAuthClientOptions {\n \/\/ properties of the OAuth Application to use for authentication\n readonly app: OAuthApp;\n\n \/\/ implementation for storing the OAuth state\n readonly storage: OAuthStorage;\n\n \/\/ implementation for broadcasting changes to the OAuth state\n readonly broadcaster: OAuthStateBroadcaster;\n\n \/\/ the owner to associate with the token (used to validate if the current token should be used or not)\n readonly owner?: string;\n\n \/\/ used to overwrite the `expiresAt` received whenever the token is granted\n readonly tokenLifetime?: number;\n}\n\nexport interface OAuthClient extends TokenProvider {\n \/**\n * Returns boolean for whether there's a valid token stored for this OAuthClient.\n *\/\n checkForValidToken(): Promise;\n\n \/**\n * Redirects to the OAuthApp's authorize URL for OAuth handshake\n *\/\n redirectToAuthorize(): Promise;\n\n \/**\n * When the OAuthApp's authroize URL redirects back to the app, this method should be triggered.\n *\n * - If the OAuth handshake was done silently in an iframe, we'll notify the parent frame\n * - Else, let's fetch and store a token, then redirect back to the original URL\n *\/\n handleCallback(): Promise;\n\n \/**\n * @param callback listener that will be triggered when the token has changed\n *\/\n onTokenChange(callback: () => void): () => void;\n}\n\nexport class DefaultOAuthClient implements OAuthClient {\n readonly #app: OAuthApp;\n\n readonly #storage: OAuthStorage;\n\n readonly #eventTarget: EventTarget;\n\n readonly #tokenCache: StorageValueCache;\n\n readonly #owner: string;\n\n readonly #tokenLifetime?: number;\n\n constructor(options: OAuthClientOptions) {\n this.#app = options.app;\n this.#storage = options.storage;\n this.#eventTarget = new EventTarget();\n\n this.#tokenCache = new StorageValueCacheBuilder(\n this.#storage,\n this.#tokenStorageKey(),\n )\n .withEventEmitter(this.#eventTarget, EVENT_TYPE)\n .withBroadcasting(options.broadcaster)\n .build();\n\n this.#owner = options.owner || '';\n this.#tokenLifetime = options.tokenLifetime;\n }\n\n \/\/ region: publics ---------------------------------------------------\n\n async getToken(): Promise {\n const token = await this.#tokenCache.getValue();\n\n if (!token) {\n \/\/ TODO: Handle this error better\n throw new Error('No token found! We need to do OAuth handshake again...');\n }\n\n if (!isValidToken(token, this.#owner)) {\n return this.#refreshToken(token);\n }\n\n return token;\n }\n\n async checkForValidToken(): Promise {\n const state = await this.#tokenCache.getValue(true);\n\n if (!state) {\n return false;\n }\n\n return isValidToken(state, this.#owner);\n }\n\n async redirectToAuthorize() {\n const { url, handshakeState } = await generateAuthorizeUrl(this.#app);\n\n await this.#setHandshakeState(handshakeState);\n\n window.location.href = url;\n }\n\n async handleCallback() {\n if (isCallbackFromIframe()) {\n notifyParentFromIframe();\n return;\n }\n\n const url = new URL(window.location.href);\n\n const handshakeState = await this.#getHandshakeState();\n if (!handshakeState) {\n throw new Error('handshake state not found');\n }\n\n const grant = getGrantFromCallbackUrl(url, handshakeState);\n\n await this.#requestAndStoreToken(grant);\n await this.#deleteHandshakeState();\n\n window.location.href = handshakeState.originalUrl;\n }\n\n onTokenChange(callback: () => void): () => void {\n this.#eventTarget.addEventListener(EVENT_TYPE, callback);\n\n return () => {\n this.#eventTarget.removeEventListener(EVENT_TYPE, callback);\n };\n }\n\n \/\/ region: privates --------------------------------------------------\n\n async #refreshToken(token: OAuthTokenState) {\n const grant = await this.#getGrantFromToken(token);\n\n return this.#requestAndStoreToken(grant);\n }\n\n async #getGrantFromToken(token: OAuthTokenState): Promise {\n if (token.refreshToken) {\n return getGrantFromRefreshToken(token.refreshToken);\n }\n\n return authorizeGrantWithIframe(this.#app);\n }\n\n async #requestAndStoreToken(params: OAuthTokenGrant) {\n const response = await fetch(this.#app.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n client_id: this.#app.clientId,\n redirect_uri: this.#app.callbackUrl,\n ...params,\n }).toString(),\n });\n\n if (!response.ok) {\n \/\/ TODO: Handle this better\n const errorResponse = await response.json().catch(() => ({}));\n\n throw new Error(\n `Something bad happened while getting OAuth token: ${JSON.stringify(errorResponse)}`,\n );\n }\n\n const responseJson = await response.json();\n const expiresIn =\n this.#tokenLifetime === undefined ? responseJson.expires_in : this.#tokenLifetime;\n\n const value: OAuthTokenState = {\n accessToken: responseJson.access_token,\n \/\/ why: * 1000 to convert seconds to ms\n expiresAt: (responseJson.created_at + expiresIn) * 1000,\n refreshToken: responseJson.refresh_token,\n \/\/ why: If owner is falsey it's the same as undefined. Let's not save it in localStorage.\n owner: this.#owner || undefined,\n };\n\n if (isExpiredToken(value)) {\n throw new Error(`[OAuth] Access token lifetime cannot be less than ${BUFFER_MIN} minutes.`);\n }\n\n await this.#tokenCache.setValue(value);\n\n return value;\n }\n\n #getHandshakeState(): Promise {\n return this.#storage.get(this.#handshakeStorageKey());\n }\n\n #setHandshakeState(state: OAuthHandshakeState) {\n return this.#storage.set(this.#handshakeStorageKey(), state);\n }\n\n #deleteHandshakeState() {\n return this.#storage.remove(this.#handshakeStorageKey());\n }\n\n #tokenStorageKey(): string {\n return `${STORAGE_KEY_PREFIX}\/${this.#app.clientId}\/token`;\n }\n\n #handshakeStorageKey(): string {\n return `${STORAGE_KEY_PREFIX}\/${this.#app.clientId}\/handshake`;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"59ab0079-d430-4376-ab0a-92b25e7a7a5e","name":"constructor","imports":"[{'import_name': ['OAuthTokenState', 'StorageValueCache'], 'import_path': '.\/types'}, {'import_name': ['StorageValueCacheBuilder'], 'import_path': '.\/StorageValueCacheBuilder'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"constructor(options: OAuthClientOptions) {\n this.#app = options.app;\n this.#storage = options.storage;\n this.#eventTarget = new EventTarget();\n\n this.#tokenCache = new StorageValueCacheBuilder(\n this.#storage,\n this.#tokenStorageKey(),\n )\n .withEventEmitter(this.#eventTarget, EVENT_TYPE)\n .withBroadcasting(options.broadcaster)\n .build();\n\n this.#owner = options.owner || '';\n this.#tokenLifetime = options.tokenLifetime;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fcdcbef7-478f-4ceb-9211-c84433e337fb","name":"getToken","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['isValidToken'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async getToken(): Promise {\n const token = await this.#tokenCache.getValue();\n\n if (!token) {\n \/\/ TODO: Handle this error better\n throw new Error('No token found! We need to do OAuth handshake again...');\n }\n\n if (!isValidToken(token, this.#owner)) {\n return this.#refreshToken(token);\n }\n\n return token;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"89e73143-f54a-4c7e-8af0-7e9cce3257b4","name":"checkForValidToken","imports":"[{'import_name': ['isValidToken'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async checkForValidToken(): Promise {\n const state = await this.#tokenCache.getValue(true);\n\n if (!state) {\n return false;\n }\n\n return isValidToken(state, this.#owner);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ca0d8202-2533-475f-b62d-6fc6679e35f8","name":"redirectToAuthorize","imports":"[{'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async redirectToAuthorize() {\n const { url, handshakeState } = await generateAuthorizeUrl(this.#app);\n\n await this.#setHandshakeState(handshakeState);\n\n window.location.href = url;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"2a71edd1-2287-4bdd-a120-1dcfba4b7396","name":"handleCallback","imports":"[{'import_name': ['getGrantFromCallbackUrl', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async handleCallback() {\n if (isCallbackFromIframe()) {\n notifyParentFromIframe();\n return;\n }\n\n const url = new URL(window.location.href);\n\n const handshakeState = await this.#getHandshakeState();\n if (!handshakeState) {\n throw new Error('handshake state not found');\n }\n\n const grant = getGrantFromCallbackUrl(url, handshakeState);\n\n await this.#requestAndStoreToken(grant);\n await this.#deleteHandshakeState();\n\n window.location.href = handshakeState.originalUrl;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fcf359e7-c348-49ee-92a4-ebe4fa0cd6f4","name":"onTokenChange","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"onTokenChange(callback: () => void): () => void {\n this.#eventTarget.addEventListener(EVENT_TYPE, callback);\n\n return () => {\n this.#eventTarget.removeEventListener(EVENT_TYPE, callback);\n };\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"77896dd0-7426-4b08-90f0-07551574c9a3","name":"#refreshToken","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async #refreshToken(token: OAuthTokenState) {\n const grant = await this.#getGrantFromToken(token);\n\n return this.#requestAndStoreToken(grant);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f6059e2a-26bb-4195-b1ad-69a4fa7e3c81","name":"#getGrantFromToken","imports":"[{'import_name': ['OAuthTokenState', 'OAuthTokenGrant'], 'import_path': '.\/types'}, {'import_name': ['authorizeGrantWithIframe', 'getGrantFromRefreshToken'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async #getGrantFromToken(token: OAuthTokenState): Promise {\n if (token.refreshToken) {\n return getGrantFromRefreshToken(token.refreshToken);\n }\n\n return authorizeGrantWithIframe(this.#app);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fef718d3-d368-49ec-bf17-8bee5cc83aa5","name":"#requestAndStoreToken","imports":"[{'import_name': ['OAuthTokenState', 'OAuthTokenGrant'], 'import_path': '.\/types'}, {'import_name': ['BUFFER_MIN', 'isExpiredToken'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"async #requestAndStoreToken(params: OAuthTokenGrant) {\n const response = await fetch(this.#app.tokenUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application\/x-www-form-urlencoded',\n },\n body: new URLSearchParams({\n client_id: this.#app.clientId,\n redirect_uri: this.#app.callbackUrl,\n ...params,\n }).toString(),\n });\n\n if (!response.ok) {\n \/\/ TODO: Handle this better\n const errorResponse = await response.json().catch(() => ({}));\n\n throw new Error(\n `Something bad happened while getting OAuth token: ${JSON.stringify(errorResponse)}`,\n );\n }\n\n const responseJson = await response.json();\n const expiresIn =\n this.#tokenLifetime === undefined ? responseJson.expires_in : this.#tokenLifetime;\n\n const value: OAuthTokenState = {\n accessToken: responseJson.access_token,\n \/\/ why: * 1000 to convert seconds to ms\n expiresAt: (responseJson.created_at + expiresIn) * 1000,\n refreshToken: responseJson.refresh_token,\n \/\/ why: If owner is falsey it's the same as undefined. Let's not save it in localStorage.\n owner: this.#owner || undefined,\n };\n\n if (isExpiredToken(value)) {\n throw new Error(`[OAuth] Access token lifetime cannot be less than ${BUFFER_MIN} minutes.`);\n }\n\n await this.#tokenCache.setValue(value);\n\n return value;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"0fe9bddd-c408-48b2-ad2d-f6d87bb0e2c0","name":"#getHandshakeState","imports":"[{'import_name': ['OAuthHandshakeState'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"#getHandshakeState(): Promise {\n return this.#storage.get(this.#handshakeStorageKey());\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"10b8257d-cf5c-46bb-90ec-a4614873879a","name":"#setHandshakeState","imports":"[{'import_name': ['OAuthHandshakeState'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"#setHandshakeState(state: OAuthHandshakeState) {\n return this.#storage.set(this.#handshakeStorageKey(), state);\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ba852c93-72b9-45b5-83ef-f6f66ae45694","name":"#deleteHandshakeState","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"#deleteHandshakeState() {\n return this.#storage.remove(this.#handshakeStorageKey());\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"5bd6b292-39f4-40a3-be2b-b2f49f00701a","name":"#tokenStorageKey","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"#tokenStorageKey(): string {\n return `${STORAGE_KEY_PREFIX}\/${this.#app.clientId}\/token`;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"dc094d51-a1fb-4d59-a931-0b133183373c","name":"#handshakeStorageKey","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthClient.ts","code":"#handshakeStorageKey(): string {\n return `${STORAGE_KEY_PREFIX}\/${this.#app.clientId}\/handshake`;\n }","parent":"{'type': 'class_declaration', 'name': 'DefaultOAuthClient'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"a6e3a9d7-6083-476c-8c3a-63b17d7930d7","name":"OAuthLocalStorage.test.ts","imports":"[{'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}, {'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"import { OAuthLocalStorage } from '.\/OAuthLocalStorage';\nimport { encodeBase64 } from '.\/utils';\n\nconst TEST_KEY = 'test-key';\nconst TEST_VALUE = {\n foo: 'bar',\n lorem: 'ipsum',\n num: 123,\n};\n\ndescribe('OAuthLocalStorage', () => {\n let subject: OAuthLocalStorage;\n\n afterEach(() => {\n window.localStorage.clear();\n });\n\n describe('default', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage();\n });\n\n describe('get', () => {\n it('returns null if not json encoded base64 object', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns null if nothing found', async () => {\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns object in local storage', async () => {\n window.localStorage.setItem(TEST_KEY, encodeBase64(JSON.stringify(TEST_VALUE)));\n const result = await subject.get(TEST_KEY);\n\n expect(result).toEqual(TEST_VALUE);\n });\n });\n\n describe('set', () => {\n it('updates localStorage with value', async () => {\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify(TEST_VALUE)),\n );\n });\n });\n\n describe('remove', () => {\n it('removes key from localStorage', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n\n await subject.remove(TEST_KEY);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n });\n });\n });\n\n describe('with excludeKeys', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage({\n excludeKeys: ['lorem'],\n });\n });\n\n describe('set', () => {\n it('strips excludeKeys from object', async () => {\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify({ foo: 'bar', num: 123 })),\n );\n });\n\n it('can set non-object values', async () => {\n await subject.set(TEST_KEY, 7);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(encodeBase64('7'));\n });\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"bc9dc222-2c3f-4b0f-baec-723325773e2c","name":"OAuthLocalStorage","imports":"[{'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}, {'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('OAuthLocalStorage', () => {\n let subject: OAuthLocalStorage;\n\n afterEach(() => {\n window.localStorage.clear();\n });\n\n describe('default', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage();\n });\n\n describe('get', () => {\n it('returns null if not json encoded base64 object', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns null if nothing found', async () => {\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns object in local storage', async () => {\n window.localStorage.setItem(TEST_KEY, encodeBase64(JSON.stringify(TEST_VALUE)));\n const result = await subject.get(TEST_KEY);\n\n expect(result).toEqual(TEST_VALUE);\n });\n });\n\n describe('set', () => {\n it('updates localStorage with value', async () => {\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify(TEST_VALUE)),\n );\n });\n });\n\n describe('remove', () => {\n it('removes key from localStorage', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n\n await subject.remove(TEST_KEY);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n });\n });\n });\n\n describe('with excludeKeys', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage({\n excludeKeys: ['lorem'],\n });\n });\n\n describe('set', () => {\n it('strips excludeKeys from object', async () => {\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify({ foo: 'bar', num: 123 })),\n );\n });\n\n it('can set non-object values', async () => {\n await subject.set(TEST_KEY, 7);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(encodeBase64('7'));\n });\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"aaa600db-f6d9-4ba3-b62e-5d7f35b563e6","name":"default","imports":"[{'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}, {'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('default', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage();\n });\n\n describe('get', () => {\n it('returns null if not json encoded base64 object', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns null if nothing found', async () => {\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns object in local storage', async () => {\n window.localStorage.setItem(TEST_KEY, encodeBase64(JSON.stringify(TEST_VALUE)));\n const result = await subject.get(TEST_KEY);\n\n expect(result).toEqual(TEST_VALUE);\n });\n });\n\n describe('set', () => {\n it('updates localStorage with value', async () => {\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify(TEST_VALUE)),\n );\n });\n });\n\n describe('remove', () => {\n it('removes key from localStorage', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n\n await subject.remove(TEST_KEY);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"95e99ae0-36d3-4328-8aec-d1957009f3f9","name":"get","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('get', () => {\n it('returns null if not json encoded base64 object', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns null if nothing found', async () => {\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n });\n\n it('returns object in local storage', async () => {\n window.localStorage.setItem(TEST_KEY, encodeBase64(JSON.stringify(TEST_VALUE)));\n const result = await subject.get(TEST_KEY);\n\n expect(result).toEqual(TEST_VALUE);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"fa62b8b9-fc06-44f5-a5b1-2a259795e607","name":"set","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('set', () => {\n it('updates localStorage with value', async () => {\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify(TEST_VALUE)),\n );\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"bd39449a-1f7e-4b42-87b3-43165e2796f6","name":"remove","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('remove', () => {\n it('removes key from localStorage', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n\n await subject.remove(TEST_KEY);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"2f74a6b5-1041-430f-8512-fda0507a7cbb","name":"with excludeKeys","imports":"[{'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}, {'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('with excludeKeys', () => {\n beforeEach(() => {\n subject = new OAuthLocalStorage({\n excludeKeys: ['lorem'],\n });\n });\n\n describe('set', () => {\n it('strips excludeKeys from object', async () => {\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify({ foo: 'bar', num: 123 })),\n );\n });\n\n it('can set non-object values', async () => {\n await subject.set(TEST_KEY, 7);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(encodeBase64('7'));\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"73558d19-9f33-4540-9e23-01fe82efa0a5","name":"set","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"describe('set', () => {\n it('strips excludeKeys from object', async () => {\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify({ foo: 'bar', num: 123 })),\n );\n });\n\n it('can set non-object values', async () => {\n await subject.set(TEST_KEY, 7);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(encodeBase64('7'));\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"cfcf49c5-128e-4532-8ea2-3e1f2262158d","name":"returns null if not json encoded base64 object","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('returns null if not json encoded base64 object', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"d08be5d0-14cb-4fbb-8ef4-81b75ba7621d","name":"returns null if nothing found","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('returns null if nothing found', async () => {\n const result = await subject.get(TEST_KEY);\n\n expect(result).toBeNull();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"6e261f27-46fe-4fac-b865-8817bfbddca0","name":"returns object in local storage","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('returns object in local storage', async () => {\n window.localStorage.setItem(TEST_KEY, encodeBase64(JSON.stringify(TEST_VALUE)));\n const result = await subject.get(TEST_KEY);\n\n expect(result).toEqual(TEST_VALUE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"39ff0dae-7d1c-4217-80ec-5c2a96057414","name":"updates localStorage with value","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('updates localStorage with value', async () => {\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify(TEST_VALUE)),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"604d48ce-d9bd-44d0-98d2-e92a5b93bbdd","name":"removes key from localStorage","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('removes key from localStorage', async () => {\n window.localStorage.setItem(TEST_KEY, 'foo');\n\n await subject.remove(TEST_KEY);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBeNull();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"faea6e06-7249-4699-8085-ba6c22141b46","name":"strips excludeKeys from object","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('strips excludeKeys from object', async () => {\n await subject.set(TEST_KEY, TEST_VALUE);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(\n encodeBase64(JSON.stringify({ foo: 'bar', num: 123 })),\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"d60a66ad-0cbd-40e7-a833-991d54a6532e","name":"can set non-object values","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.test.ts","code":"it('can set non-object values', async () => {\n await subject.set(TEST_KEY, 7);\n\n expect(window.localStorage.getItem(TEST_KEY)).toBe(encodeBase64('7'));\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7b3aff68-c2d1-46f3-abc1-1ab1d9a2ac77","name":"OAuthLocalStorage.ts","imports":"[{'import_name': ['Logger'], 'import_path': '@gitlab\/logger'}, {'import_name': ['OAuthStorage'], 'import_path': '.\/types'}, {'import_name': ['encodeBase64', 'decodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"import type { Logger } from '@gitlab\/logger';\nimport type { OAuthStorage } from '.\/types';\nimport { encodeBase64, decodeBase64 } from '.\/utils';\n\ninterface OAuthLocalStorageOptions {\n readonly excludeKeys?: string[];\n readonly logger?: Logger;\n}\n\nexport class OAuthLocalStorage implements OAuthStorage {\n readonly #excludeKeys: ReadonlySet;\n\n readonly #logger?: Logger;\n\n constructor({ excludeKeys, logger }: OAuthLocalStorageOptions = {}) {\n this.#excludeKeys = new Set(excludeKeys || []);\n\n this.#logger = logger;\n }\n\n async get(key: string): Promise {\n const valueAsStr = window.localStorage.getItem(key);\n\n if (valueAsStr === null) {\n return null;\n }\n\n try {\n return JSON.parse(decodeBase64(valueAsStr)) as T;\n } catch (e) {\n this.#logger?.error('Failed to parse value for given key as JSON from localStorage', e);\n\n \/\/ note: For now we can assume that a malformed token is the same as no token\n return null;\n }\n }\n\n async set(key: string, value: unknown): Promise {\n const cleanValue = this.#cleanValue(value);\n const valueAsStr = encodeBase64(JSON.stringify(cleanValue));\n\n window.localStorage.setItem(key, valueAsStr);\n }\n\n \/\/ eslint-disable-next-line class-methods-use-this\n async remove(key: string): Promise {\n window.localStorage.removeItem(key);\n }\n\n #cleanValue(value: unknown): unknown {\n if (this.#excludeKeys.size === 0) {\n return value;\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n\n const entries = Object.entries(value).filter(([key]) => !this.#excludeKeys.has(key));\n\n return Object.fromEntries(entries);\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d3929dec-bfb0-4bc9-b719-05dc4f1f6790","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"constructor({ excludeKeys, logger }: OAuthLocalStorageOptions = {}) {\n this.#excludeKeys = new Set(excludeKeys || []);\n\n this.#logger = logger;\n }","parent":"{'type': 'class_declaration', 'name': 'OAuthLocalStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e8fea85a-d1c6-460e-9ae9-04a5d7a0b3b9","name":"get","imports":"[{'import_name': ['decodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"async get(key: string): Promise {\n const valueAsStr = window.localStorage.getItem(key);\n\n if (valueAsStr === null) {\n return null;\n }\n\n try {\n return JSON.parse(decodeBase64(valueAsStr)) as T;\n } catch (e) {\n this.#logger?.error('Failed to parse value for given key as JSON from localStorage', e);\n\n \/\/ note: For now we can assume that a malformed token is the same as no token\n return null;\n }\n }","parent":"{'type': 'class_declaration', 'name': 'OAuthLocalStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"9c1157ec-ac77-47ef-b30b-ff0d5535fc28","name":"set","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"async set(key: string, value: unknown): Promise {\n const cleanValue = this.#cleanValue(value);\n const valueAsStr = encodeBase64(JSON.stringify(cleanValue));\n\n window.localStorage.setItem(key, valueAsStr);\n }","parent":"{'type': 'class_declaration', 'name': 'OAuthLocalStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"dde6ce46-b377-4d08-adb6-7c38f2648858","name":"remove","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"async remove(key: string): Promise {\n window.localStorage.removeItem(key);\n }","parent":"{'type': 'class_declaration', 'name': 'OAuthLocalStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"90dfc08b-d231-48c7-bfc1-18e5c5125a84","name":"#cleanValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/OAuthLocalStorage.ts","code":"#cleanValue(value: unknown): unknown {\n if (this.#excludeKeys.size === 0) {\n return value;\n }\n if (!value || typeof value !== 'object') {\n return value;\n }\n\n const entries = Object.entries(value).filter(([key]) => !this.#excludeKeys.has(key));\n\n return Object.fromEntries(entries);\n }","parent":"{'type': 'class_declaration', 'name': 'OAuthLocalStorage'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"49e72a9d-e21c-422b-9c87-fb180d9ec20c","name":"StorageValueCacheBroadcaster.test.ts","imports":"[{'import_name': ['createBroadcasterStub'], 'import_path': '..\/test-utils'}, {'import_name': ['StorageValueCacheBroadcaster'], 'import_path': '.\/StorageValueCacheBroadcaster'}, {'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"import { createBroadcasterStub } from '..\/test-utils';\nimport { StorageValueCacheBroadcaster } from '.\/StorageValueCacheBroadcaster';\nimport type { OAuthStateBroadcaster, StorageValueCache } from '.\/types';\n\ndescribe('StorageValueCacheBroadcaster', () => {\n let broadcaster: OAuthStateBroadcaster;\n let base: StorageValueCache;\n let subject: StorageValueCacheBroadcaster;\n\n beforeEach(() => {\n base = {\n getValue: jest.fn().mockResolvedValue('OldTestValue'),\n setValue: jest.fn(),\n };\n broadcaster = createBroadcasterStub();\n subject = new StorageValueCacheBroadcaster(base, broadcaster);\n });\n\n describe('default', () => {\n it('getValue, calls base getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(result).toBe('OldTestValue');\n expect(base.getValue).toHaveBeenCalledWith(false);\n });\n\n it('getValue, passes along force parameter', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n\n it('setValue, calls base setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(base.setValue).toHaveBeenCalledWith('TEST');\n });\n\n it('setValue, calls notifies broadcaster', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n });\n\n describe('when broadcasted receives notification', () => {\n beforeEach(() => {\n jest.mocked(broadcaster).onTokenChange.mock.calls[0][0]();\n });\n\n it('forces refresh', async () => {\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"776638d4-fbbd-4f80-9ca7-030f66a0b4d5","name":"StorageValueCacheBroadcaster","imports":"[{'import_name': ['createBroadcasterStub'], 'import_path': '..\/test-utils'}, {'import_name': ['StorageValueCacheBroadcaster'], 'import_path': '.\/StorageValueCacheBroadcaster'}, {'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"describe('StorageValueCacheBroadcaster', () => {\n let broadcaster: OAuthStateBroadcaster;\n let base: StorageValueCache;\n let subject: StorageValueCacheBroadcaster;\n\n beforeEach(() => {\n base = {\n getValue: jest.fn().mockResolvedValue('OldTestValue'),\n setValue: jest.fn(),\n };\n broadcaster = createBroadcasterStub();\n subject = new StorageValueCacheBroadcaster(base, broadcaster);\n });\n\n describe('default', () => {\n it('getValue, calls base getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(result).toBe('OldTestValue');\n expect(base.getValue).toHaveBeenCalledWith(false);\n });\n\n it('getValue, passes along force parameter', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n\n it('setValue, calls base setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(base.setValue).toHaveBeenCalledWith('TEST');\n });\n\n it('setValue, calls notifies broadcaster', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n });\n\n describe('when broadcasted receives notification', () => {\n beforeEach(() => {\n jest.mocked(broadcaster).onTokenChange.mock.calls[0][0]();\n });\n\n it('forces refresh', async () => {\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"68ac8b97-05ec-4bc4-b416-52e165f7bdf4","name":"default","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"describe('default', () => {\n it('getValue, calls base getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(result).toBe('OldTestValue');\n expect(base.getValue).toHaveBeenCalledWith(false);\n });\n\n it('getValue, passes along force parameter', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n\n it('setValue, calls base setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(base.setValue).toHaveBeenCalledWith('TEST');\n });\n\n it('setValue, calls notifies broadcaster', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"deeb4f61-1eaf-48e5-82ad-39ff2cc35e3f","name":"when broadcasted receives notification","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"describe('when broadcasted receives notification', () => {\n beforeEach(() => {\n jest.mocked(broadcaster).onTokenChange.mock.calls[0][0]();\n });\n\n it('forces refresh', async () => {\n expect(base.getValue).toHaveBeenCalledWith(true);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"06922cac-7333-4967-bb2d-77aea1417b0b","name":"getValue, calls base getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"it('getValue, calls base getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(result).toBe('OldTestValue');\n expect(base.getValue).toHaveBeenCalledWith(false);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"4fa4f582-9013-4b09-b4cb-9aa139ba5113","name":"getValue, passes along force parameter","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"it('getValue, passes along force parameter', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"70b9121a-7077-4b6b-89c3-61ef5fe21edf","name":"setValue, calls base setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"it('setValue, calls base setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(base.setValue).toHaveBeenCalledWith('TEST');\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"73b4c2f1-5b16-40f7-a4be-70f9ccd0d363","name":"setValue, calls notifies broadcaster","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"it('setValue, calls notifies broadcaster', async () => {\n expect(broadcaster.notifyTokenChange).not.toHaveBeenCalled();\n\n await subject.setValue('TEST');\n\n expect(broadcaster.notifyTokenChange).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"203a3086-d26e-4b23-bcaa-acdb217e2947","name":"forces refresh","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.test.ts","code":"it('forces refresh', async () => {\n expect(base.getValue).toHaveBeenCalledWith(true);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"fecf9f39-a7a9-4ff2-9ab9-19439fb065a2","name":"StorageValueCacheBroadcaster.ts","imports":"[{'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.ts","code":"import type { OAuthStateBroadcaster, StorageValueCache } from '.\/types';\n\nexport class StorageValueCacheBroadcaster implements StorageValueCache {\n static decorator(\n broadcaster: OAuthStateBroadcaster,\n ): (base: StorageValueCache) => StorageValueCache {\n return base => new StorageValueCacheBroadcaster(base, broadcaster);\n }\n\n readonly #base: StorageValueCache;\n\n readonly #broadcaster: OAuthStateBroadcaster;\n\n constructor(cache: StorageValueCache, broadcaster: OAuthStateBroadcaster) {\n this.#base = cache;\n this.#broadcaster = broadcaster;\n\n this.#broadcaster.onTokenChange(() => {\n \/\/ Force refresh with \"true\"\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n this.#base.getValue(true);\n });\n }\n\n async getValue(force = false): Promise {\n return this.#base.getValue(force);\n }\n\n async setValue(value: T): Promise {\n await this.#base.setValue(value);\n\n this.#broadcaster.notifyTokenChange();\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fd761416-ffe4-4e02-8ddb-5a1208ebb0b4","name":"decorator","imports":"[{'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.ts","code":"static decorator(\n broadcaster: OAuthStateBroadcaster,\n ): (base: StorageValueCache) => StorageValueCache {\n return base => new StorageValueCacheBroadcaster(base, broadcaster);\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"5f4b4050-6d4f-404b-957d-1985e9663610","name":"constructor","imports":"[{'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.ts","code":"constructor(cache: StorageValueCache, broadcaster: OAuthStateBroadcaster) {\n this.#base = cache;\n this.#broadcaster = broadcaster;\n\n this.#broadcaster.onTokenChange(() => {\n \/\/ Force refresh with \"true\"\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n this.#base.getValue(true);\n });\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"646cbe1f-b68e-4024-a720-73f72f5abadd","name":"getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.ts","code":"async getValue(force = false): Promise {\n return this.#base.getValue(force);\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBroadcaster'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"06e731b4-7400-4a7b-87a5-9ad26dbdfbfb","name":"setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBroadcaster.ts","code":"async setValue(value: T): Promise {\n await this.#base.setValue(value);\n\n this.#broadcaster.notifyTokenChange();\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBroadcaster'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0e75e1c8-ed4c-463a-987a-32a9b222c048","name":"StorageValueCacheBuilder.ts","imports":"[{'import_name': ['DefaultStorageValueCache'], 'import_path': '.\/DefaultStorageValueCache'}, {'import_name': ['StorageValueCacheBroadcaster'], 'import_path': '.\/StorageValueCacheBroadcaster'}, {'import_name': ['StorageValueCacheEventEmitter'], 'import_path': '.\/StorageValueCacheEventEmitter'}, {'import_name': ['OAuthStateBroadcaster', 'OAuthStorage', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBuilder.ts","code":"import { DefaultStorageValueCache } from '.\/DefaultStorageValueCache';\nimport { StorageValueCacheBroadcaster } from '.\/StorageValueCacheBroadcaster';\nimport { StorageValueCacheEventEmitter } from '.\/StorageValueCacheEventEmitter';\nimport type { OAuthStateBroadcaster, OAuthStorage, StorageValueCache } from '.\/types';\n\nexport class StorageValueCacheBuilder {\n #result: StorageValueCache;\n\n constructor(storage: OAuthStorage, key: string) {\n this.#result = new DefaultStorageValueCache(storage, key);\n }\n\n withBroadcasting(broadcaster: OAuthStateBroadcaster) {\n this.#result = new StorageValueCacheBroadcaster(this.#result, broadcaster);\n\n return this;\n }\n\n withEventEmitter(emitter: EventTarget, event: string) {\n this.#result = new StorageValueCacheEventEmitter(this.#result, emitter, event);\n\n return this;\n }\n\n build(): StorageValueCache {\n return this.#result;\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8e911270-a275-445f-80a5-c76f29951dba","name":"constructor","imports":"[{'import_name': ['DefaultStorageValueCache'], 'import_path': '.\/DefaultStorageValueCache'}, {'import_name': ['OAuthStorage', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBuilder.ts","code":"constructor(storage: OAuthStorage, key: string) {\n this.#result = new DefaultStorageValueCache(storage, key);\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"fa84bf00-41d8-4e41-87bc-6aa210e66d9c","name":"withBroadcasting","imports":"[{'import_name': ['StorageValueCacheBroadcaster'], 'import_path': '.\/StorageValueCacheBroadcaster'}, {'import_name': ['OAuthStateBroadcaster', 'StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBuilder.ts","code":"withBroadcasting(broadcaster: OAuthStateBroadcaster) {\n this.#result = new StorageValueCacheBroadcaster(this.#result, broadcaster);\n\n return this;\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f0deea88-a85b-42a9-b2a9-6c20a6ef05d4","name":"withEventEmitter","imports":"[{'import_name': ['StorageValueCacheEventEmitter'], 'import_path': '.\/StorageValueCacheEventEmitter'}, {'import_name': ['StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBuilder.ts","code":"withEventEmitter(emitter: EventTarget, event: string) {\n this.#result = new StorageValueCacheEventEmitter(this.#result, emitter, event);\n\n return this;\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBuilder'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"866e5d50-f3f2-419e-a838-2e696237eb6d","name":"build","imports":"[{'import_name': ['StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheBuilder.ts","code":"build(): StorageValueCache {\n return this.#result;\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheBuilder'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"e9ac11f5-dee2-45df-adde-2c3607240a32","name":"StorageValueCacheEventEmitter.test.ts","imports":"[{'import_name': ['StorageValueCache'], 'import_path': '.\/types'}, {'import_name': ['StorageValueCacheEventEmitter'], 'import_path': '.\/StorageValueCacheEventEmitter'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"import type { StorageValueCache } from '.\/types';\nimport { StorageValueCacheEventEmitter } from '.\/StorageValueCacheEventEmitter';\n\nconst TEST_EVENT = 'test_event';\nconst TEST_VALUE = '123ABC';\n\ndescribe('StorageValueCacheEventEmitter', () => {\n let eventTarget: EventTarget;\n let listener: jest.Mock;\n let base: StorageValueCache;\n let subject: StorageValueCacheEventEmitter;\n\n beforeEach(() => {\n listener = jest.fn();\n\n eventTarget = new EventTarget();\n eventTarget.addEventListener(TEST_EVENT, listener);\n\n base = {\n getValue: jest.fn().mockResolvedValue(TEST_VALUE),\n setValue: jest.fn(),\n };\n\n subject = new StorageValueCacheEventEmitter(base, eventTarget, TEST_EVENT);\n });\n\n describe('getValue', () => {\n it('forwards base.getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(base.getValue).toHaveBeenCalledTimes(1);\n expect(base.getValue).toHaveBeenCalledWith(undefined);\n expect(result).toBe(TEST_VALUE);\n });\n\n it('without force, does not trigger event', async () => {\n await subject.getValue();\n\n expect(listener).not.toHaveBeenCalled();\n });\n\n it('with force, triggers event', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n expect(listener).toHaveBeenCalled();\n });\n });\n\n describe('setValue', () => {\n it('forwards to base.setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue(TEST_VALUE);\n\n expect(base.setValue).toHaveBeenCalledTimes(1);\n expect(base.setValue).toHaveBeenCalledWith(TEST_VALUE);\n });\n\n it('triggers event', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(listener).toHaveBeenCalledTimes(1);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"a0bc872a-e21e-4bc6-ac04-c80d7c648a37","name":"StorageValueCacheEventEmitter","imports":"[{'import_name': ['StorageValueCache'], 'import_path': '.\/types'}, {'import_name': ['StorageValueCacheEventEmitter'], 'import_path': '.\/StorageValueCacheEventEmitter'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"describe('StorageValueCacheEventEmitter', () => {\n let eventTarget: EventTarget;\n let listener: jest.Mock;\n let base: StorageValueCache;\n let subject: StorageValueCacheEventEmitter;\n\n beforeEach(() => {\n listener = jest.fn();\n\n eventTarget = new EventTarget();\n eventTarget.addEventListener(TEST_EVENT, listener);\n\n base = {\n getValue: jest.fn().mockResolvedValue(TEST_VALUE),\n setValue: jest.fn(),\n };\n\n subject = new StorageValueCacheEventEmitter(base, eventTarget, TEST_EVENT);\n });\n\n describe('getValue', () => {\n it('forwards base.getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(base.getValue).toHaveBeenCalledTimes(1);\n expect(base.getValue).toHaveBeenCalledWith(undefined);\n expect(result).toBe(TEST_VALUE);\n });\n\n it('without force, does not trigger event', async () => {\n await subject.getValue();\n\n expect(listener).not.toHaveBeenCalled();\n });\n\n it('with force, triggers event', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n expect(listener).toHaveBeenCalled();\n });\n });\n\n describe('setValue', () => {\n it('forwards to base.setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue(TEST_VALUE);\n\n expect(base.setValue).toHaveBeenCalledTimes(1);\n expect(base.setValue).toHaveBeenCalledWith(TEST_VALUE);\n });\n\n it('triggers event', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(listener).toHaveBeenCalledTimes(1);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"ee3af62c-a50e-4a1e-83e9-4964a7a50455","name":"getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"describe('getValue', () => {\n it('forwards base.getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(base.getValue).toHaveBeenCalledTimes(1);\n expect(base.getValue).toHaveBeenCalledWith(undefined);\n expect(result).toBe(TEST_VALUE);\n });\n\n it('without force, does not trigger event', async () => {\n await subject.getValue();\n\n expect(listener).not.toHaveBeenCalled();\n });\n\n it('with force, triggers event', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n expect(listener).toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"7d73b6c2-082e-4a5f-97e0-82538eeb2e18","name":"setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"describe('setValue', () => {\n it('forwards to base.setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue(TEST_VALUE);\n\n expect(base.setValue).toHaveBeenCalledTimes(1);\n expect(base.setValue).toHaveBeenCalledWith(TEST_VALUE);\n });\n\n it('triggers event', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(listener).toHaveBeenCalledTimes(1);\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"894ad0c4-8308-403b-8003-f0aed0e022a6","name":"forwards base.getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"it('forwards base.getValue', async () => {\n expect(base.getValue).not.toHaveBeenCalled();\n\n const result = await subject.getValue();\n\n expect(base.getValue).toHaveBeenCalledTimes(1);\n expect(base.getValue).toHaveBeenCalledWith(undefined);\n expect(result).toBe(TEST_VALUE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"c5f21690-ab53-4a1d-8f2f-7433fd4d7ce0","name":"without force, does not trigger event","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"it('without force, does not trigger event', async () => {\n await subject.getValue();\n\n expect(listener).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"bfac2407-e8d1-429a-a721-acedecdd1a78","name":"with force, triggers event","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"it('with force, triggers event', async () => {\n await subject.getValue(true);\n\n expect(base.getValue).toHaveBeenCalledWith(true);\n expect(listener).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"aaa4ca15-2380-4cfd-8a3e-3940e37f768f","name":"forwards to base.setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"it('forwards to base.setValue', async () => {\n expect(base.setValue).not.toHaveBeenCalled();\n\n await subject.setValue(TEST_VALUE);\n\n expect(base.setValue).toHaveBeenCalledTimes(1);\n expect(base.setValue).toHaveBeenCalledWith(TEST_VALUE);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1f56e018-edab-4082-bf22-ccef93bc6bde","name":"triggers event","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.test.ts","code":"it('triggers event', async () => {\n await subject.setValue(TEST_VALUE);\n\n expect(listener).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"dd244b6b-f932-44b0-bd21-ffc178a86968","name":"StorageValueCacheEventEmitter.ts","imports":"[{'import_name': ['StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.ts","code":"import type { StorageValueCache } from '.\/types';\n\n\/**\n * This wraps the given StorageValueCache and emits to the EventTarget whenever\n * we should consider the `value` changed:\n *\n * - `setValue` was called\n * - `getValue` with `force: true` was called\n *\/\nexport class StorageValueCacheEventEmitter implements StorageValueCache {\n readonly #base: StorageValueCache;\n\n readonly #eventTarget: EventTarget;\n\n readonly #event: string;\n\n constructor(base: StorageValueCache, eventTarget: EventTarget, event: string) {\n this.#base = base;\n this.#eventTarget = eventTarget;\n this.#event = event;\n }\n\n async getValue(force?: boolean): Promise {\n const value = await this.#base.getValue(force);\n\n if (force) {\n this.#dispatchEvent();\n }\n\n return value;\n }\n\n async setValue(value: T): Promise {\n await this.#base.setValue(value);\n\n this.#dispatchEvent();\n }\n\n #dispatchEvent() {\n this.#eventTarget.dispatchEvent(new Event(this.#event));\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"08a497e6-6048-4dc1-9684-007db8f10901","name":"constructor","imports":"[{'import_name': ['StorageValueCache'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.ts","code":"constructor(base: StorageValueCache, eventTarget: EventTarget, event: string) {\n this.#base = base;\n this.#eventTarget = eventTarget;\n this.#event = event;\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheEventEmitter'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"29adf92c-5f90-4ab2-99c0-141dddccbe1f","name":"getValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.ts","code":"async getValue(force?: boolean): Promise {\n const value = await this.#base.getValue(force);\n\n if (force) {\n this.#dispatchEvent();\n }\n\n return value;\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheEventEmitter'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"c1720d05-17f8-48e7-b000-d203845204fb","name":"setValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.ts","code":"async setValue(value: T): Promise {\n await this.#base.setValue(value);\n\n this.#dispatchEvent();\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheEventEmitter'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"1359b1ad-cb17-4547-99b7-622add453bba","name":"#dispatchEvent","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/StorageValueCacheEventEmitter.ts","code":"#dispatchEvent() {\n this.#eventTarget.dispatchEvent(new Event(this.#event));\n }","parent":"{'type': 'class_declaration', 'name': 'StorageValueCacheEventEmitter'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f4c11aa7-5b8a-4a17-9849-d6b19b1952b8","name":"asOAuthProvider.test.ts","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['createOAuthClient'], 'import_path': '.\/createOAuthClient'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['asOAuthProvider'], 'import_path': '.\/asOAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.test.ts","code":"import type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport { useFakeBroadcastChannel } from '@gitlab\/utils-test';\nimport { createOAuthClient } from '.\/createOAuthClient';\nimport type { OAuthTokenState } from '.\/types';\nimport { asOAuthProvider } from '.\/asOAuthProvider';\n\nconst TEST_TOKEN: OAuthTokenState = {\n accessToken: 'test-access-token',\n expiresAt: 0,\n};\n\ndescribe('asOAuthProvider', () => {\n useFakeBroadcastChannel();\n\n let subject: AuthProvider;\n\n beforeEach(() => {\n const client = createOAuthClient({\n oauthConfig: {\n type: 'oauth',\n callbackUrl: 'https:\/\/example.com\/oauth_callback',\n clientId: 'ABC123-456DEF',\n },\n gitlabUrl: 'https:\/\/gdk.test:3443',\n });\n jest.spyOn(client, 'getToken').mockResolvedValue(TEST_TOKEN);\n\n subject = asOAuthProvider(client);\n });\n\n it('getToken - returns token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN.accessToken);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"71aabfda-a257-4500-905f-443bdba34441","name":"asOAuthProvider","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['createOAuthClient'], 'import_path': '.\/createOAuthClient'}, {'import_name': ['asOAuthProvider'], 'import_path': '.\/asOAuthProvider'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.test.ts","code":"describe('asOAuthProvider', () => {\n useFakeBroadcastChannel();\n\n let subject: AuthProvider;\n\n beforeEach(() => {\n const client = createOAuthClient({\n oauthConfig: {\n type: 'oauth',\n callbackUrl: 'https:\/\/example.com\/oauth_callback',\n clientId: 'ABC123-456DEF',\n },\n gitlabUrl: 'https:\/\/gdk.test:3443',\n });\n jest.spyOn(client, 'getToken').mockResolvedValue(TEST_TOKEN);\n\n subject = asOAuthProvider(client);\n });\n\n it('getToken - returns token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN.accessToken);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"9cff82af-c679-4a14-ab0d-44442558cbf8","name":"getToken - returns token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.test.ts","code":"it('getToken - returns token', async () => {\n const actual = await subject.getToken();\n\n expect(actual).toEqual(TEST_TOKEN.accessToken);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7331468e-3e9c-46a1-8e48-fbadd393ab7f","name":"asOAuthProvider.ts","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['TokenProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.ts","code":"import type { AuthProvider } from '@gitlab\/gitlab-api-client';\nimport type { TokenProvider } from '.\/types';\n\nclass ApiClientOAuthProvider implements AuthProvider {\n readonly #client: TokenProvider;\n\n constructor(client: TokenProvider) {\n this.#client = client;\n }\n\n async getToken(): Promise {\n const tokenState = await this.#client.getToken();\n\n return tokenState.accessToken;\n }\n}\n\nexport const asOAuthProvider = (client: TokenProvider) => new ApiClientOAuthProvider(client);\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"2425904e-52e9-48ff-8f67-e3625cf84bb8","name":"constructor","imports":"[{'import_name': ['TokenProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.ts","code":"constructor(client: TokenProvider) {\n this.#client = client;\n }","parent":"{'type': 'class_declaration', 'name': 'ApiClientOAuthProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ece5fb7a-6c69-4283-97ce-f5d75331fbca","name":"getToken","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.ts","code":"async getToken(): Promise {\n const tokenState = await this.#client.getToken();\n\n return tokenState.accessToken;\n }","parent":"{'type': 'class_declaration', 'name': 'ApiClientOAuthProvider'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f9572eca-a348-46cc-bd25-85d8af113ee1","name":"asOAuthProvider","imports":"[{'import_name': ['AuthProvider'], 'import_path': '@gitlab\/gitlab-api-client'}, {'import_name': ['TokenProvider'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/asOAuthProvider.ts","code":"(client: TokenProvider) => new ApiClientOAuthProvider(client)","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"e017bf07-f46a-4c09-bb5f-86d50c2f95fd","name":"createOAuthClient.test.ts","imports":"[{'import_name': ['OAuthConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['Logger'], 'import_path': '@gitlab\/logger'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['createOAuthClient'], 'import_path': '.\/createOAuthClient'}, {'import_name': ['DefaultOAuthStateBroadcaster'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}, {'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/createOAuthClient.test.ts","code":"import type { OAuthConfig } from '@gitlab\/web-ide-types';\nimport { useFakeBroadcastChannel } from '@gitlab\/utils-test';\nimport { Logger } from '@gitlab\/logger';\nimport { DefaultOAuthClient } from '.\/OAuthClient';\nimport { createOAuthClient } from '.\/createOAuthClient';\nimport { DefaultOAuthStateBroadcaster } from '.\/DefaultOAuthStateBroadcaster';\nimport { OAuthLocalStorage } from '.\/OAuthLocalStorage';\n\njest.mock('.\/OAuthLocalStorage');\njest.mock('.\/OAuthClient');\n\nconst TEST_OWNER = 'root';\nconst TEST_OAUTH_CONFIG: OAuthConfig = {\n callbackUrl: 'https:\/\/example.com\/oauth_callback',\n clientId: '123456',\n type: 'oauth',\n protectRefreshToken: false,\n};\nconst TEST_GITLAB_URL = 'https:\/\/gdk.test:3443\/gitlab';\n\ndescribe('createOAuthClient', () => {\n useFakeBroadcastChannel();\n\n it('creates OAuthClient', () => {\n expect(DefaultOAuthClient).not.toHaveBeenCalled();\n\n const client = createOAuthClient({\n oauthConfig: TEST_OAUTH_CONFIG,\n owner: TEST_OWNER,\n gitlabUrl: TEST_GITLAB_URL,\n });\n\n expect(client).toBeInstanceOf(DefaultOAuthClient);\n expect(DefaultOAuthClient).toHaveBeenCalledTimes(1);\n expect(DefaultOAuthClient).toHaveBeenCalledWith({\n app: {\n clientId: TEST_OAUTH_CONFIG.clientId,\n callbackUrl: TEST_OAUTH_CONFIG.callbackUrl,\n authorizeUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/authorize',\n tokenUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/token',\n },\n owner: TEST_OWNER,\n broadcaster: expect.any(DefaultOAuthStateBroadcaster),\n storage: expect.any(OAuthLocalStorage),\n });\n });\n\n it.each`\n auth | excludeKeys\n ${{ protectRefreshToken: false }} | ${[]}\n ${{ protectRefreshToken: true }} | ${['refreshToken']}\n `('with $auth, initializes storage with excludeKeys=$excludeKeys', ({ auth, excludeKeys }) => {\n expect(OAuthLocalStorage).not.toHaveBeenCalled();\n\n createOAuthClient({\n oauthConfig: { ...TEST_OAUTH_CONFIG, ...auth },\n owner: TEST_OWNER,\n gitlabUrl: TEST_GITLAB_URL,\n });\n\n expect(OAuthLocalStorage).toHaveBeenCalledTimes(1);\n expect(OAuthLocalStorage).toHaveBeenCalledWith({ excludeKeys, logger: expect.any(Logger) });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"cfec01ff-2205-4f62-a52b-6adedfa07d9d","name":"createOAuthClient","imports":"[{'import_name': ['useFakeBroadcastChannel'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['Logger'], 'import_path': '@gitlab\/logger'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['createOAuthClient'], 'import_path': '.\/createOAuthClient'}, {'import_name': ['DefaultOAuthStateBroadcaster'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}, {'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/createOAuthClient.test.ts","code":"describe('createOAuthClient', () => {\n useFakeBroadcastChannel();\n\n it('creates OAuthClient', () => {\n expect(DefaultOAuthClient).not.toHaveBeenCalled();\n\n const client = createOAuthClient({\n oauthConfig: TEST_OAUTH_CONFIG,\n owner: TEST_OWNER,\n gitlabUrl: TEST_GITLAB_URL,\n });\n\n expect(client).toBeInstanceOf(DefaultOAuthClient);\n expect(DefaultOAuthClient).toHaveBeenCalledTimes(1);\n expect(DefaultOAuthClient).toHaveBeenCalledWith({\n app: {\n clientId: TEST_OAUTH_CONFIG.clientId,\n callbackUrl: TEST_OAUTH_CONFIG.callbackUrl,\n authorizeUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/authorize',\n tokenUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/token',\n },\n owner: TEST_OWNER,\n broadcaster: expect.any(DefaultOAuthStateBroadcaster),\n storage: expect.any(OAuthLocalStorage),\n });\n });\n\n it.each`\n auth | excludeKeys\n ${{ protectRefreshToken: false }} | ${[]}\n ${{ protectRefreshToken: true }} | ${['refreshToken']}\n `('with $auth, initializes storage with excludeKeys=$excludeKeys', ({ auth, excludeKeys }) => {\n expect(OAuthLocalStorage).not.toHaveBeenCalled();\n\n createOAuthClient({\n oauthConfig: { ...TEST_OAUTH_CONFIG, ...auth },\n owner: TEST_OWNER,\n gitlabUrl: TEST_GITLAB_URL,\n });\n\n expect(OAuthLocalStorage).toHaveBeenCalledTimes(1);\n expect(OAuthLocalStorage).toHaveBeenCalledWith({ excludeKeys, logger: expect.any(Logger) });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"7894fb15-4fe3-4dfe-b2ac-3ff9a8f02975","name":"creates OAuthClient","imports":"[{'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['createOAuthClient'], 'import_path': '.\/createOAuthClient'}, {'import_name': ['DefaultOAuthStateBroadcaster'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}, {'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/createOAuthClient.test.ts","code":"it('creates OAuthClient', () => {\n expect(DefaultOAuthClient).not.toHaveBeenCalled();\n\n const client = createOAuthClient({\n oauthConfig: TEST_OAUTH_CONFIG,\n owner: TEST_OWNER,\n gitlabUrl: TEST_GITLAB_URL,\n });\n\n expect(client).toBeInstanceOf(DefaultOAuthClient);\n expect(DefaultOAuthClient).toHaveBeenCalledTimes(1);\n expect(DefaultOAuthClient).toHaveBeenCalledWith({\n app: {\n clientId: TEST_OAUTH_CONFIG.clientId,\n callbackUrl: TEST_OAUTH_CONFIG.callbackUrl,\n authorizeUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/authorize',\n tokenUrl: 'https:\/\/gdk.test:3443\/gitlab\/oauth\/token',\n },\n owner: TEST_OWNER,\n broadcaster: expect.any(DefaultOAuthStateBroadcaster),\n storage: expect.any(OAuthLocalStorage),\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2f0d1c80-58e8-4bae-91b3-ffbb3c2510f3","name":"createOAuthClient.ts","imports":"[{'import_name': ['createConsoleLogger', 'Logger'], 'import_path': '@gitlab\/logger'}, {'import_name': ['OAuthConfig'], 'import_path': '@gitlab\/web-ide-types'}, {'import_name': ['joinPaths'], 'import_path': '@gitlab\/utils-path'}, {'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['DefaultOAuthStateBroadcaster'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/createOAuthClient.ts","code":"import { createConsoleLogger, type Logger } from '@gitlab\/logger';\nimport type { OAuthConfig } from '@gitlab\/web-ide-types';\nimport { joinPaths } from '@gitlab\/utils-path';\nimport type { OAuthClient } from '.\/OAuthClient';\nimport type { OAuthTokenState } from '.\/types';\nimport { DefaultOAuthStateBroadcaster } from '.\/DefaultOAuthStateBroadcaster';\nimport { DefaultOAuthClient } from '.\/OAuthClient';\nimport { OAuthLocalStorage } from '.\/OAuthLocalStorage';\n\ninterface CreateOAuthClientOptions {\n readonly oauthConfig: OAuthConfig;\n readonly gitlabUrl: string;\n readonly owner?: string;\n readonly logger?: Logger;\n}\n\nexport const createOAuthClient = ({\n oauthConfig,\n gitlabUrl,\n owner,\n \/\/ TODO: We should make sure we're passing a relevant logger down whenever we createOAuthClient\n logger = createConsoleLogger(),\n}: CreateOAuthClientOptions): OAuthClient => {\n const excludeKeys: (keyof OAuthTokenState)[] = [];\n if (oauthConfig.protectRefreshToken) {\n excludeKeys.push('refreshToken');\n }\n\n const storage = new OAuthLocalStorage({ excludeKeys, logger });\n const broadcaster = new DefaultOAuthStateBroadcaster();\n\n return new DefaultOAuthClient({\n app: {\n clientId: oauthConfig.clientId,\n callbackUrl: oauthConfig.callbackUrl,\n authorizeUrl: joinPaths(gitlabUrl, 'oauth\/authorize'),\n tokenUrl: joinPaths(gitlabUrl, 'oauth\/token'),\n },\n storage,\n broadcaster,\n owner,\n tokenLifetime: oauthConfig.tokenLifetime,\n });\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"94f146b1-6b02-44ba-9340-8c7323aaf846","name":"createOAuthClient","imports":"[{'import_name': ['createConsoleLogger', 'Logger'], 'import_path': '@gitlab\/logger'}, {'import_name': ['joinPaths'], 'import_path': '@gitlab\/utils-path'}, {'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}, {'import_name': ['DefaultOAuthStateBroadcaster'], 'import_path': '.\/DefaultOAuthStateBroadcaster'}, {'import_name': ['DefaultOAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['OAuthLocalStorage'], 'import_path': '.\/OAuthLocalStorage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/createOAuthClient.ts","code":"({\n oauthConfig,\n gitlabUrl,\n owner,\n \/\/ TODO: We should make sure we're passing a relevant logger down whenever we createOAuthClient\n logger = createConsoleLogger(),\n}: CreateOAuthClientOptions): OAuthClient => {\n const excludeKeys: (keyof OAuthTokenState)[] = [];\n if (oauthConfig.protectRefreshToken) {\n excludeKeys.push('refreshToken');\n }\n\n const storage = new OAuthLocalStorage({ excludeKeys, logger });\n const broadcaster = new DefaultOAuthStateBroadcaster();\n\n return new DefaultOAuthClient({\n app: {\n clientId: oauthConfig.clientId,\n callbackUrl: oauthConfig.callbackUrl,\n authorizeUrl: joinPaths(gitlabUrl, 'oauth\/authorize'),\n tokenUrl: joinPaths(gitlabUrl, 'oauth\/token'),\n },\n storage,\n broadcaster,\n owner,\n tokenLifetime: oauthConfig.tokenLifetime,\n });\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"6c8f4f1d-47e2-4aba-9f01-24f7bec5dbab","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/index.ts","code":"export * from '.\/asOAuthProvider';\nexport * from '.\/createOAuthClient';\nexport * from '.\/types';\nexport * from '.\/OAuthClient';\nexport * from '.\/setupAutoRefresh';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"68c49faf-19e7-4c85-a341-456e616b5637","name":"setupAutoRefresh.test.ts","imports":"[{'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['setupAutoRefresh'], 'import_path': '.\/setupAutoRefresh'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"import type { OAuthClient } from '.\/OAuthClient';\nimport { setupAutoRefresh } from '.\/setupAutoRefresh';\nimport type { OAuthTokenState } from '.\/types';\n\nconst FAKE_TIME = new Date('2020-01-03T05:00:00Z');\nconst FAKE_EXPIRES_TIME = new Date('2020-01-03T10:00:00Z');\n\nconst TEST_TOKEN: OAuthTokenState = {\n accessToken: 'test-access-token',\n expiresAt: FAKE_EXPIRES_TIME.getTime(),\n};\n\nconst TEST_NEW_TOKEN: OAuthTokenState = {\n accessToken: 'test-new-access-token',\n expiresAt: 0,\n};\n\n\/\/ note: I hardcode 4 minutes here because I want to test that explicit timing\nconst FOUR_MINUTES_MS = 4 * 60 * 1000;\n\ndescribe('setupAutoRefresh', () => {\n let dispose: () => void;\n let oauthClientFake: OAuthClient;\n\n const updateTokenAndTrigger = (token: OAuthTokenState) => {\n jest.mocked(oauthClientFake.getToken).mockResolvedValue(token);\n\n jest.mocked(oauthClientFake.onTokenChange).mock.calls.forEach(([callback]) => {\n callback();\n });\n };\n\n const getOnTokenChangeDispose = () =>\n jest.mocked(oauthClientFake.onTokenChange).mock.results[0].value;\n\n beforeEach(() => {\n jest.useFakeTimers().setSystemTime(FAKE_TIME);\n\n oauthClientFake = {\n checkForValidToken: jest.fn(),\n getToken: jest.fn().mockResolvedValue(TEST_TOKEN),\n handleCallback: jest.fn(),\n onTokenChange: jest.fn().mockImplementation(() => jest.fn()),\n redirectToAuthorize: jest.fn(),\n };\n\n dispose = setupAutoRefresh(oauthClientFake);\n\n \/\/ Clear initial token read since we're interested in after timeouts are set\n jest.mocked(oauthClientFake.getToken).mockClear();\n });\n\n afterEach(() => {\n dispose();\n });\n\n describe('when expiresAt time has not quite elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(\n FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS - 1,\n );\n });\n\n it('does not dispose onTokenChange listener', () => {\n expect(getOnTokenChangeDispose()).not.toHaveBeenCalled();\n });\n\n it('does not fetch new token', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n\n describe('when token has been updated and more time elapsed', () => {\n beforeEach(() => {\n updateTokenAndTrigger(TEST_NEW_TOKEN);\n\n jest.mocked(oauthClientFake.getToken).mockClear();\n\n jest.advanceTimersByTime(99999);\n });\n\n it('does not fetch new token because timeout has been cleared', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('when expiresAt time has elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n });\n\n it('fetches new token that triggers refresh', () => {\n expect(oauthClientFake.getToken).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('when disposed', () => {\n beforeEach(() => {\n dispose();\n });\n\n it('disposes token change listener', () => {\n expect(getOnTokenChangeDispose()).toHaveBeenCalled();\n });\n\n it('does not refresh when expiresAt time has elapsed', () => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8533474d-180d-4dc9-9376-842ca8ce752c","name":"setupAutoRefresh","imports":"[{'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['setupAutoRefresh'], 'import_path': '.\/setupAutoRefresh'}, {'import_name': ['OAuthTokenState'], 'import_path': '.\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"describe('setupAutoRefresh', () => {\n let dispose: () => void;\n let oauthClientFake: OAuthClient;\n\n const updateTokenAndTrigger = (token: OAuthTokenState) => {\n jest.mocked(oauthClientFake.getToken).mockResolvedValue(token);\n\n jest.mocked(oauthClientFake.onTokenChange).mock.calls.forEach(([callback]) => {\n callback();\n });\n };\n\n const getOnTokenChangeDispose = () =>\n jest.mocked(oauthClientFake.onTokenChange).mock.results[0].value;\n\n beforeEach(() => {\n jest.useFakeTimers().setSystemTime(FAKE_TIME);\n\n oauthClientFake = {\n checkForValidToken: jest.fn(),\n getToken: jest.fn().mockResolvedValue(TEST_TOKEN),\n handleCallback: jest.fn(),\n onTokenChange: jest.fn().mockImplementation(() => jest.fn()),\n redirectToAuthorize: jest.fn(),\n };\n\n dispose = setupAutoRefresh(oauthClientFake);\n\n \/\/ Clear initial token read since we're interested in after timeouts are set\n jest.mocked(oauthClientFake.getToken).mockClear();\n });\n\n afterEach(() => {\n dispose();\n });\n\n describe('when expiresAt time has not quite elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(\n FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS - 1,\n );\n });\n\n it('does not dispose onTokenChange listener', () => {\n expect(getOnTokenChangeDispose()).not.toHaveBeenCalled();\n });\n\n it('does not fetch new token', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n\n describe('when token has been updated and more time elapsed', () => {\n beforeEach(() => {\n updateTokenAndTrigger(TEST_NEW_TOKEN);\n\n jest.mocked(oauthClientFake.getToken).mockClear();\n\n jest.advanceTimersByTime(99999);\n });\n\n it('does not fetch new token because timeout has been cleared', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n });\n });\n\n describe('when expiresAt time has elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n });\n\n it('fetches new token that triggers refresh', () => {\n expect(oauthClientFake.getToken).toHaveBeenCalledTimes(1);\n });\n });\n\n describe('when disposed', () => {\n beforeEach(() => {\n dispose();\n });\n\n it('disposes token change listener', () => {\n expect(getOnTokenChangeDispose()).toHaveBeenCalled();\n });\n\n it('does not refresh when expiresAt time has elapsed', () => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"39a1a98f-7c43-435e-beb6-4dc5b434a228","name":"when expiresAt time has not quite elapsed","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"describe('when expiresAt time has not quite elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(\n FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS - 1,\n );\n });\n\n it('does not dispose onTokenChange listener', () => {\n expect(getOnTokenChangeDispose()).not.toHaveBeenCalled();\n });\n\n it('does not fetch new token', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n\n describe('when token has been updated and more time elapsed', () => {\n beforeEach(() => {\n updateTokenAndTrigger(TEST_NEW_TOKEN);\n\n jest.mocked(oauthClientFake.getToken).mockClear();\n\n jest.advanceTimersByTime(99999);\n });\n\n it('does not fetch new token because timeout has been cleared', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"03d9e9bd-9590-4054-ba16-b67cdb4c3b0e","name":"when token has been updated and more time elapsed","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"describe('when token has been updated and more time elapsed', () => {\n beforeEach(() => {\n updateTokenAndTrigger(TEST_NEW_TOKEN);\n\n jest.mocked(oauthClientFake.getToken).mockClear();\n\n jest.advanceTimersByTime(99999);\n });\n\n it('does not fetch new token because timeout has been cleared', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"7e2498ef-5405-48fb-a0b7-658edc546239","name":"when expiresAt time has elapsed","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"describe('when expiresAt time has elapsed', () => {\n beforeEach(() => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n });\n\n it('fetches new token that triggers refresh', () => {\n expect(oauthClientFake.getToken).toHaveBeenCalledTimes(1);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"484dff17-ed16-411b-886b-e75bb949edd0","name":"when disposed","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"describe('when disposed', () => {\n beforeEach(() => {\n dispose();\n });\n\n it('disposes token change listener', () => {\n expect(getOnTokenChangeDispose()).toHaveBeenCalled();\n });\n\n it('does not refresh when expiresAt time has elapsed', () => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"f90b2d05-0fb6-4964-a42a-f1392a991ec7","name":"does not dispose onTokenChange listener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('does not dispose onTokenChange listener', () => {\n expect(getOnTokenChangeDispose()).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1aca57f8-9f5a-4cf1-a01e-68cda24ba26c","name":"does not fetch new token","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('does not fetch new token', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"0333b443-617a-417f-9801-00eb91a012a0","name":"does not fetch new token because timeout has been cleared","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('does not fetch new token because timeout has been cleared', () => {\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"27e3b103-2e7e-496e-8359-25ea6244a145","name":"fetches new token that triggers refresh","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('fetches new token that triggers refresh', () => {\n expect(oauthClientFake.getToken).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"22df05fc-ade9-4bfc-a8e9-5d36376bd67c","name":"disposes token change listener","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('disposes token change listener', () => {\n expect(getOnTokenChangeDispose()).toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"eb6b9187-a2ec-4552-a0e4-6a15832dfa2d","name":"does not refresh when expiresAt time has elapsed","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.test.ts","code":"it('does not refresh when expiresAt time has elapsed', () => {\n jest.advanceTimersByTime(FAKE_EXPIRES_TIME.getTime() - FAKE_TIME.getTime() - FOUR_MINUTES_MS);\n\n expect(oauthClientFake.getToken).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"40e24ae4-03f0-4ce1-9b06-7772513a0864","name":"setupAutoRefresh.ts","imports":"[{'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['BUFFER_MS'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.ts","code":"import type { OAuthClient } from '.\/OAuthClient';\nimport { BUFFER_MS } from '.\/utils';\n\n\/\/ note: We want to be a little less than BUFFER_MS so we are guaranteed to refresh\nconst REFRESH_DELAY_BUFFER_MS = BUFFER_MS - 60 * 1000;\n\nexport const setupAutoRefresh = (oauthClient: OAuthClient) => {\n let refreshTimeout: undefined | NodeJS.Timeout;\n\n const setupRefreshForCurrentToken = async () => {\n clearTimeout(refreshTimeout);\n refreshTimeout = undefined;\n\n const token = await oauthClient.getToken();\n\n if (token.expiresAt) {\n const delay = token.expiresAt - Date.now() - REFRESH_DELAY_BUFFER_MS;\n\n refreshTimeout = setTimeout(() => {\n \/\/ note: This will trigger refresh. It's okay to fire and forget.\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n oauthClient.getToken();\n }, delay);\n }\n };\n\n const disposeTokenChangeListener = oauthClient.onTokenChange(setupRefreshForCurrentToken);\n\n \/\/ why: It's okay to fire and forget here\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n setupRefreshForCurrentToken();\n\n return () => {\n disposeTokenChangeListener();\n clearTimeout(refreshTimeout);\n };\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"89d53645-ea6e-4551-b6d7-391ff2ed7a87","name":"setupAutoRefresh","imports":"[{'import_name': ['OAuthClient'], 'import_path': '.\/OAuthClient'}, {'import_name': ['BUFFER_MS'], 'import_path': '.\/utils'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/setupAutoRefresh.ts","code":"(oauthClient: OAuthClient) => {\n let refreshTimeout: undefined | NodeJS.Timeout;\n\n const setupRefreshForCurrentToken = async () => {\n clearTimeout(refreshTimeout);\n refreshTimeout = undefined;\n\n const token = await oauthClient.getToken();\n\n if (token.expiresAt) {\n const delay = token.expiresAt - Date.now() - REFRESH_DELAY_BUFFER_MS;\n\n refreshTimeout = setTimeout(() => {\n \/\/ note: This will trigger refresh. It's okay to fire and forget.\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n oauthClient.getToken();\n }, delay);\n }\n };\n\n const disposeTokenChangeListener = oauthClient.onTokenChange(setupRefreshForCurrentToken);\n\n \/\/ why: It's okay to fire and forget here\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n setupRefreshForCurrentToken();\n\n return () => {\n disposeTokenChangeListener();\n clearTimeout(refreshTimeout);\n };\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0282eaaf-b94c-4d21-922b-cce265901860","name":"types.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/types.ts","code":"export interface OAuthApp {\n \/\/ the unique client ID of the oauth app\n readonly clientId: string;\n\n \/\/ the callback URL associated with the client ID\n readonly callbackUrl: string;\n\n \/\/ the URL of the service used to authorize for an oauth token\n readonly authorizeUrl: string;\n\n \/\/ the URL of the service used to receive a token\n readonly tokenUrl: string;\n}\n\nexport interface OAuthStorage {\n get(key: string): Promise;\n\n set(key: string, value: unknown): Promise;\n\n remove(key: string): Promise;\n}\n\nexport interface OAuthStateBroadcaster {\n notifyTokenChange(): void;\n\n onTokenChange(callback: () => void): () => void;\n\n dispose(): void;\n}\n\nexport interface OAuthHandshakeState {\n readonly state: string;\n\n readonly codeVerifier: string;\n\n readonly originalUrl: string;\n}\n\nexport interface OAuthTokenState {\n readonly accessToken: string;\n\n readonly expiresAt: number;\n\n readonly refreshToken?: string;\n\n readonly owner?: string;\n}\n\nexport interface TokenProvider {\n getToken(): Promise;\n}\n\nexport type OAuthTokenGrant =\n | {\n readonly grant_type: 'refresh_token';\n\n readonly refresh_token: string;\n }\n | {\n readonly grant_type: 'authorization_code';\n\n readonly code: string;\n\n readonly code_verifier: string;\n };\n\nexport type OAuthTokenGrantStrategy = (token: OAuthTokenState) => Promise;\n\nexport interface StorageValueCache {\n \/**\n * Return the cached value and optionally force the cache to refresh\n *\/\n getValue(force?: boolean): Promise;\n\n setValue(value: T): Promise;\n}\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"578a45c8-a9b0-44f7-9dd4-1d82d794ecce","name":"base64.test.ts","imports":"[{'import_name': ['decodeBase64', 'encodeBase64'], 'import_path': '.\/base64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.test.ts","code":"import { decodeBase64, encodeBase64 } from '.\/base64';\n\nconst TEST_CASES = [\n { text: '', base64: '' },\n { text: 'Hello World.', base64: 'SGVsbG8gV29ybGQu' },\n { text: 'Goodbye!', base64: 'R29vZGJ5ZSE=' },\n];\n\ndescribe('utils\/base64', () => {\n describe('encodeBase64', () => {\n it.each(TEST_CASES)('encodes to base64 (with input=\"$text\")', ({ text, base64 }) => {\n expect(encodeBase64(text)).toBe(base64);\n });\n });\n\n describe('decodeBase64', () => {\n it.each(TEST_CASES)('decodes from base64 (with input=\"$base64\")', ({ text, base64 }) => {\n expect(decodeBase64(base64)).toBe(text);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8754f66c-8c33-419f-9df4-a1a313308de7","name":"utils\/base64","imports":"[{'import_name': ['decodeBase64', 'encodeBase64'], 'import_path': '.\/base64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.test.ts","code":"describe('utils\/base64', () => {\n describe('encodeBase64', () => {\n it.each(TEST_CASES)('encodes to base64 (with input=\"$text\")', ({ text, base64 }) => {\n expect(encodeBase64(text)).toBe(base64);\n });\n });\n\n describe('decodeBase64', () => {\n it.each(TEST_CASES)('decodes from base64 (with input=\"$base64\")', ({ text, base64 }) => {\n expect(decodeBase64(base64)).toBe(text);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f6907853-f334-471d-b777-bbadb4a74cbe","name":"encodeBase64","imports":"[{'import_name': ['encodeBase64'], 'import_path': '.\/base64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.test.ts","code":"describe('encodeBase64', () => {\n it.each(TEST_CASES)('encodes to base64 (with input=\"$text\")', ({ text, base64 }) => {\n expect(encodeBase64(text)).toBe(base64);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"318edadd-d576-4dec-9111-fff3355ff4db","name":"decodeBase64","imports":"[{'import_name': ['decodeBase64'], 'import_path': '.\/base64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.test.ts","code":"describe('decodeBase64', () => {\n it.each(TEST_CASES)('decodes from base64 (with input=\"$base64\")', ({ text, base64 }) => {\n expect(decodeBase64(base64)).toBe(text);\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"7ade52d3-8ce3-4753-af92-c7e68113c19f","name":"base64.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.ts","code":"export const encodeBase64 = (content: string): string => {\n const bytes = new TextEncoder().encode(content);\n\n const binString = String.fromCodePoint(...bytes);\n\n return btoa(binString);\n};\n\nexport const decodeBase64 = (encoded: string): string => {\n const binString = atob(encoded);\n const bytes = Uint8Array.from(binString, m => m.codePointAt(0) || 0);\n const content = new TextDecoder().decode(bytes);\n\n return content;\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"a5acabe6-b7ea-4e96-8ba1-84535fbf3e69","name":"encodeBase64","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.ts","code":"(content: string): string => {\n const bytes = new TextEncoder().encode(content);\n\n const binString = String.fromCodePoint(...bytes);\n\n return btoa(binString);\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"8084320e-4039-4480-bd7c-e1b550b61ef7","name":"decodeBase64","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/base64.ts","code":"(encoded: string): string => {\n const binString = atob(encoded);\n const bytes = Uint8Array.from(binString, m => m.codePointAt(0) || 0);\n const content = new TextDecoder().decode(bytes);\n\n return content;\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f063122f-37f5-404f-94de-780aa9c5bf05","name":"generateAuthorizeUrl.test.ts","imports":"[{'import_name': ['OAuthApp'], 'import_path': '..\/types'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/generateAuthorizeUrl.test.ts","code":"import type { OAuthApp } from '..\/types';\nimport { generateAuthorizeUrl } from '.\/generateAuthorizeUrl';\n\nimport '@gitlab\/utils-test\/src\/jsdom.d';\nimport { sha256ForUrl } from '.\/sha256ForUrl';\n\nconst TEST_ORIGINAL_URL = 'https:\/\/example.com\/original\/url';\nconst TEST_APP: OAuthApp = {\n authorizeUrl: 'https:\/\/gdk.test:3443\/-\/oauth\/authorize',\n callbackUrl: 'https:\/\/localhost:8000\/oauth_callback.html',\n clientId: 'AB123-456DE',\n tokenUrl: 'https:\/\/gdk.test:3443\/-\/oauth\/token',\n};\nconst TEST_NANOID = '32-0123456789abcdef';\n\ndescribe('generateAuthorizeUrl', () => {\n dom.reconfigure({ url: TEST_ORIGINAL_URL });\n\n it('generates authorize URL', async () => {\n const result = generateAuthorizeUrl(TEST_APP);\n\n const codeChallenge = sha256ForUrl(TEST_NANOID);\n\n const expectedUrl = new URL(TEST_APP.authorizeUrl);\n expectedUrl.searchParams.set('client_id', TEST_APP.clientId);\n expectedUrl.searchParams.set('redirect_uri', TEST_APP.callbackUrl);\n expectedUrl.searchParams.set('response_type', 'code');\n expectedUrl.searchParams.set('scope', 'api');\n expectedUrl.searchParams.set('state', TEST_NANOID);\n expectedUrl.searchParams.set('code_challenge', codeChallenge);\n expectedUrl.searchParams.set('code_challenge_method', 'S256');\n\n await expect(result).resolves.toEqual({\n url: expectedUrl.href,\n handshakeState: {\n state: TEST_NANOID,\n codeVerifier: TEST_NANOID,\n originalUrl: TEST_ORIGINAL_URL,\n },\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"f07ee3db-ca20-4cc0-98f6-dece6f8290a0","name":"generateAuthorizeUrl","imports":"[{'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/generateAuthorizeUrl.test.ts","code":"describe('generateAuthorizeUrl', () => {\n dom.reconfigure({ url: TEST_ORIGINAL_URL });\n\n it('generates authorize URL', async () => {\n const result = generateAuthorizeUrl(TEST_APP);\n\n const codeChallenge = sha256ForUrl(TEST_NANOID);\n\n const expectedUrl = new URL(TEST_APP.authorizeUrl);\n expectedUrl.searchParams.set('client_id', TEST_APP.clientId);\n expectedUrl.searchParams.set('redirect_uri', TEST_APP.callbackUrl);\n expectedUrl.searchParams.set('response_type', 'code');\n expectedUrl.searchParams.set('scope', 'api');\n expectedUrl.searchParams.set('state', TEST_NANOID);\n expectedUrl.searchParams.set('code_challenge', codeChallenge);\n expectedUrl.searchParams.set('code_challenge_method', 'S256');\n\n await expect(result).resolves.toEqual({\n url: expectedUrl.href,\n handshakeState: {\n state: TEST_NANOID,\n codeVerifier: TEST_NANOID,\n originalUrl: TEST_ORIGINAL_URL,\n },\n });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"8dcfeeee-bf52-4856-886e-416d3b794dc5","name":"generates authorize URL","imports":"[{'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/generateAuthorizeUrl.test.ts","code":"it('generates authorize URL', async () => {\n const result = generateAuthorizeUrl(TEST_APP);\n\n const codeChallenge = sha256ForUrl(TEST_NANOID);\n\n const expectedUrl = new URL(TEST_APP.authorizeUrl);\n expectedUrl.searchParams.set('client_id', TEST_APP.clientId);\n expectedUrl.searchParams.set('redirect_uri', TEST_APP.callbackUrl);\n expectedUrl.searchParams.set('response_type', 'code');\n expectedUrl.searchParams.set('scope', 'api');\n expectedUrl.searchParams.set('state', TEST_NANOID);\n expectedUrl.searchParams.set('code_challenge', codeChallenge);\n expectedUrl.searchParams.set('code_challenge_method', 'S256');\n\n await expect(result).resolves.toEqual({\n url: expectedUrl.href,\n handshakeState: {\n state: TEST_NANOID,\n codeVerifier: TEST_NANOID,\n originalUrl: TEST_ORIGINAL_URL,\n },\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"4fee1b66-8700-42da-bdc3-2b864fc757cc","name":"generateAuthorizeUrl.ts","imports":"[{'import_name': ['customAlphabet'], 'import_path': 'nanoid\/async'}, {'import_name': ['OAuthApp', 'OAuthHandshakeState'], 'import_path': '..\/types'}, {'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/generateAuthorizeUrl.ts","code":"import { customAlphabet } from 'nanoid\/async';\nimport type { OAuthApp, OAuthHandshakeState } from '..\/types';\nimport { sha256ForUrl } from '.\/sha256ForUrl';\n\nconst nanoid = customAlphabet('0123456789abcdef', 10);\n\ninterface AuthorizeUrlResult {\n readonly handshakeState: OAuthHandshakeState;\n readonly url: string;\n}\n\nexport const generateAuthorizeUrl = async (app: OAuthApp): Promise => {\n const authorizeUrl = new URL(app.authorizeUrl);\n\n const state = await nanoid(32);\n const codeVerifier = await nanoid(32);\n const codeChallenge = sha256ForUrl(codeVerifier);\n const originalUrl = document.location.href;\n\n authorizeUrl.searchParams.set('client_id', app.clientId);\n authorizeUrl.searchParams.set('redirect_uri', app.callbackUrl);\n authorizeUrl.searchParams.set('response_type', 'code');\n authorizeUrl.searchParams.set('scope', 'api');\n authorizeUrl.searchParams.set('state', state);\n authorizeUrl.searchParams.set('code_challenge', codeChallenge);\n authorizeUrl.searchParams.set('code_challenge_method', 'S256');\n\n return {\n url: authorizeUrl.href,\n handshakeState: {\n state,\n codeVerifier,\n originalUrl,\n },\n };\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6d7a2d59-5e0a-41ff-a134-4c242bf73156","name":"generateAuthorizeUrl","imports":"[{'import_name': ['OAuthApp'], 'import_path': '..\/types'}, {'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/generateAuthorizeUrl.ts","code":"async (app: OAuthApp): Promise => {\n const authorizeUrl = new URL(app.authorizeUrl);\n\n const state = await nanoid(32);\n const codeVerifier = await nanoid(32);\n const codeChallenge = sha256ForUrl(codeVerifier);\n const originalUrl = document.location.href;\n\n authorizeUrl.searchParams.set('client_id', app.clientId);\n authorizeUrl.searchParams.set('redirect_uri', app.callbackUrl);\n authorizeUrl.searchParams.set('response_type', 'code');\n authorizeUrl.searchParams.set('scope', 'api');\n authorizeUrl.searchParams.set('state', state);\n authorizeUrl.searchParams.set('code_challenge', codeChallenge);\n authorizeUrl.searchParams.set('code_challenge_method', 'S256');\n\n return {\n url: authorizeUrl.href,\n handshakeState: {\n state,\n codeVerifier,\n originalUrl,\n },\n };\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2c2b182c-f6d9-42bb-bc14-280fc3b57ea4","name":"getGrantFromCallbackUrl.test.ts","imports":"[{'import_name': ['OAuthHandshakeState'], 'import_path': '..\/types'}, {'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.test.ts","code":"import type { OAuthHandshakeState } from '..\/types';\nimport { getGrantFromCallbackUrl } from '.\/getGrantFromCallbackUrl';\n\nconst TEST_CALLBACK_URL_BASE = 'https:\/\/example.com\/oauth_callback';\nconst TEST_CODE = 'random-code-abc';\nconst TEST_STATE = 'random-state-123';\nconst TEST_CODE_VERIFIER = 'random-code-verifier-abc';\nconst TEST_HANDSHAKE_STATE: OAuthHandshakeState = {\n codeVerifier: TEST_CODE_VERIFIER,\n originalUrl: '',\n state: TEST_STATE,\n};\n\ndescribe('utils\/getGrantFromCallbackUrl', () => {\n const createCallbackUrl = (state: string, code: string) => {\n const url = new URL(TEST_CALLBACK_URL_BASE);\n url.searchParams.set('state', state);\n url.searchParams.set('code', code);\n\n return url;\n };\n\n it('returns authorization_code grant', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, TEST_CODE);\n\n const result = getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE);\n\n expect(result).toEqual({\n grant_type: 'authorization_code',\n code: TEST_CODE,\n code_verifier: TEST_CODE_VERIFIER,\n });\n });\n\n it('throws error if state does not match handshake state', () => {\n const callbackUrl = createCallbackUrl('dne-state', TEST_CODE);\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'handshake state does not match received state',\n );\n });\n\n it('throws if code is not found', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, '');\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'code not found',\n );\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"3f9659cc-a6bd-4f11-a09d-34200c90258b","name":"utils\/getGrantFromCallbackUrl","imports":"[{'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.test.ts","code":"describe('utils\/getGrantFromCallbackUrl', () => {\n const createCallbackUrl = (state: string, code: string) => {\n const url = new URL(TEST_CALLBACK_URL_BASE);\n url.searchParams.set('state', state);\n url.searchParams.set('code', code);\n\n return url;\n };\n\n it('returns authorization_code grant', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, TEST_CODE);\n\n const result = getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE);\n\n expect(result).toEqual({\n grant_type: 'authorization_code',\n code: TEST_CODE,\n code_verifier: TEST_CODE_VERIFIER,\n });\n });\n\n it('throws error if state does not match handshake state', () => {\n const callbackUrl = createCallbackUrl('dne-state', TEST_CODE);\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'handshake state does not match received state',\n );\n });\n\n it('throws if code is not found', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, '');\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'code not found',\n );\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"d261fd25-51c4-43b2-83f9-054afb1b9b0f","name":"returns authorization_code grant","imports":"[{'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.test.ts","code":"it('returns authorization_code grant', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, TEST_CODE);\n\n const result = getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE);\n\n expect(result).toEqual({\n grant_type: 'authorization_code',\n code: TEST_CODE,\n code_verifier: TEST_CODE_VERIFIER,\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"4dbc7b8e-e0b0-43bd-9649-a70d5fec5ca3","name":"throws error if state does not match handshake state","imports":"[{'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.test.ts","code":"it('throws error if state does not match handshake state', () => {\n const callbackUrl = createCallbackUrl('dne-state', TEST_CODE);\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'handshake state does not match received state',\n );\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"b7d20d44-1d77-423d-97a3-b1d14343c1fa","name":"throws if code is not found","imports":"[{'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.test.ts","code":"it('throws if code is not found', () => {\n const callbackUrl = createCallbackUrl(TEST_STATE, '');\n\n expect(() => getGrantFromCallbackUrl(callbackUrl, TEST_HANDSHAKE_STATE)).toThrowError(\n 'code not found',\n );\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"08f42cf7-a59e-4e52-bc51-729a5b13ef37","name":"getGrantFromCallbackUrl.ts","imports":"[{'import_name': ['OAuthHandshakeState', 'OAuthTokenGrant'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.ts","code":"import type { OAuthHandshakeState, OAuthTokenGrant } from '..\/types';\n\nexport const getGrantFromCallbackUrl = (\n callbackUrl: URL,\n handshakeState: OAuthHandshakeState,\n): OAuthTokenGrant => {\n const stateParam = callbackUrl.searchParams.get('state');\n const code = callbackUrl.searchParams.get('code');\n\n if (handshakeState.state !== stateParam) {\n throw new Error('handshake state does not match received state');\n }\n\n if (!code) {\n throw new Error('code not found');\n }\n\n return {\n grant_type: 'authorization_code',\n code,\n code_verifier: handshakeState.codeVerifier,\n };\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6b903b02-a694-480d-baa1-1e78210a4de0","name":"getGrantFromCallbackUrl","imports":"[{'import_name': ['OAuthHandshakeState', 'OAuthTokenGrant'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromCallbackUrl.ts","code":"(\n callbackUrl: URL,\n handshakeState: OAuthHandshakeState,\n): OAuthTokenGrant => {\n const stateParam = callbackUrl.searchParams.get('state');\n const code = callbackUrl.searchParams.get('code');\n\n if (handshakeState.state !== stateParam) {\n throw new Error('handshake state does not match received state');\n }\n\n if (!code) {\n throw new Error('code not found');\n }\n\n return {\n grant_type: 'authorization_code',\n code,\n code_verifier: handshakeState.codeVerifier,\n };\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"326d1e90-4e19-4d77-b609-aa65321da255","name":"getGrantFromRefreshToken.test.ts","imports":"[{'import_name': ['getGrantFromRefreshToken'], 'import_path': '.\/getGrantFromRefreshToken'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromRefreshToken.test.ts","code":"import { getGrantFromRefreshToken } from '.\/getGrantFromRefreshToken';\n\nconst TEST_REFRESH_TOKEN = 'test-refresh-token';\n\ndescribe('utils\/getGrantFromRefreshToken', () => {\n it('returns refresh_token grant', () => {\n expect(getGrantFromRefreshToken(TEST_REFRESH_TOKEN)).toEqual({\n grant_type: 'refresh_token',\n refresh_token: TEST_REFRESH_TOKEN,\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"53733f93-a24e-466f-a238-2d33afd80909","name":"utils\/getGrantFromRefreshToken","imports":"[{'import_name': ['getGrantFromRefreshToken'], 'import_path': '.\/getGrantFromRefreshToken'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromRefreshToken.test.ts","code":"describe('utils\/getGrantFromRefreshToken', () => {\n it('returns refresh_token grant', () => {\n expect(getGrantFromRefreshToken(TEST_REFRESH_TOKEN)).toEqual({\n grant_type: 'refresh_token',\n refresh_token: TEST_REFRESH_TOKEN,\n });\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"1e4ff114-d026-482e-9fc1-5a85ab9eb677","name":"returns refresh_token grant","imports":"[{'import_name': ['getGrantFromRefreshToken'], 'import_path': '.\/getGrantFromRefreshToken'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromRefreshToken.test.ts","code":"it('returns refresh_token grant', () => {\n expect(getGrantFromRefreshToken(TEST_REFRESH_TOKEN)).toEqual({\n grant_type: 'refresh_token',\n refresh_token: TEST_REFRESH_TOKEN,\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"bc5c5577-708e-410f-aca7-dffdab760cbf","name":"getGrantFromRefreshToken.ts","imports":"[{'import_name': ['OAuthTokenGrant'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromRefreshToken.ts","code":"import type { OAuthTokenGrant } from '..\/types';\n\nexport const getGrantFromRefreshToken = (refreshToken: string): OAuthTokenGrant => ({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n});\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6de66445-2fa8-4e2c-8df2-b2119d9dd233","name":"getGrantFromRefreshToken","imports":"[{'import_name': ['OAuthTokenGrant'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/getGrantFromRefreshToken.ts","code":"(refreshToken: string): OAuthTokenGrant => ({\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n})","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"a8bba13d-a15c-4881-870d-a43d2afe55af","name":"iframeAuth.test.ts","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['authorizeGrantWithIframe', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/iframeAuth'}, {'import_name': ['OAuthApp', 'OAuthHandshakeState', 'OAuthTokenGrant'], 'import_path': '..\/types'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"import { createFakePartial } from '@gitlab\/utils-test';\nimport {\n authorizeGrantWithIframe,\n isCallbackFromIframe,\n notifyParentFromIframe,\n} from '.\/iframeAuth';\nimport type { OAuthApp, OAuthHandshakeState, OAuthTokenGrant } from '..\/types';\nimport { generateAuthorizeUrl } from '.\/generateAuthorizeUrl';\nimport { waitForMessage } from '.\/waitForMessage';\n\njest.mock('.\/waitForMessage');\n\nconst TEST_CALLBACK_URL_BASE = 'https:\/\/example.com\/oauth_callback';\nconst TEST_CODE = 'random-code-abc';\nconst TEST_OAUTH_APP: OAuthApp = {\n authorizeUrl: 'https:\/\/example.com\/oauth\/authorize',\n callbackUrl: TEST_CALLBACK_URL_BASE,\n clientId: 'test-client-id',\n tokenUrl: 'https:\/\/example.com\/oauth\/token',\n};\n\ndescribe('utils\/iframeAuth', () => {\n let windowParent: Window;\n let resolveWaitForMessage: () => void;\n\n const createCallbackUrl = (state: string, code: string) => {\n const url = new URL(TEST_CALLBACK_URL_BASE);\n url.searchParams.set('state', state);\n url.searchParams.set('code', code);\n\n return url;\n };\n\n const findIframe = () => {\n const iframe = document.querySelector('iframe');\n\n if (!iframe) {\n throw new Error('Expected to find iframe');\n }\n\n return iframe;\n };\n\n const setIframeHref = (href: string) => {\n Object.defineProperty(findIframe(), 'contentWindow', {\n get() {\n return createFakePartial({\n location: createFakePartial({\n href,\n }),\n });\n },\n });\n };\n\n beforeEach(() => {\n document.body.innerHTML = '';\n Object.defineProperty(window, 'parent', {\n get() {\n return windowParent;\n },\n });\n\n jest.mocked(waitForMessage).mockImplementation(\n () =>\n new Promise(resolve => {\n resolveWaitForMessage = resolve;\n }),\n );\n });\n\n describe('authorizeGrantWithIframe', () => {\n let result: Promise;\n let onFulfilledSpy: jest.Mock;\n let expectedAuthorizeUrl: string;\n let expectedHandshakeState: OAuthHandshakeState;\n\n beforeEach(async () => {\n onFulfilledSpy = jest.fn();\n result = authorizeGrantWithIframe(TEST_OAUTH_APP).then(x => {\n onFulfilledSpy();\n\n return x;\n });\n\n ({ url: expectedAuthorizeUrl, handshakeState: expectedHandshakeState } =\n await generateAuthorizeUrl(TEST_OAUTH_APP));\n });\n\n it('creates iframe', async () => {\n const iframe = findIframe();\n expect(iframe).not.toBeUndefined();\n expect(iframe.src).toBe(expectedAuthorizeUrl);\n expect(iframe.style).toMatchObject({\n width: '0px',\n height: '0px',\n position: 'absolute',\n });\n });\n\n it('does not resolve right away', async () => {\n expect(onFulfilledSpy).not.toHaveBeenCalled();\n });\n\n it('waits for \"web-ide-oauth-handshake-ready\" message', () => {\n expect(waitForMessage).toHaveBeenCalledTimes(1);\n\n const waitPredicate = jest.mocked(waitForMessage).mock.calls[0][0];\n\n expect(waitPredicate('foo')).toBe(false);\n expect(waitPredicate('web-ide-oauth-handshake-ready')).toBe(true);\n });\n\n describe('when iframe posts ready message', () => {\n beforeEach(async () => {\n setIframeHref(createCallbackUrl(expectedHandshakeState.state, TEST_CODE).href);\n\n resolveWaitForMessage();\n });\n\n it('resolves with grant', async () => {\n expect(onFulfilledSpy).toHaveBeenCalled();\n const grant = await result;\n\n expect(grant).toEqual({\n grant_type: 'authorization_code',\n code_verifier: expectedHandshakeState.codeVerifier,\n code: TEST_CODE,\n });\n });\n });\n\n describe('when iframe posts ready and href is falsey', () => {\n beforeEach(async () => {\n setIframeHref('');\n\n resolveWaitForMessage();\n });\n\n it('rejects with error', async () => {\n await expect(result).rejects.toThrow(\/Could not read callback href\/);\n });\n });\n });\n\n describe('isCallbackFromIframe', () => {\n it.each`\n desc | parent | expected\n ${'when window.parent is self'} | ${window} | ${false}\n ${'when window.parent is different'} | ${{}} | ${true}\n `('$desc, returns $expected', ({ parent, expected }) => {\n windowParent = parent;\n\n expect(isCallbackFromIframe()).toBe(expected);\n });\n });\n\n describe('notifyParentFromIframe', () => {\n it('posts message to parent frame', () => {\n windowParent = createFakePartial({\n postMessage: jest.fn(),\n });\n\n expect(windowParent.postMessage).not.toHaveBeenCalled();\n\n notifyParentFromIframe();\n\n expect(windowParent.postMessage).toHaveBeenCalledTimes(1);\n expect(windowParent.postMessage).toHaveBeenCalledWith(\n 'web-ide-oauth-handshake-ready',\n window.location.origin,\n );\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"9d5b07eb-450f-43a4-9348-01581a7f4502","name":"utils\/iframeAuth","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['authorizeGrantWithIframe', 'isCallbackFromIframe', 'notifyParentFromIframe'], 'import_path': '.\/iframeAuth'}, {'import_name': ['OAuthHandshakeState', 'OAuthTokenGrant'], 'import_path': '..\/types'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('utils\/iframeAuth', () => {\n let windowParent: Window;\n let resolveWaitForMessage: () => void;\n\n const createCallbackUrl = (state: string, code: string) => {\n const url = new URL(TEST_CALLBACK_URL_BASE);\n url.searchParams.set('state', state);\n url.searchParams.set('code', code);\n\n return url;\n };\n\n const findIframe = () => {\n const iframe = document.querySelector('iframe');\n\n if (!iframe) {\n throw new Error('Expected to find iframe');\n }\n\n return iframe;\n };\n\n const setIframeHref = (href: string) => {\n Object.defineProperty(findIframe(), 'contentWindow', {\n get() {\n return createFakePartial({\n location: createFakePartial({\n href,\n }),\n });\n },\n });\n };\n\n beforeEach(() => {\n document.body.innerHTML = '';\n Object.defineProperty(window, 'parent', {\n get() {\n return windowParent;\n },\n });\n\n jest.mocked(waitForMessage).mockImplementation(\n () =>\n new Promise(resolve => {\n resolveWaitForMessage = resolve;\n }),\n );\n });\n\n describe('authorizeGrantWithIframe', () => {\n let result: Promise;\n let onFulfilledSpy: jest.Mock;\n let expectedAuthorizeUrl: string;\n let expectedHandshakeState: OAuthHandshakeState;\n\n beforeEach(async () => {\n onFulfilledSpy = jest.fn();\n result = authorizeGrantWithIframe(TEST_OAUTH_APP).then(x => {\n onFulfilledSpy();\n\n return x;\n });\n\n ({ url: expectedAuthorizeUrl, handshakeState: expectedHandshakeState } =\n await generateAuthorizeUrl(TEST_OAUTH_APP));\n });\n\n it('creates iframe', async () => {\n const iframe = findIframe();\n expect(iframe).not.toBeUndefined();\n expect(iframe.src).toBe(expectedAuthorizeUrl);\n expect(iframe.style).toMatchObject({\n width: '0px',\n height: '0px',\n position: 'absolute',\n });\n });\n\n it('does not resolve right away', async () => {\n expect(onFulfilledSpy).not.toHaveBeenCalled();\n });\n\n it('waits for \"web-ide-oauth-handshake-ready\" message', () => {\n expect(waitForMessage).toHaveBeenCalledTimes(1);\n\n const waitPredicate = jest.mocked(waitForMessage).mock.calls[0][0];\n\n expect(waitPredicate('foo')).toBe(false);\n expect(waitPredicate('web-ide-oauth-handshake-ready')).toBe(true);\n });\n\n describe('when iframe posts ready message', () => {\n beforeEach(async () => {\n setIframeHref(createCallbackUrl(expectedHandshakeState.state, TEST_CODE).href);\n\n resolveWaitForMessage();\n });\n\n it('resolves with grant', async () => {\n expect(onFulfilledSpy).toHaveBeenCalled();\n const grant = await result;\n\n expect(grant).toEqual({\n grant_type: 'authorization_code',\n code_verifier: expectedHandshakeState.codeVerifier,\n code: TEST_CODE,\n });\n });\n });\n\n describe('when iframe posts ready and href is falsey', () => {\n beforeEach(async () => {\n setIframeHref('');\n\n resolveWaitForMessage();\n });\n\n it('rejects with error', async () => {\n await expect(result).rejects.toThrow(\/Could not read callback href\/);\n });\n });\n });\n\n describe('isCallbackFromIframe', () => {\n it.each`\n desc | parent | expected\n ${'when window.parent is self'} | ${window} | ${false}\n ${'when window.parent is different'} | ${{}} | ${true}\n `('$desc, returns $expected', ({ parent, expected }) => {\n windowParent = parent;\n\n expect(isCallbackFromIframe()).toBe(expected);\n });\n });\n\n describe('notifyParentFromIframe', () => {\n it('posts message to parent frame', () => {\n windowParent = createFakePartial({\n postMessage: jest.fn(),\n });\n\n expect(windowParent.postMessage).not.toHaveBeenCalled();\n\n notifyParentFromIframe();\n\n expect(windowParent.postMessage).toHaveBeenCalledTimes(1);\n expect(windowParent.postMessage).toHaveBeenCalledWith(\n 'web-ide-oauth-handshake-ready',\n window.location.origin,\n );\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"46675c35-51b6-46ab-887a-fa1aab349eeb","name":"authorizeGrantWithIframe","imports":"[{'import_name': ['authorizeGrantWithIframe'], 'import_path': '.\/iframeAuth'}, {'import_name': ['OAuthHandshakeState', 'OAuthTokenGrant'], 'import_path': '..\/types'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('authorizeGrantWithIframe', () => {\n let result: Promise;\n let onFulfilledSpy: jest.Mock;\n let expectedAuthorizeUrl: string;\n let expectedHandshakeState: OAuthHandshakeState;\n\n beforeEach(async () => {\n onFulfilledSpy = jest.fn();\n result = authorizeGrantWithIframe(TEST_OAUTH_APP).then(x => {\n onFulfilledSpy();\n\n return x;\n });\n\n ({ url: expectedAuthorizeUrl, handshakeState: expectedHandshakeState } =\n await generateAuthorizeUrl(TEST_OAUTH_APP));\n });\n\n it('creates iframe', async () => {\n const iframe = findIframe();\n expect(iframe).not.toBeUndefined();\n expect(iframe.src).toBe(expectedAuthorizeUrl);\n expect(iframe.style).toMatchObject({\n width: '0px',\n height: '0px',\n position: 'absolute',\n });\n });\n\n it('does not resolve right away', async () => {\n expect(onFulfilledSpy).not.toHaveBeenCalled();\n });\n\n it('waits for \"web-ide-oauth-handshake-ready\" message', () => {\n expect(waitForMessage).toHaveBeenCalledTimes(1);\n\n const waitPredicate = jest.mocked(waitForMessage).mock.calls[0][0];\n\n expect(waitPredicate('foo')).toBe(false);\n expect(waitPredicate('web-ide-oauth-handshake-ready')).toBe(true);\n });\n\n describe('when iframe posts ready message', () => {\n beforeEach(async () => {\n setIframeHref(createCallbackUrl(expectedHandshakeState.state, TEST_CODE).href);\n\n resolveWaitForMessage();\n });\n\n it('resolves with grant', async () => {\n expect(onFulfilledSpy).toHaveBeenCalled();\n const grant = await result;\n\n expect(grant).toEqual({\n grant_type: 'authorization_code',\n code_verifier: expectedHandshakeState.codeVerifier,\n code: TEST_CODE,\n });\n });\n });\n\n describe('when iframe posts ready and href is falsey', () => {\n beforeEach(async () => {\n setIframeHref('');\n\n resolveWaitForMessage();\n });\n\n it('rejects with error', async () => {\n await expect(result).rejects.toThrow(\/Could not read callback href\/);\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"4e2916ae-dee5-4fd1-9894-be3700bb79c8","name":"when iframe posts ready message","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('when iframe posts ready message', () => {\n beforeEach(async () => {\n setIframeHref(createCallbackUrl(expectedHandshakeState.state, TEST_CODE).href);\n\n resolveWaitForMessage();\n });\n\n it('resolves with grant', async () => {\n expect(onFulfilledSpy).toHaveBeenCalled();\n const grant = await result;\n\n expect(grant).toEqual({\n grant_type: 'authorization_code',\n code_verifier: expectedHandshakeState.codeVerifier,\n code: TEST_CODE,\n });\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"37f264ce-5cd1-4628-b8d9-146e3e3386ad","name":"when iframe posts ready and href is falsey","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('when iframe posts ready and href is falsey', () => {\n beforeEach(async () => {\n setIframeHref('');\n\n resolveWaitForMessage();\n });\n\n it('rejects with error', async () => {\n await expect(result).rejects.toThrow(\/Could not read callback href\/);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"61a01fd4-ec73-442d-8e30-9dbdb8f87577","name":"isCallbackFromIframe","imports":"[{'import_name': ['isCallbackFromIframe'], 'import_path': '.\/iframeAuth'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('isCallbackFromIframe', () => {\n it.each`\n desc | parent | expected\n ${'when window.parent is self'} | ${window} | ${false}\n ${'when window.parent is different'} | ${{}} | ${true}\n `('$desc, returns $expected', ({ parent, expected }) => {\n windowParent = parent;\n\n expect(isCallbackFromIframe()).toBe(expected);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"a6cc50ff-6819-421b-9e60-40c4f5370ab5","name":"notifyParentFromIframe","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['notifyParentFromIframe'], 'import_path': '.\/iframeAuth'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"describe('notifyParentFromIframe', () => {\n it('posts message to parent frame', () => {\n windowParent = createFakePartial({\n postMessage: jest.fn(),\n });\n\n expect(windowParent.postMessage).not.toHaveBeenCalled();\n\n notifyParentFromIframe();\n\n expect(windowParent.postMessage).toHaveBeenCalledTimes(1);\n expect(windowParent.postMessage).toHaveBeenCalledWith(\n 'web-ide-oauth-handshake-ready',\n window.location.origin,\n );\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"07589b16-94a0-4ef4-bf3f-ec3879c9971b","name":"creates iframe","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('creates iframe', async () => {\n const iframe = findIframe();\n expect(iframe).not.toBeUndefined();\n expect(iframe.src).toBe(expectedAuthorizeUrl);\n expect(iframe.style).toMatchObject({\n width: '0px',\n height: '0px',\n position: 'absolute',\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"e280fe5f-e8bd-4019-a9bf-0141cf402800","name":"does not resolve right away","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('does not resolve right away', async () => {\n expect(onFulfilledSpy).not.toHaveBeenCalled();\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"f5ab17dd-5fd6-4401-af08-8f7b01ebca2f","name":"waits for \"web-ide-oauth-handshake-ready\" message","imports":"[{'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('waits for \"web-ide-oauth-handshake-ready\" message', () => {\n expect(waitForMessage).toHaveBeenCalledTimes(1);\n\n const waitPredicate = jest.mocked(waitForMessage).mock.calls[0][0];\n\n expect(waitPredicate('foo')).toBe(false);\n expect(waitPredicate('web-ide-oauth-handshake-ready')).toBe(true);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"5d18448a-0f50-43f9-a1a8-0b2fb9a618d2","name":"resolves with grant","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('resolves with grant', async () => {\n expect(onFulfilledSpy).toHaveBeenCalled();\n const grant = await result;\n\n expect(grant).toEqual({\n grant_type: 'authorization_code',\n code_verifier: expectedHandshakeState.codeVerifier,\n code: TEST_CODE,\n });\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"09f8cef1-373b-479e-a63d-5e8dac831efe","name":"rejects with error","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('rejects with error', async () => {\n await expect(result).rejects.toThrow(\/Could not read callback href\/);\n })","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"585137e6-42a3-43ec-bc29-d84fbf612b8c","name":"posts message to parent frame","imports":"[{'import_name': ['createFakePartial'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['notifyParentFromIframe'], 'import_path': '.\/iframeAuth'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.test.ts","code":"it('posts message to parent frame', () => {\n windowParent = createFakePartial({\n postMessage: jest.fn(),\n });\n\n expect(windowParent.postMessage).not.toHaveBeenCalled();\n\n notifyParentFromIframe();\n\n expect(windowParent.postMessage).toHaveBeenCalledTimes(1);\n expect(windowParent.postMessage).toHaveBeenCalledWith(\n 'web-ide-oauth-handshake-ready',\n window.location.origin,\n );\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0cb5c599-c115-4169-bc13-96a640ff96cb","name":"iframeAuth.ts","imports":"[{'import_name': ['OAuthApp', 'OAuthTokenGrant'], 'import_path': '..\/types'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.ts","code":"import type { OAuthApp, OAuthTokenGrant } from '..\/types';\nimport { waitForMessage } from '.\/waitForMessage';\nimport { generateAuthorizeUrl } from '.\/generateAuthorizeUrl';\nimport { getGrantFromCallbackUrl } from '.\/getGrantFromCallbackUrl';\n\nconst MSG_WEB_IDE_OAUTH_HANDSHAKE_READY = 'web-ide-oauth-handshake-ready';\n\nexport const isCallbackFromIframe = () => window !== window.parent;\n\nexport const notifyParentFromIframe = () => {\n window.parent.postMessage(MSG_WEB_IDE_OAUTH_HANDSHAKE_READY, window.location.origin);\n};\n\nexport const authorizeGrantWithIframe = async (app: OAuthApp): Promise => {\n const { url: authorizeUrl, handshakeState } = await generateAuthorizeUrl(app);\n\n \/\/ TODO: What about timeout?\n const readyAsync = waitForMessage(data => data === MSG_WEB_IDE_OAUTH_HANDSHAKE_READY);\n\n const authorizeIframe = document.createElement('iframe');\n authorizeIframe.src = authorizeUrl;\n authorizeIframe.style.width = '0';\n authorizeIframe.style.height = '0';\n authorizeIframe.style.border = 'none';\n authorizeIframe.style.position = 'absolute';\n document.body.appendChild(authorizeIframe);\n\n await readyAsync;\n\n const callbackHref = authorizeIframe.contentWindow?.location.href;\n if (!callbackHref) {\n throw new Error('Could not read callback href');\n }\n const callbackUrl = new URL(callbackHref);\n\n return getGrantFromCallbackUrl(callbackUrl, handshakeState);\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"f8f7d71a-d858-46a0-9d51-2fac56070c83","name":"isCallbackFromIframe","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.ts","code":"() => window !== window.parent","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bbe530af-1615-48ee-808b-a84c2b326ce2","name":"notifyParentFromIframe","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.ts","code":"() => {\n window.parent.postMessage(MSG_WEB_IDE_OAUTH_HANDSHAKE_READY, window.location.origin);\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"7819fce6-2f05-4be1-a674-457e98a6b7d6","name":"authorizeGrantWithIframe","imports":"[{'import_name': ['OAuthApp', 'OAuthTokenGrant'], 'import_path': '..\/types'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}, {'import_name': ['generateAuthorizeUrl'], 'import_path': '.\/generateAuthorizeUrl'}, {'import_name': ['getGrantFromCallbackUrl'], 'import_path': '.\/getGrantFromCallbackUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/iframeAuth.ts","code":"async (app: OAuthApp): Promise => {\n const { url: authorizeUrl, handshakeState } = await generateAuthorizeUrl(app);\n\n \/\/ TODO: What about timeout?\n const readyAsync = waitForMessage(data => data === MSG_WEB_IDE_OAUTH_HANDSHAKE_READY);\n\n const authorizeIframe = document.createElement('iframe');\n authorizeIframe.src = authorizeUrl;\n authorizeIframe.style.width = '0';\n authorizeIframe.style.height = '0';\n authorizeIframe.style.border = 'none';\n authorizeIframe.style.position = 'absolute';\n document.body.appendChild(authorizeIframe);\n\n await readyAsync;\n\n const callbackHref = authorizeIframe.contentWindow?.location.href;\n if (!callbackHref) {\n throw new Error('Could not read callback href');\n }\n const callbackUrl = new URL(callbackHref);\n\n return getGrantFromCallbackUrl(callbackUrl, handshakeState);\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"3d109f12-060a-4fcc-a291-0910b3d786bd","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/index.ts","code":"export * from '.\/base64';\nexport * from '.\/generateAuthorizeUrl';\nexport * from '.\/getGrantFromCallbackUrl';\nexport * from '.\/getGrantFromRefreshToken';\nexport * from '.\/iframeAuth';\nexport * from '.\/sha256ForUrl';\nexport * from '.\/token';\nexport * from '.\/waitForMessage';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f4d197fb-6d87-4bf8-ad4c-704674916611","name":"sha256ForUrl.test.ts","imports":"[{'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/sha256ForUrl.test.ts","code":"import { sha256ForUrl } from '.\/sha256ForUrl';\n\ndescribe('utils\/sha256ForUrl', () => {\n \/\/ You can test these outputs locally by running something like:\n \/\/\n \/\/ ```\n \/\/ echo -n \"Hello World\" | openssl dgst -binary -sha256 | openssl base64\n \/\/ ```\n it.each`\n input | output\n ${'Hello World'} | ${'pZGm1Av0IEBKARczz7exkNYsZb8LzaMrV7J32a2fFG4'}\n ${'Goodbye!'} | ${'HLeyIbet2hz0xHJLMjaTlFgEgMhKuDV5XWCKxZqhMAI'}\n `('with input=\"$input\", should return a sha256 hash', ({ input, output }) => {\n const actual = sha256ForUrl(input);\n\n expect(actual).toBe(output);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"836bf455-782b-46f2-a2f1-938054c48420","name":"utils\/sha256ForUrl","imports":"[{'import_name': ['sha256ForUrl'], 'import_path': '.\/sha256ForUrl'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/sha256ForUrl.test.ts","code":"describe('utils\/sha256ForUrl', () => {\n \/\/ You can test these outputs locally by running something like:\n \/\/\n \/\/ ```\n \/\/ echo -n \"Hello World\" | openssl dgst -binary -sha256 | openssl base64\n \/\/ ```\n it.each`\n input | output\n ${'Hello World'} | ${'pZGm1Av0IEBKARczz7exkNYsZb8LzaMrV7J32a2fFG4'}\n ${'Goodbye!'} | ${'HLeyIbet2hz0xHJLMjaTlFgEgMhKuDV5XWCKxZqhMAI'}\n `('with input=\"$input\", should return a sha256 hash', ({ input, output }) => {\n const actual = sha256ForUrl(input);\n\n expect(actual).toBe(output);\n });\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"02c825a9-b7c4-46a9-a63a-67763dac74ef","name":"sha256ForUrl.ts","imports":"[{'import_name': ['sha256', 'urlSafeBase64'], 'import_path': '@gitlab\/utils-crypto'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/sha256ForUrl.ts","code":"import { sha256, urlSafeBase64 } from '@gitlab\/utils-crypto';\n\nexport const sha256ForUrl = (str: string) => {\n const input = new TextEncoder().encode(str);\n const hashed = sha256(input);\n\n return urlSafeBase64(hashed).replace(\/=\/g, '');\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6c53097c-100e-4f3b-be05-6ea1e5e17745","name":"sha256ForUrl","imports":"[{'import_name': ['sha256', 'urlSafeBase64'], 'import_path': '@gitlab\/utils-crypto'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/sha256ForUrl.ts","code":"(str: string) => {\n const input = new TextEncoder().encode(str);\n const hashed = sha256(input);\n\n return urlSafeBase64(hashed).replace(\/=\/g, '');\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"14a268f4-6483-47b1-bcd6-9e8eb0aa64df","name":"token.test.ts","imports":"[{'import_name': ['isExpiredToken', 'isValidToken', 'BUFFER_MS'], 'import_path': '.\/token'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.test.ts","code":"import { isExpiredToken, isValidToken, BUFFER_MS } from '.\/token';\n\nconst TEST_NOW = new Date(2022, 7, 5);\nconst TEST_LATER = TEST_NOW.getTime() + BUFFER_MS + 1;\nconst TEST_SOON = TEST_NOW.getTime() + BUFFER_MS - 1;\nconst TEST_PAST = TEST_NOW.getTime() - 1000;\n\ndescribe('utils\/token', () => {\n jest.useFakeTimers().setSystemTime(TEST_NOW);\n\n describe('isExpiredToken', () => {\n it.each`\n desc | expiresAt | expected\n ${'with expiresAt more than buffer MS'} | ${TEST_LATER} | ${false}\n ${'with expiresAt less than buffer MS'} | ${TEST_SOON} | ${true}\n ${'with expiresAt before now'} | ${TEST_PAST} | ${true}\n `('$desc, returns $expected', ({ expiresAt, expected }) => {\n expect(\n isExpiredToken({\n accessToken: 'abc',\n expiresAt,\n }),\n ).toBe(expected);\n });\n });\n\n describe('isValidToken', () => {\n it.each`\n token | owner | expected\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${'lorem'} | ${true}\n ${{ accessToken: '123456', expiresAt: TEST_LATER }} | ${''} | ${true}\n ${{ accessToken: '', expiresAt: TEST_LATER }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: 0 }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_SOON }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${''} | ${false}\n `('with token=$token and owner=$owner, returns $expected', ({ token, owner, expected }) => {\n expect(isValidToken(token, owner)).toBe(expected);\n });\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"8b101a47-f816-4e79-94d2-24c973e27600","name":"utils\/token","imports":"[{'import_name': ['isExpiredToken', 'isValidToken'], 'import_path': '.\/token'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.test.ts","code":"describe('utils\/token', () => {\n jest.useFakeTimers().setSystemTime(TEST_NOW);\n\n describe('isExpiredToken', () => {\n it.each`\n desc | expiresAt | expected\n ${'with expiresAt more than buffer MS'} | ${TEST_LATER} | ${false}\n ${'with expiresAt less than buffer MS'} | ${TEST_SOON} | ${true}\n ${'with expiresAt before now'} | ${TEST_PAST} | ${true}\n `('$desc, returns $expected', ({ expiresAt, expected }) => {\n expect(\n isExpiredToken({\n accessToken: 'abc',\n expiresAt,\n }),\n ).toBe(expected);\n });\n });\n\n describe('isValidToken', () => {\n it.each`\n token | owner | expected\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${'lorem'} | ${true}\n ${{ accessToken: '123456', expiresAt: TEST_LATER }} | ${''} | ${true}\n ${{ accessToken: '', expiresAt: TEST_LATER }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: 0 }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_SOON }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${''} | ${false}\n `('with token=$token and owner=$owner, returns $expected', ({ token, owner, expected }) => {\n expect(isValidToken(token, owner)).toBe(expected);\n });\n });\n})","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"53852ebc-3b66-4a64-998b-cdc5833f7917","name":"isExpiredToken","imports":"[{'import_name': ['isExpiredToken'], 'import_path': '.\/token'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.test.ts","code":"describe('isExpiredToken', () => {\n it.each`\n desc | expiresAt | expected\n ${'with expiresAt more than buffer MS'} | ${TEST_LATER} | ${false}\n ${'with expiresAt less than buffer MS'} | ${TEST_SOON} | ${true}\n ${'with expiresAt before now'} | ${TEST_PAST} | ${true}\n `('$desc, returns $expected', ({ expiresAt, expected }) => {\n expect(\n isExpiredToken({\n accessToken: 'abc',\n expiresAt,\n }),\n ).toBe(expected);\n });\n })","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"bed3d7bf-6cae-4585-88f2-023053fc449b","name":"isValidToken","imports":"[{'import_name': ['isValidToken'], 'import_path': '.\/token'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.test.ts","code":"describe('isValidToken', () => {\n it.each`\n token | owner | expected\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${'lorem'} | ${true}\n ${{ accessToken: '123456', expiresAt: TEST_LATER }} | ${''} | ${true}\n ${{ accessToken: '', expiresAt: TEST_LATER }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: 0 }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_SOON }} | ${''} | ${false}\n ${{ accessToken: '123456', expiresAt: TEST_LATER, owner: 'lorem' }} | ${''} | ${false}\n `('with token=$token and owner=$owner, returns $expected', ({ token, owner, expected }) => {\n expect(isValidToken(token, owner)).toBe(expected);\n });\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"c0680ad3-2c93-4e29-b711-7d926cb4b851","name":"token.ts","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.ts","code":"import type { OAuthTokenState } from '..\/types';\n\nexport const BUFFER_MIN = 5;\nexport const BUFFER_MS = 1000 * 60 * BUFFER_MIN; \/\/ 5 minutes\n\nexport const isExpiredToken = (state: OAuthTokenState) => state.expiresAt - BUFFER_MS < Date.now();\n\nconst hasNonEmptyValues = (state: OAuthTokenState) => Boolean(state.accessToken && state.expiresAt);\n\nconst isOwnedBy = (state: OAuthTokenState, owner: string) => owner === (state.owner || '');\n\nexport const isValidToken = (state: OAuthTokenState, owner: string) =>\n hasNonEmptyValues(state) && !isExpiredToken(state) && isOwnedBy(state, owner);\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"20b8e349-3de7-4b1b-a9bb-d270e44eacee","name":"isExpiredToken","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.ts","code":"(state: OAuthTokenState) => state.expiresAt - BUFFER_MS < Date.now()","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b413514f-0c1a-4e06-9c90-b75067ec5f01","name":"hasNonEmptyValues","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.ts","code":"(state: OAuthTokenState) => Boolean(state.accessToken && state.expiresAt)","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b4cb7b1f-51dd-4463-8605-d5a5564a72b8","name":"isOwnedBy","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.ts","code":"(state: OAuthTokenState, owner: string) => owner === (state.owner || '')","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"555d4338-df01-49cc-a388-5e26dd0709d6","name":"isValidToken","imports":"[{'import_name': ['OAuthTokenState'], 'import_path': '..\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/token.ts","code":"(state: OAuthTokenState, owner: string) =>\n hasNonEmptyValues(state) && !isExpiredToken(state) && isOwnedBy(state, owner)","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"1f90147b-141e-4346-bd91-d31796c9d833","name":"waitForMessage.test.ts","imports":"[{'import_name': ['waitForPromises'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/waitForMessage.test.ts","code":"import { waitForPromises } from '@gitlab\/utils-test';\nimport { waitForMessage } from '.\/waitForMessage';\n\nconst TEST_MESSAGE = 'test-msg';\n\ndescribe('utils\/waitForMessage', () => {\n it('returns promise that resolves when message passes predicate', async () => {\n const spy = jest.fn();\n\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n waitForMessage(x => x === TEST_MESSAGE).then(spy);\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage('bar', '*');\n window.postMessage('foo', '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).toHaveBeenCalledTimes(1);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"bfdc0efc-b003-4303-b801-58a6d6d4f51a","name":"utils\/waitForMessage","imports":"[{'import_name': ['waitForPromises'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/waitForMessage.test.ts","code":"describe('utils\/waitForMessage', () => {\n it('returns promise that resolves when message passes predicate', async () => {\n const spy = jest.fn();\n\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n waitForMessage(x => x === TEST_MESSAGE).then(spy);\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage('bar', '*');\n window.postMessage('foo', '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).toHaveBeenCalledTimes(1);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"83ed52cc-cd5d-4c67-9165-f35b20b4bcbd","name":"returns promise that resolves when message passes predicate","imports":"[{'import_name': ['waitForPromises'], 'import_path': '@gitlab\/utils-test'}, {'import_name': ['waitForMessage'], 'import_path': '.\/waitForMessage'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/waitForMessage.test.ts","code":"it('returns promise that resolves when message passes predicate', async () => {\n const spy = jest.fn();\n\n \/\/ eslint-disable-next-line @typescript-eslint\/no-floating-promises\n waitForMessage(x => x === TEST_MESSAGE).then(spy);\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage('bar', '*');\n window.postMessage('foo', '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).not.toHaveBeenCalled();\n\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n window.postMessage(TEST_MESSAGE, '*');\n \/\/ wait for promises since postMessage is async\n await waitForPromises();\n\n expect(spy).toHaveBeenCalledTimes(1);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"dec9099a-12c1-4a68-aab4-6b9f1b1a7815","name":"waitForMessage.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/waitForMessage.ts","code":"export const waitForMessage = (predicate: (data: unknown) => boolean): Promise =>\n new Promise(resolve => {\n const handler = (event: MessageEvent) => {\n if (predicate(event.data)) {\n window.removeEventListener('message', handler);\n resolve();\n }\n };\n\n window.addEventListener('message', handler);\n });\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"b6ef2583-f000-4337-a8a5-0b51fc7032e1","name":"waitForMessage","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/src\/utils\/waitForMessage.ts","code":"(predicate: (data: unknown) => boolean): Promise =>\n new Promise(resolve => {\n const handler = (event: MessageEvent) => {\n if (predicate(event.data)) {\n window.removeEventListener('message', handler);\n resolve();\n }\n };\n\n window.addEventListener('message', handler);\n })","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"9162e7b1-c7bc-460f-b3e7-8aafc4a287a9","name":"InMemoryOAuthStorage.ts","imports":"[{'import_name': ['OAuthStorage'], 'import_path': '..\/src\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"import { OAuthStorage } from '..\/src\/types';\n\nexport class InMemoryOAuthStorage implements OAuthStorage {\n readonly #map: Map;\n\n constructor() {\n this.#map = new Map();\n }\n\n async get(key: string): Promise {\n const value = this.#map.get(key);\n\n if (value === undefined) {\n return null;\n }\n\n \/\/ note: Allow casting in test util\n return value as T;\n }\n\n async set(key: string, value: unknown): Promise {\n this.#map.set(key, value);\n }\n\n async remove(key: string): Promise {\n this.#map.delete(key);\n }\n\n keys(): string[] {\n return Array.from(this.#map.keys());\n }\n}\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bedf9e03-4c90-4bbe-b98f-25fb82d16fbc","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"constructor() {\n this.#map = new Map();\n }","parent":"{'type': 'class_declaration', 'name': 'InMemoryOAuthStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"0f2b901b-0ebb-4afb-bcac-070b0a1ece89","name":"get","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"async get(key: string): Promise {\n const value = this.#map.get(key);\n\n if (value === undefined) {\n return null;\n }\n\n \/\/ note: Allow casting in test util\n return value as T;\n }","parent":"{'type': 'class_declaration', 'name': 'InMemoryOAuthStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"2828da9c-ad63-48a2-b8c8-999cbd94b7d1","name":"set","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"async set(key: string, value: unknown): Promise {\n this.#map.set(key, value);\n }","parent":"{'type': 'class_declaration', 'name': 'InMemoryOAuthStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"01748c0c-e61e-418f-b263-daae7bcfb552","name":"remove","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"async remove(key: string): Promise {\n this.#map.delete(key);\n }","parent":"{'type': 'class_declaration', 'name': 'InMemoryOAuthStorage'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d9b837ce-3428-4ffa-88f5-35c2f02d1954","name":"keys","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/InMemoryOAuthStorage.ts","code":"keys(): string[] {\n return Array.from(this.#map.keys());\n }","parent":"{'type': 'class_declaration', 'name': 'InMemoryOAuthStorage'}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"b66a434a-09dd-48eb-9029-e77a8e67fd08","name":"createBroadcasterStub.ts","imports":"[{'import_name': ['OAuthStateBroadcaster'], 'import_path': '..\/src\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/createBroadcasterStub.ts","code":"import { OAuthStateBroadcaster } from '..\/src\/types';\n\nexport const createBroadcasterStub = (): OAuthStateBroadcaster => ({\n dispose: jest.fn(),\n notifyTokenChange: jest.fn(),\n onTokenChange: jest.fn(),\n});\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d3b6f256-2602-4547-8db6-8dbfe50589a3","name":"createBroadcasterStub","imports":"[{'import_name': ['OAuthStateBroadcaster'], 'import_path': '..\/src\/types'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/createBroadcasterStub.ts","code":"(): OAuthStateBroadcaster => ({\n dispose: jest.fn(),\n notifyTokenChange: jest.fn(),\n onTokenChange: jest.fn(),\n})","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"1aaac785-56a2-4742-a2a9-b14b369b3317","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/oauth-client\/test-utils\/index.ts","code":"export * from '.\/InMemoryOAuthStorage';\nexport * from '.\/createBroadcasterStub';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"afbf64bc-91d5-4f04-b6e5-07855ce33154","name":"index.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/index.ts","code":"export * from '.\/sha256';\nexport * from '.\/urlSafeBase64';\n","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"3ec00a34-bc68-4815-b472-c97964191b89","name":"sha256.test.ts","imports":"[{'import_name': ['sha256'], 'import_path': '.\/sha256'}, {'import_name': ['urlSafeBase64'], 'import_path': '.\/urlSafeBase64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.test.ts","code":"import { sha256 } from '.\/sha256';\nimport { urlSafeBase64 } from '.\/urlSafeBase64';\n\ndescribe('sha256', () => {\n const LONG_INPUT = Array(100).fill('Lorem ipsum dolar sit amit.\\n').join('');\n\n \/\/ Verify output with the following command:\n \/\/ ```\n \/\/ echo -n \"test123\" | openssl dgst -binary -sha256 | openssl base64\n \/\/ ```\n it.each`\n input | output\n ${''} | ${'47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU='}\n ${'a'} | ${'ypeBEsobvcr6wjGzmiPcTaeG7_gUfE5yuYB3ha_uSLs='}\n ${'test123'} | ${'7NcYcNGWMxapfjrDQIyYNa2M8PPBvHA1J8MCZVNPda4='}\n ${LONG_INPUT} | ${'dcfG6GxnVCqimHtrI91JkY00Oawb--0IO1dhRwHQh50='}\n `(\n 'with input of size $input.length, returns sha256 hash',\n ({ input, output }: { input: string; output: string }) => {\n const inputEncoded = new TextEncoder().encode(input);\n const result = sha256(inputEncoded);\n\n expect(urlSafeBase64(result)).toBe(output);\n },\n );\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"984ef1d3-5638-4fcb-a641-43efae458189","name":"sha256","imports":"[{'import_name': ['sha256'], 'import_path': '.\/sha256'}, {'import_name': ['urlSafeBase64'], 'import_path': '.\/urlSafeBase64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.test.ts","code":"describe('sha256', () => {\n const LONG_INPUT = Array(100).fill('Lorem ipsum dolar sit amit.\\n').join('');\n\n \/\/ Verify output with the following command:\n \/\/ ```\n \/\/ echo -n \"test123\" | openssl dgst -binary -sha256 | openssl base64\n \/\/ ```\n it.each`\n input | output\n ${''} | ${'47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU='}\n ${'a'} | ${'ypeBEsobvcr6wjGzmiPcTaeG7_gUfE5yuYB3ha_uSLs='}\n ${'test123'} | ${'7NcYcNGWMxapfjrDQIyYNa2M8PPBvHA1J8MCZVNPda4='}\n ${LONG_INPUT} | ${'dcfG6GxnVCqimHtrI91JkY00Oawb--0IO1dhRwHQh50='}\n `(\n 'with input of size $input.length, returns sha256 hash',\n ({ input, output }: { input: string; output: string }) => {\n const inputEncoded = new TextEncoder().encode(input);\n const result = sha256(inputEncoded);\n\n expect(urlSafeBase64(result)).toBe(output);\n },\n );\n})","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"53795ed1-cc7c-4492-9c9e-1aa579484aef","name":"sha256.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"\/\/ The following code is lovingly borrowed from:\n\/\/ - https:\/\/github.com\/kawanet\/sha256-uint8array\/blob\/a035f83824c319d01ca1e7559fdcf1632c0cd6c4\/lib\/sha256-uint8array.ts\n\/\/ - MIT License Copyright (c) 2020-2023 Yusuke Kawasaki\n\/* eslint-disable *\/\n\n\/\/ first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311\nconst K = [\n 0x428a2f98 | 0,\n 0x71374491 | 0,\n 0xb5c0fbcf | 0,\n 0xe9b5dba5 | 0,\n 0x3956c25b | 0,\n 0x59f111f1 | 0,\n 0x923f82a4 | 0,\n 0xab1c5ed5 | 0,\n 0xd807aa98 | 0,\n 0x12835b01 | 0,\n 0x243185be | 0,\n 0x550c7dc3 | 0,\n 0x72be5d74 | 0,\n 0x80deb1fe | 0,\n 0x9bdc06a7 | 0,\n 0xc19bf174 | 0,\n 0xe49b69c1 | 0,\n 0xefbe4786 | 0,\n 0x0fc19dc6 | 0,\n 0x240ca1cc | 0,\n 0x2de92c6f | 0,\n 0x4a7484aa | 0,\n 0x5cb0a9dc | 0,\n 0x76f988da | 0,\n 0x983e5152 | 0,\n 0xa831c66d | 0,\n 0xb00327c8 | 0,\n 0xbf597fc7 | 0,\n 0xc6e00bf3 | 0,\n 0xd5a79147 | 0,\n 0x06ca6351 | 0,\n 0x14292967 | 0,\n 0x27b70a85 | 0,\n 0x2e1b2138 | 0,\n 0x4d2c6dfc | 0,\n 0x53380d13 | 0,\n 0x650a7354 | 0,\n 0x766a0abb | 0,\n 0x81c2c92e | 0,\n 0x92722c85 | 0,\n 0xa2bfe8a1 | 0,\n 0xa81a664b | 0,\n 0xc24b8b70 | 0,\n 0xc76c51a3 | 0,\n 0xd192e819 | 0,\n 0xd6990624 | 0,\n 0xf40e3585 | 0,\n 0x106aa070 | 0,\n 0x19a4c116 | 0,\n 0x1e376c08 | 0,\n 0x2748774c | 0,\n 0x34b0bcb5 | 0,\n 0x391c0cb3 | 0,\n 0x4ed8aa4a | 0,\n 0x5b9cca4f | 0,\n 0x682e6ff3 | 0,\n 0x748f82ee | 0,\n 0x78a5636f | 0,\n 0x84c87814 | 0,\n 0x8cc70208 | 0,\n 0x90befffa | 0,\n 0xa4506ceb | 0,\n 0xbef9a3f7 | 0,\n 0xc67178f2 | 0,\n];\n\nconst enum N {\n inputBytes = 64,\n inputWords = inputBytes \/ 4,\n highIndex = inputWords - 2,\n lowIndex = inputWords - 1,\n workWords = 64,\n allocBytes = 80,\n allocWords = allocBytes \/ 4,\n allocTotal = allocBytes,\n}\n\nclass Hash {\n \/\/ first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n private A = 0x6a09e667 | 0;\n private B = 0xbb67ae85 | 0;\n private C = 0x3c6ef372 | 0;\n private D = 0xa54ff53a | 0;\n private E = 0x510e527f | 0;\n private F = 0x9b05688c | 0;\n private G = 0x1f83d9ab | 0;\n private H = 0x5be0cd19 | 0;\n\n private _byte: Uint8Array;\n private _word: Int32Array;\n private _size = 0;\n\n \/\/ GITLAB NOTE: These variables `W` and `sharedBuffer` were originally\n \/\/ shared across every instance of Hash this seemed like unnecessary\n \/\/ optimization and potentially dangerous so we've moved them as class variables\n private _W: Int32Array;\n\n private _sharedBuffer: ArrayBuffer;\n\n constructor() {\n this._W = new Int32Array(N.workWords);\n this._sharedBuffer = new ArrayBuffer(N.allocTotal);\n\n this._byte = new Uint8Array(this._sharedBuffer, 0, N.allocBytes);\n this._word = new Int32Array(this._sharedBuffer, 0, N.allocWords);\n }\n\n update(data: Uint8Array): this;\n update(data: ArrayBufferView): this;\n\n update(data: Uint8Array | ArrayBufferView): this {\n \/\/ data: undefined\n if (data == null) {\n throw new TypeError('Invalid type: ' + typeof data);\n }\n\n const byteOffset = data.byteOffset;\n const length = data.byteLength;\n let blocks = (length \/ N.inputBytes) | 0;\n let offset = 0;\n\n \/\/ longer than 1 block\n if (blocks && !(byteOffset & 3) && !(this._size % N.inputBytes)) {\n const block = new Int32Array(data.buffer, byteOffset, blocks * N.inputWords);\n while (blocks--) {\n this._int32(block, offset >> 2);\n offset += N.inputBytes;\n }\n this._size += offset;\n }\n\n \/\/ data: TypedArray | DataView\n const BYTES_PER_ELEMENT = (data as Uint8Array).BYTES_PER_ELEMENT;\n if (BYTES_PER_ELEMENT !== 1 && data.buffer) {\n const rest = new Uint8Array(data.buffer, byteOffset + offset, length - offset);\n return this._uint8(rest);\n }\n\n \/\/ no more bytes\n if (offset === length) return this;\n\n \/\/ data: Uint8Array | Int8Array\n return this._uint8(data as any, offset);\n }\n\n private _uint8(data: Uint8Array, offset?: number) {\n const { _byte, _word } = this;\n const length = data.length;\n offset = offset!! | 0;\n\n while (offset < length) {\n const start = this._size % N.inputBytes;\n let index = start;\n\n while (offset < length && index < N.inputBytes) {\n _byte[index++] = data[offset++];\n }\n\n if (index >= N.inputBytes) {\n this._int32(_word);\n }\n\n this._size += index - start;\n }\n\n return this;\n }\n\n private _int32(data: Int32Array, offset?: number): void {\n let { A, B, C, D, E, F, G, H, _W: W } = this;\n let i = 0;\n offset = offset!! | 0;\n\n while (i < N.inputWords) {\n W[i++] = swap32(data[offset++]);\n }\n\n for (i = N.inputWords; i < N.workWords; i++) {\n W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0;\n }\n\n for (i = 0; i < N.workWords; i++) {\n const T1 = (H + sigma1(E) + ch(E, F, G) + K[i] + W[i]) | 0;\n const T2 = (sigma0(A) + maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n\n this.A = (A + this.A) | 0;\n this.B = (B + this.B) | 0;\n this.C = (C + this.C) | 0;\n this.D = (D + this.D) | 0;\n this.E = (E + this.E) | 0;\n this.F = (F + this.F) | 0;\n this.G = (G + this.G) | 0;\n this.H = (H + this.H) | 0;\n }\n\n digest(): Uint8Array {\n const { _byte, _word } = this;\n let i = this._size % N.inputBytes | 0;\n _byte[i++] = 0x80;\n\n \/\/ pad 0 for current word\n while (i & 3) {\n _byte[i++] = 0;\n }\n i >>= 2;\n\n if (i > N.highIndex) {\n while (i < N.inputWords) {\n _word[i++] = 0;\n }\n i = 0;\n this._int32(_word);\n }\n\n \/\/ pad 0 for rest words\n while (i < N.inputWords) {\n _word[i++] = 0;\n }\n\n \/\/ input size\n const bits64 = this._size * 8;\n const low32 = (bits64 & 0xffffffff) >>> 0;\n const high32 = (bits64 - low32) \/ 0x100000000;\n if (high32) _word[N.highIndex] = swap32(high32);\n if (low32) _word[N.lowIndex] = swap32(low32);\n\n this._int32(_word);\n\n return this._bin();\n }\n\n private _bin(): Uint8Array {\n const { A, B, C, D, E, F, G, H, _byte, _word } = this;\n\n _word[0] = swap32(A);\n _word[1] = swap32(B);\n _word[2] = swap32(C);\n _word[3] = swap32(D);\n _word[4] = swap32(E);\n _word[5] = swap32(F);\n _word[6] = swap32(G);\n _word[7] = swap32(H);\n\n return _byte.slice(0, 32);\n }\n}\n\ntype NN = (num: number) => number;\ntype N3N = (x: number, y: number, z: number) => number;\n\nconst swapLE: NN = c =>\n ((c << 24) & 0xff000000) | ((c << 8) & 0xff0000) | ((c >> 8) & 0xff00) | ((c >> 24) & 0xff);\nconst swapBE: NN = c => c;\nconst swap32: NN = isBE() ? swapBE : swapLE;\n\nconst ch: N3N = (x, y, z) => z ^ (x & (y ^ z));\nconst maj: N3N = (x, y, z) => (x & y) | (z & (x | y));\n\nconst sigma0: NN = x =>\n ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10));\nconst sigma1: NN = x =>\n ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7));\nconst gamma0: NN = x => ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);\nconst gamma1: NN = x => ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10);\n\nfunction isBE(): boolean {\n const buf = new Uint8Array(new Uint16Array([0xfeff]).buffer); \/\/ BOM\n return buf[0] === 0xfe;\n}\n\/* eslint-enable *\/\n\nexport const sha256 = function sha256(data: Uint8Array) {\n return new Hash().update(data).digest();\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"89aeb459-e099-479e-b064-aa25878c0e3f","name":"constructor","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"constructor() {\n this._W = new Int32Array(N.workWords);\n this._sharedBuffer = new ArrayBuffer(N.allocTotal);\n\n this._byte = new Uint8Array(this._sharedBuffer, 0, N.allocBytes);\n this._word = new Int32Array(this._sharedBuffer, 0, N.allocWords);\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"aee70b69-4126-4443-bfde-a67abfc8ed75","name":"update","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"update(data: Uint8Array | ArrayBufferView): this {\n \/\/ data: undefined\n if (data == null) {\n throw new TypeError('Invalid type: ' + typeof data);\n }\n\n const byteOffset = data.byteOffset;\n const length = data.byteLength;\n let blocks = (length \/ N.inputBytes) | 0;\n let offset = 0;\n\n \/\/ longer than 1 block\n if (blocks && !(byteOffset & 3) && !(this._size % N.inputBytes)) {\n const block = new Int32Array(data.buffer, byteOffset, blocks * N.inputWords);\n while (blocks--) {\n this._int32(block, offset >> 2);\n offset += N.inputBytes;\n }\n this._size += offset;\n }\n\n \/\/ data: TypedArray | DataView\n const BYTES_PER_ELEMENT = (data as Uint8Array).BYTES_PER_ELEMENT;\n if (BYTES_PER_ELEMENT !== 1 && data.buffer) {\n const rest = new Uint8Array(data.buffer, byteOffset + offset, length - offset);\n return this._uint8(rest);\n }\n\n \/\/ no more bytes\n if (offset === length) return this;\n\n \/\/ data: Uint8Array | Int8Array\n return this._uint8(data as any, offset);\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d3a0ef9a-b171-4f23-ace6-5d66cc9b5165","name":"_uint8","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"private _uint8(data: Uint8Array, offset?: number) {\n const { _byte, _word } = this;\n const length = data.length;\n offset = offset!! | 0;\n\n while (offset < length) {\n const start = this._size % N.inputBytes;\n let index = start;\n\n while (offset < length && index < N.inputBytes) {\n _byte[index++] = data[offset++];\n }\n\n if (index >= N.inputBytes) {\n this._int32(_word);\n }\n\n this._size += index - start;\n }\n\n return this;\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"6816634e-415f-4d1a-91a9-4bfbc87b9393","name":"_int32","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"private _int32(data: Int32Array, offset?: number): void {\n let { A, B, C, D, E, F, G, H, _W: W } = this;\n let i = 0;\n offset = offset!! | 0;\n\n while (i < N.inputWords) {\n W[i++] = swap32(data[offset++]);\n }\n\n for (i = N.inputWords; i < N.workWords; i++) {\n W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0;\n }\n\n for (i = 0; i < N.workWords; i++) {\n const T1 = (H + sigma1(E) + ch(E, F, G) + K[i] + W[i]) | 0;\n const T2 = (sigma0(A) + maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n\n this.A = (A + this.A) | 0;\n this.B = (B + this.B) | 0;\n this.C = (C + this.C) | 0;\n this.D = (D + this.D) | 0;\n this.E = (E + this.E) | 0;\n this.F = (F + this.F) | 0;\n this.G = (G + this.G) | 0;\n this.H = (H + this.H) | 0;\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"0fda3394-8686-4eb1-9fef-fdb68b0059b3","name":"digest","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"digest(): Uint8Array {\n const { _byte, _word } = this;\n let i = this._size % N.inputBytes | 0;\n _byte[i++] = 0x80;\n\n \/\/ pad 0 for current word\n while (i & 3) {\n _byte[i++] = 0;\n }\n i >>= 2;\n\n if (i > N.highIndex) {\n while (i < N.inputWords) {\n _word[i++] = 0;\n }\n i = 0;\n this._int32(_word);\n }\n\n \/\/ pad 0 for rest words\n while (i < N.inputWords) {\n _word[i++] = 0;\n }\n\n \/\/ input size\n const bits64 = this._size * 8;\n const low32 = (bits64 & 0xffffffff) >>> 0;\n const high32 = (bits64 - low32) \/ 0x100000000;\n if (high32) _word[N.highIndex] = swap32(high32);\n if (low32) _word[N.lowIndex] = swap32(low32);\n\n this._int32(_word);\n\n return this._bin();\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e744cac7-8187-43be-9b97-5953b89efd74","name":"_bin","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"private _bin(): Uint8Array {\n const { A, B, C, D, E, F, G, H, _byte, _word } = this;\n\n _word[0] = swap32(A);\n _word[1] = swap32(B);\n _word[2] = swap32(C);\n _word[3] = swap32(D);\n _word[4] = swap32(E);\n _word[5] = swap32(F);\n _word[6] = swap32(G);\n _word[7] = swap32(H);\n\n return _byte.slice(0, 32);\n }","parent":"{'type': 'class_declaration', 'name': 'Hash'}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"1c3d3fdf-c6e6-43e7-a298-6580049b4171","name":"swapLE","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"c =>\n ((c << 24) & 0xff000000) | ((c << 8) & 0xff0000) | ((c >> 8) & 0xff00) | ((c >> 24) & 0xff)","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"bccad912-0a6d-439d-ab65-fdfcfd0527c1","name":"swapBE","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"c => c","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ba809928-5587-4793-ae55-17ccba15839f","name":"ch","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"(x, y, z) => z ^ (x & (y ^ z))","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"dc9d05a4-4b1f-477a-8381-c179eb8099c4","name":"maj","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"(x, y, z) => (x & y) | (z & (x | y))","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"2b08a88c-8209-4ff1-9c18-2e738b68c719","name":"sigma0","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"x =>\n ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10))","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"d5f56ea1-7dcb-4c51-85da-cf7a08f6610f","name":"sigma1","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"x =>\n ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7))","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"212c0de2-8110-4262-8ba1-12c55f84dda7","name":"gamma0","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"x => ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3)","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e42287e0-8713-45f0-9487-07d058f02497","name":"gamma1","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"x => ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10)","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"ba14373a-7e08-4ae9-b66b-354716dd3aa2","name":"isBE","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"function isBE(): boolean {\n const buf = new Uint8Array(new Uint16Array([0xfeff]).buffer); \/\/ BOM\n return buf[0] === 0xfe;\n}","parent":"{}"} {"element_type":"function","project_name":"tsgitlabtest","uuid":"950327ee-f6af-462f-8a86-fdb73768c8d6","name":"sha256","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/sha256.ts","code":"function sha256(data: Uint8Array) {\n return new Hash().update(data).digest();\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"f01d6d0a-631f-4faa-977a-cd627a7cf19f","name":"urlSafeBase64.test.ts","imports":"[{'import_name': ['urlSafeBase64'], 'import_path': '.\/urlSafeBase64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/urlSafeBase64.test.ts","code":"import { urlSafeBase64 } from '.\/urlSafeBase64';\n\ndescribe('urlSafeBase64', () => {\n it('converts a Uint8Array of character codes into base64 string', () => {\n const str = 'Hello world!';\n const strAsBase64 = btoa(str);\n const typedArray = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i += 1) {\n typedArray.set([str.charCodeAt(i)], i);\n }\n\n const actual = urlSafeBase64(typedArray);\n\n expect(actual).toBe(strAsBase64);\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"5cbcd044-ad15-4e5a-8a4f-cf2369f9ca72","name":"urlSafeBase64","imports":"[{'import_name': ['urlSafeBase64'], 'import_path': '.\/urlSafeBase64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/urlSafeBase64.test.ts","code":"describe('urlSafeBase64', () => {\n it('converts a Uint8Array of character codes into base64 string', () => {\n const str = 'Hello world!';\n const strAsBase64 = btoa(str);\n const typedArray = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i += 1) {\n typedArray.set([str.charCodeAt(i)], i);\n }\n\n const actual = urlSafeBase64(typedArray);\n\n expect(actual).toBe(strAsBase64);\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"bf5fd9f3-90f0-434d-acba-87ac6b8e6955","name":"converts a Uint8Array of character codes into base64 string","imports":"[{'import_name': ['urlSafeBase64'], 'import_path': '.\/urlSafeBase64'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/urlSafeBase64.test.ts","code":"it('converts a Uint8Array of character codes into base64 string', () => {\n const str = 'Hello world!';\n const strAsBase64 = btoa(str);\n const typedArray = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i += 1) {\n typedArray.set([str.charCodeAt(i)], i);\n }\n\n const actual = urlSafeBase64(typedArray);\n\n expect(actual).toBe(strAsBase64);\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"0690a204-1deb-4a6f-b048-3be07dadbe1d","name":"urlSafeBase64.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/urlSafeBase64.ts","code":"\/**\n * This converts a Uint8Array into URL safe base64\n *\n * This shoudl be equivalent to Ruby's `Base64.urlsafe_encode64`.\n * See [this relevant bit from Doorkeeper][1].\n *\n * [1]: https:\/\/github.com\/doorkeeper-gem\/doorkeeper\/blob\/0aa94c5a82035ec4840785156760a2930e5de27a\/lib\/doorkeeper\/models\/access_grant_mixin.rb#L92\n *\/\nexport const urlSafeBase64 = (arr: Uint8Array) => {\n const arrAsString = String.fromCharCode(...arr);\n\n \/\/ We need to be browser compatible so we use btoa\n const base64 = btoa(arrAsString);\n\n return base64.replace(\/\\+\/g, '-').replace(\/\\\/\/g, '_');\n};\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"c6be0224-b4f2-40cb-9875-b407991a3065","name":"urlSafeBase64","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-crypto\/src\/urlSafeBase64.ts","code":"(arr: Uint8Array) => {\n const arrAsString = String.fromCharCode(...arr);\n\n \/\/ We need to be browser compatible so we use btoa\n const base64 = btoa(arrAsString);\n\n return base64.replace(\/\\+\/g, '-').replace(\/\\\/\/g, '_');\n}","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"e7f7f840-4f2d-4c51-9d68-036a2d77b81f","name":"escapeCssQuotedValue.test.ts","imports":"[{'import_name': ['escapeCssQuotedValue'], 'import_path': '.\/escapeCssQuotedValue'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeCssQuotedValue.test.ts","code":"import { escapeCssQuotedValue } from '.\/escapeCssQuotedValue';\n\ndescribe('utils\/escape\/escapeCssQuotedValue', () => {\n it('escapes single and double quotes', () => {\n expect(escapeCssQuotedValue(`http:\/\/comma\/'\"`)).toBe('http:\/\/comma\/%27%22');\n });\n});\n","parent":null} {"element_type":"test","project_name":"tsgitlabtest","uuid":"a7ca38c2-1d8b-4f04-94c3-c88e1f8500d2","name":"utils\/escape\/escapeCssQuotedValue","imports":"[{'import_name': ['escapeCssQuotedValue'], 'import_path': '.\/escapeCssQuotedValue'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeCssQuotedValue.test.ts","code":"describe('utils\/escape\/escapeCssQuotedValue', () => {\n it('escapes single and double quotes', () => {\n expect(escapeCssQuotedValue(`http:\/\/comma\/'\"`)).toBe('http:\/\/comma\/%27%22');\n });\n})","parent":null} {"element_type":"test case","project_name":"tsgitlabtest","uuid":"adf3072f-8937-4806-9401-3591ba74e562","name":"escapes single and double quotes","imports":"[{'import_name': ['escapeCssQuotedValue'], 'import_path': '.\/escapeCssQuotedValue'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeCssQuotedValue.test.ts","code":"it('escapes single and double quotes', () => {\n expect(escapeCssQuotedValue(`http:\/\/comma\/'\"`)).toBe('http:\/\/comma\/%27%22');\n })","parent":null} {"element_type":"file","project_name":"tsgitlabtest","uuid":"2ef26b4a-de99-479f-8b40-dd097892f17c","name":"escapeCssQuotedValue.ts","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeCssQuotedValue.ts","code":"\/\/ doesn't allow the value to end the quoted string\nexport const escapeCssQuotedValue = (val: string) => val.replace('\"', '%22').replace(\"'\", '%27');\n","parent":null} {"element_type":"function","project_name":"tsgitlabtest","uuid":"e0f0ed10-d461-4974-acf7-e2fa46e1ae0f","name":"escapeCssQuotedValue","imports":"","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeCssQuotedValue.ts","code":"(val: string) => val.replace('\"', '%22').replace(\"'\", '%27')","parent":"{}"} {"element_type":"file","project_name":"tsgitlabtest","uuid":"d9922d2c-ce77-46b3-a7df-6c5715216b88","name":"escapeHtml.test.ts","imports":"[{'import_name': ['escapeHtml'], 'import_path': '.\/escapeHtml'}]","file_location":"https:\/\/github.com\/tsgitlabtest\/\/tmp\/repos\/gitlab-web-ide\/packages\/utils-escape\/src\/escapeHtml.test.ts","code":"import { escapeHtml } from '.\/escapeHtml';\n\ndescribe('utils\/escape\/escapeHtml', () => {\n it('escapes common HTML control characters', () => {\n expect(escapeHtml(`