@pikku/core 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/channel/channel-runner.js +1 -1
  3. package/dist/channel/serverless/serverless-channel-runner.js +1 -1
  4. package/dist/function/function-runner.js +7 -5
  5. package/dist/http/http-runner.js +4 -2
  6. package/dist/http/log-http-routes.js +1 -1
  7. package/lcov.info +4596 -0
  8. package/package.json +1 -1
  9. package/src/channel/channel-handler.ts +165 -0
  10. package/src/channel/channel-runner.ts +153 -0
  11. package/src/channel/channel-store.ts +29 -0
  12. package/src/channel/channel.types.ts +133 -0
  13. package/src/channel/eventhub-service.ts +30 -0
  14. package/src/channel/eventhub-store.ts +8 -0
  15. package/src/channel/index.ts +8 -0
  16. package/src/channel/local/index.ts +3 -0
  17. package/src/channel/local/local-channel-handler.ts +50 -0
  18. package/src/channel/local/local-channel-runner.test.ts +157 -0
  19. package/src/channel/local/local-channel-runner.ts +139 -0
  20. package/src/channel/local/local-eventhub-service.test.ts +95 -0
  21. package/src/channel/local/local-eventhub-service.ts +95 -0
  22. package/src/channel/log-channels.ts +20 -0
  23. package/src/channel/pikku-abstract-channel-handler.test.ts +52 -0
  24. package/src/channel/pikku-abstract-channel-handler.ts +38 -0
  25. package/src/channel/serverless/index.ts +1 -0
  26. package/src/channel/serverless/serverless-channel-runner.ts +220 -0
  27. package/src/errors/error-handler.ts +61 -0
  28. package/src/errors/error.test.ts +54 -0
  29. package/src/errors/errors.ts +339 -0
  30. package/src/errors/index.ts +2 -0
  31. package/src/function/function-runner.ts +92 -0
  32. package/src/function/functions.types.ts +77 -0
  33. package/src/function/index.ts +2 -0
  34. package/src/handle-error.ts +73 -0
  35. package/src/http/http-runner.test.ts +140 -0
  36. package/src/http/http-runner.ts +493 -0
  37. package/src/http/http.types.ts +250 -0
  38. package/src/http/incomingmessage-to-request-convertor.ts +0 -0
  39. package/src/http/index.ts +8 -0
  40. package/src/http/log-http-routes.ts +22 -0
  41. package/src/http/pikku-fetch-http-request.test.ts +237 -0
  42. package/src/http/pikku-fetch-http-request.ts +163 -0
  43. package/src/http/pikku-fetch-http-response.test.ts +82 -0
  44. package/src/http/pikku-fetch-http-response.ts +138 -0
  45. package/src/index.ts +20 -0
  46. package/src/middleware/auth-apikey.ts +66 -0
  47. package/src/middleware/auth-bearer.ts +66 -0
  48. package/src/middleware/auth-cookie.ts +103 -0
  49. package/src/middleware/index.ts +3 -0
  50. package/src/middleware/timeout.ts +13 -0
  51. package/src/middleware-runner.ts +43 -0
  52. package/src/permissions.test.ts +58 -0
  53. package/src/permissions.ts +43 -0
  54. package/src/pikku-function.ts +1 -0
  55. package/src/pikku-request.ts +23 -0
  56. package/src/pikku-response.ts +5 -0
  57. package/src/pikku-state.ts +87 -0
  58. package/src/scheduler/index.ts +5 -0
  59. package/src/scheduler/log-schedulers.ts +20 -0
  60. package/src/scheduler/scheduler-runner.ts +105 -0
  61. package/src/scheduler/scheduler.types.ts +33 -0
  62. package/src/schema.test.ts +57 -0
  63. package/src/schema.ts +99 -0
  64. package/src/services/content-service.ts +68 -0
  65. package/src/services/index.ts +18 -0
  66. package/src/services/jwt-service.ts +30 -0
  67. package/src/services/local-content.ts +105 -0
  68. package/src/services/local-secrets.ts +43 -0
  69. package/src/services/local-variables.ts +17 -0
  70. package/src/services/logger-console.ts +97 -0
  71. package/src/services/logger.ts +57 -0
  72. package/src/services/schema-service.ts +26 -0
  73. package/src/services/secret-service.ts +17 -0
  74. package/src/services/user-session-service.ts +53 -0
  75. package/src/services/variables-service.ts +6 -0
  76. package/src/time-utils.test.ts +56 -0
  77. package/src/time-utils.ts +32 -0
  78. package/src/types/core.types.ts +178 -0
  79. package/src/utils.ts +40 -0
  80. package/tsconfig.json +13 -0
  81. package/tsconfig.tsbuildinfo +1 -0
  82. package/dist/http/http-route-runner.d.ts +0 -90
  83. package/dist/http/http-route-runner.js +0 -325
  84. package/dist/http/http-routes.types.d.ts +0 -179
  85. package/dist/http/http-routes.types.js +0 -1
  86. package/dist/http/pikku-http-request.d.ts +0 -56
  87. package/dist/http/pikku-http-request.js +0 -95
  88. package/dist/http/pikku-http-response.d.ts +0 -13
  89. package/dist/http/pikku-http-response.js +0 -60
  90. package/dist/parse-relative-time-offset.d.ts +0 -12
  91. package/dist/parse-relative-time-offset.js +0 -20
  92. package/dist/pikku-func.d.ts +0 -12
  93. package/dist/pikku-func.js +0 -39
  94. package/dist/types/functions.types.d.ts +0 -37
  95. package/dist/types/functions.types.js +0 -1
@@ -0,0 +1,157 @@
1
+ import { test, beforeEach, afterEach } from 'node:test'
2
+ import * as assert from 'node:assert/strict'
3
+ import { runLocalChannel } from './local-channel-runner.js'
4
+ import { pikkuState, resetPikkuState } from '../../pikku-state.js'
5
+ import { addChannel } from '../channel-runner.js'
6
+ import {
7
+ HTTPMethod,
8
+ PikkuHTTPRequest,
9
+ PikkuHTTPResponse,
10
+ PikkuQuery,
11
+ } from '../../http/http.types.js'
12
+ import { SerializeOptions } from 'cookie'
13
+
14
+ /**
15
+ * Minimal stubs for dependencies that runChannel expects.
16
+ * In a real test setup, you may provide more comprehensive mocks
17
+ * or refactor your code to allow dependency injection.
18
+ */
19
+ const mockLogger = {
20
+ info: () => {},
21
+ error: () => {},
22
+ warn: () => {},
23
+ debug: () => {},
24
+ }
25
+
26
+ const mockSingletonServices = {
27
+ logger: mockLogger,
28
+ } as any
29
+
30
+ // Mock request and response objects
31
+ export class PikkuMockRequest implements PikkuHTTPRequest {
32
+ private _params: Record<string, string | string[] | undefined> = {}
33
+
34
+ constructor(
35
+ private _route: string,
36
+ private _method: HTTPMethod
37
+ ) {}
38
+
39
+ method(): HTTPMethod {
40
+ return this._method
41
+ }
42
+ path(): string {
43
+ return this._route
44
+ }
45
+ json(): Promise<unknown> {
46
+ throw new Error('Method not implemented.')
47
+ }
48
+ arrayBuffer(): Promise<ArrayBuffer> {
49
+ throw new Error('Method not implemented.')
50
+ }
51
+ header(headerName: string): string | null {
52
+ throw new Error('Method not implemented.')
53
+ }
54
+ cookie(name?: string): string | null {
55
+ throw new Error('Method not implemented.')
56
+ }
57
+ params(): Partial<Record<string, string | string[]>> {
58
+ return this._params
59
+ }
60
+ setParams(params: Record<string, string | string[] | undefined>): void {
61
+ this._params = params
62
+ }
63
+ query(): PikkuQuery {
64
+ throw new Error('Method not implemented.')
65
+ }
66
+ public async data() {
67
+ return { test: 'data' }
68
+ }
69
+ }
70
+
71
+ export class PikkuMockResponse implements PikkuHTTPResponse {
72
+ public _status: number | undefined
73
+
74
+ status(code: number): this {
75
+ this._status = code
76
+ return this
77
+ }
78
+
79
+ cookie(name: string, value: string | null, options: SerializeOptions): this {
80
+ throw new Error('Method not implemented.')
81
+ }
82
+ header(name: string, value: string | string[]): this {
83
+ throw new Error('Method not implemented.')
84
+ }
85
+ arrayBuffer(data: XMLHttpRequestBodyInit): this {
86
+ throw new Error('Method not implemented.')
87
+ }
88
+ json(data: unknown): this {
89
+ // We don't need to implement this for our test
90
+ return this
91
+ }
92
+ redirect(location: string, status?: number): this {
93
+ throw new Error('Method not implemented.')
94
+ }
95
+ }
96
+
97
+ const mockCreateSessionServices = async () => ({ sessionServiceMock: true })
98
+
99
+ beforeEach(() => {
100
+ resetPikkuState()
101
+ })
102
+
103
+ afterEach(() => {
104
+ resetPikkuState()
105
+ })
106
+
107
+ test('runChannel should return undefined and 404 if no matching channel is found', async () => {
108
+ const mockResponse = new PikkuMockResponse()
109
+
110
+ const result = await runLocalChannel({
111
+ singletonServices: mockSingletonServices,
112
+ channelId: 'test-channel-id',
113
+ request: new PikkuMockRequest('/non-existent-channel', 'get'),
114
+ response: mockResponse,
115
+ createSessionServices: mockCreateSessionServices,
116
+ })
117
+
118
+ assert.equal(
119
+ result,
120
+ undefined,
121
+ 'Should return undefined if no channel matches'
122
+ )
123
+ assert.equal(mockResponse._status, 404, 'Should set response status to 404')
124
+ // assert.equal(mockResponse._ended, true, 'Should end the response')
125
+ })
126
+
127
+ test('runChannel should return a channel handler if channel matches and no auth required', async () => {
128
+ resetPikkuState()
129
+
130
+ pikkuState('channel', 'meta', {
131
+ test: {
132
+ name: 'test',
133
+ route: '/test-channel',
134
+ },
135
+ } as any)
136
+ addChannel({
137
+ name: 'test',
138
+ route: '/test-channel',
139
+ auth: false,
140
+ })
141
+
142
+ const result = await runLocalChannel({
143
+ singletonServices: mockSingletonServices,
144
+ channelId: 'test-channel-id',
145
+ request: new PikkuMockRequest('/test-channel', 'get'),
146
+ response: new PikkuMockResponse(),
147
+ route: '/test-channel',
148
+ createSessionServices: mockCreateSessionServices,
149
+ })
150
+
151
+ assert.ok(result, 'Should return a PikkuChannelHandler instance')
152
+
153
+ // Simulate opening the channel
154
+ result.open()
155
+
156
+ // TODO: Test that the opened channel works
157
+ })
@@ -0,0 +1,139 @@
1
+ import { openChannel } from '../channel-runner.js'
2
+ import { createHTTPInteraction } from '../../http/http-runner.js'
3
+ import { closeSessionServices } from '../../utils.js'
4
+ import { processMessageHandlers } from '../channel-handler.js'
5
+ import {
6
+ CoreAPIChannel,
7
+ RunChannelOptions,
8
+ RunChannelParams,
9
+ } from '../channel.types.js'
10
+ import { PikkuLocalChannelHandler } from './local-channel-handler.js'
11
+ import { SessionServices } from '../../types/core.types.js'
12
+ import { handleError } from '../../handle-error.js'
13
+ import { runMiddleware } from '../../middleware-runner.js'
14
+ import { PikkuUserSessionService } from '../../services/user-session-service.js'
15
+ import { PikkuHTTP } from '../../http/http.types.js'
16
+ import { runPikkuFuncDirectly } from '../../function/function-runner.js'
17
+
18
+ export const runLocalChannel = async ({
19
+ singletonServices,
20
+ channelId,
21
+ request,
22
+ response,
23
+ route,
24
+ createSessionServices,
25
+ skipUserSession = false,
26
+ respondWith404 = true,
27
+ coerceDataFromSchema = true,
28
+ logWarningsForStatusCodes = [],
29
+ bubbleErrors = false,
30
+ }: Partial<Pick<CoreAPIChannel<unknown, any>, 'route'>> &
31
+ RunChannelOptions &
32
+ RunChannelParams<unknown>): Promise<PikkuLocalChannelHandler | void> => {
33
+ let sessionServices: SessionServices<typeof singletonServices> | undefined
34
+
35
+ let channelHandler: PikkuLocalChannelHandler | undefined
36
+ const userSession = new PikkuUserSessionService()
37
+
38
+ let http: PikkuHTTP | undefined
39
+ if (request) {
40
+ http = createHTTPInteraction(request, response)
41
+ route = http?.request?.path()
42
+ }
43
+
44
+ const main = async () => {
45
+ try {
46
+ const { openingData, channelConfig, meta } = await openChannel({
47
+ channelId,
48
+ createSessionServices,
49
+ respondWith404,
50
+ request,
51
+ response,
52
+ route,
53
+ singletonServices,
54
+ skipUserSession,
55
+ coerceDataFromSchema,
56
+ userSession,
57
+ })
58
+
59
+ channelHandler = new PikkuLocalChannelHandler(
60
+ channelId,
61
+ channelConfig.name,
62
+ openingData
63
+ )
64
+ const channel = channelHandler.getChannel()
65
+ const session = await userSession.get()
66
+ if (createSessionServices) {
67
+ sessionServices = await createSessionServices(
68
+ singletonServices,
69
+ { http },
70
+ session
71
+ )
72
+ }
73
+
74
+ const allServices = {
75
+ ...singletonServices,
76
+ ...sessionServices,
77
+ userSession: userSession,
78
+ }
79
+
80
+ channelHandler.registerOnOpen(() => {
81
+ if (channelConfig.onConnect && meta.connectPikkuFuncName) {
82
+ runPikkuFuncDirectly(
83
+ meta.connectPikkuFuncName,
84
+ { ...allServices, channel },
85
+ openingData
86
+ )
87
+ }
88
+ })
89
+
90
+ channelHandler.registerOnClose(async () => {
91
+ if (channelConfig.onDisconnect && meta.disconnectPikkuFuncName) {
92
+ runPikkuFuncDirectly(
93
+ meta.disconnectPikkuFuncName,
94
+ { ...allServices, channel },
95
+ openingData
96
+ )
97
+ }
98
+ if (sessionServices) {
99
+ await closeSessionServices(singletonServices.logger, sessionServices)
100
+ }
101
+ })
102
+
103
+ channelHandler.registerOnMessage(
104
+ processMessageHandlers(
105
+ allServices,
106
+ session,
107
+ channelConfig as any,
108
+ channelHandler
109
+ )
110
+ )
111
+ } catch (e: any) {
112
+ handleError(
113
+ e,
114
+ http,
115
+ channelId,
116
+ singletonServices.logger,
117
+ logWarningsForStatusCodes,
118
+ respondWith404,
119
+ bubbleErrors
120
+ )
121
+ } finally {
122
+ if (sessionServices) {
123
+ await closeSessionServices(singletonServices.logger, sessionServices)
124
+ }
125
+ }
126
+ }
127
+
128
+ await runMiddleware(
129
+ {
130
+ ...singletonServices,
131
+ userSession,
132
+ },
133
+ { http },
134
+ route.middleware || [],
135
+ main
136
+ )
137
+
138
+ return channelHandler
139
+ }
@@ -0,0 +1,95 @@
1
+ import * as assert from 'assert'
2
+ import { test } from 'node:test'
3
+ import { PikkuChannelHandler } from '../channel.types.js'
4
+ import { CoreUserSession } from '../../types/core.types.js'
5
+ import { LocalEventHubService } from './local-eventhub-service.js'
6
+
7
+ class MockChannelHandler implements PikkuChannelHandler {
8
+ private channelId: string
9
+
10
+ constructor(channelId: string) {
11
+ this.channelId = channelId
12
+ }
13
+
14
+ setUserSession(session: CoreUserSession): Promise<void> | void {
15
+ throw new Error('Method not needed.')
16
+ }
17
+
18
+ getChannel() {
19
+ return { channelId: this.channelId } as any
20
+ }
21
+
22
+ send(data: unknown, isBinary?: boolean) {
23
+ // Mock send functionality
24
+ console.log(`Sent to ${this.channelId}:`, { data, isBinary })
25
+ }
26
+ }
27
+
28
+ test('LocalEventHubService: subscribe and unsubscribe', () => {
29
+ const eventHub = new LocalEventHubService()
30
+
31
+ // Subscribe a channel to a topic
32
+ eventHub.subscribe('topic1', 'channel1')
33
+ assert.strictEqual(eventHub['subscriptions'].get('topic1')!.size, 1)
34
+
35
+ // Unsubscribe the channel
36
+ eventHub.unsubscribe('topic1', 'channel1')
37
+ assert.strictEqual(eventHub['subscriptions'].has('topic1'), false)
38
+ })
39
+
40
+ test('LocalEventHubService: publish messages', () => {
41
+ const eventHub = new LocalEventHubService()
42
+
43
+ // Register mock channels
44
+ const channel1 = new MockChannelHandler('channel1')
45
+ const channel2 = new MockChannelHandler('channel2')
46
+ eventHub.onChannelOpened(channel1)
47
+ eventHub.onChannelOpened(channel2)
48
+
49
+ // Subscribe channels to a topic
50
+ eventHub.subscribe('topic1', 'channel1')
51
+ eventHub.subscribe('topic1', 'channel2')
52
+
53
+ // Mock `send` method to track calls
54
+ let sendCallCount = 0
55
+ channel1.send = () => {
56
+ sendCallCount++
57
+ }
58
+ channel2.send = () => {
59
+ sendCallCount++
60
+ }
61
+
62
+ // Publish a message
63
+ eventHub.publish('topic1', 'channel1', { message: 'Hello!' })
64
+
65
+ // Ensure the message was sent only to channel2
66
+ assert.strictEqual(sendCallCount, 1)
67
+ })
68
+
69
+ test('LocalEventHubService: onChannelOpened and onChannelClosed', () => {
70
+ const eventHub = new LocalEventHubService()
71
+
72
+ // Register and verify channel
73
+ const channel1 = new MockChannelHandler('channel1')
74
+ eventHub.onChannelOpened(channel1)
75
+ assert.strictEqual(eventHub['channels'].has('channel1'), true)
76
+
77
+ // Close and verify removal
78
+ eventHub.onChannelClosed('channel1')
79
+ assert.strictEqual(eventHub['channels'].has('channel1'), false)
80
+ })
81
+
82
+ test('LocalEventHubService: clean up empty topics on channel close', () => {
83
+ const eventHub = new LocalEventHubService()
84
+
85
+ // Register and subscribe channels
86
+ const channel1 = new MockChannelHandler('channel1')
87
+ eventHub.onChannelOpened(channel1)
88
+ eventHub.subscribe('topic1', 'channel1')
89
+
90
+ // Close channel
91
+ eventHub.onChannelClosed('channel1')
92
+
93
+ // Ensure topic1 is removed
94
+ assert.strictEqual(eventHub['subscriptions'].has('topic1'), false)
95
+ })
@@ -0,0 +1,95 @@
1
+ import { PikkuChannelHandler } from '../channel.types.js'
2
+ import { EventHubService } from '../eventhub-service.js'
3
+
4
+ /**
5
+ * Implementation of the SubscriptionService interface.
6
+ * Manages subscriptions and publishes messages to subscribers.
7
+ */
8
+ export class LocalEventHubService<Data = unknown>
9
+ implements EventHubService<Data>
10
+ {
11
+ private channels = new Map<string, PikkuChannelHandler>()
12
+
13
+ /**
14
+ * A map storing topics and their associated connection IDs.
15
+ */
16
+ private subscriptions: Map<string, Set<string>> = new Map()
17
+
18
+ /**
19
+ * Subscribes a connection to a specific topic.
20
+ * Creates the topic if it does not already exist.
21
+ * @param topic - The topic to subscribe to.
22
+ * @param channelId - The unique ID of the connection to subscribe.
23
+ */
24
+ public subscribe(topic: string, channelId: string): void {
25
+ if (!this.subscriptions.has(topic)) {
26
+ this.subscriptions.set(topic, new Set())
27
+ }
28
+ this.subscriptions.get(topic)!.add(channelId)
29
+ }
30
+
31
+ /**
32
+ * Unsubscribes a connection from a specific topic.
33
+ * Removes the topic if it has no more subscribers.
34
+ * @param topic - The topic to unsubscribe from.
35
+ * @param channelId - The unique ID of the connection to unsubscribe.
36
+ */
37
+ public unsubscribe(topic: string, channelId: string): void {
38
+ const topicSubscriptions = this.subscriptions.get(topic)
39
+ if (topicSubscriptions) {
40
+ topicSubscriptions.delete(channelId)
41
+ if (topicSubscriptions.size === 0) {
42
+ this.subscriptions.delete(topic) // Cleanup empty subscriptions
43
+ }
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Sends data to all connections subscribed to a topic.
49
+ * @param topic - The topic to send data to.
50
+ * @param data - The data to send to the subscribers.
51
+ */
52
+ public publish(
53
+ topic: string,
54
+ channelId: string,
55
+ data: Data,
56
+ isBinary?: boolean
57
+ ): void {
58
+ const subscribedChannelIds = this.subscriptions.get(topic)
59
+ if (!subscribedChannelIds) {
60
+ return
61
+ }
62
+ for (const toChannelId of subscribedChannelIds) {
63
+ if (channelId === toChannelId) continue // Skip sending to the sender
64
+ const channel = this.channels.get(toChannelId)
65
+ if (channel) {
66
+ channel.send(data, isBinary)
67
+ } else {
68
+ // TODO: Websocket is closed, remove the channel from the topic
69
+ }
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Registers a channel on open
75
+ */
76
+ public onChannelOpened(channelHandler: PikkuChannelHandler): void {
77
+ this.channels.set(channelHandler.getChannel().channelId, channelHandler)
78
+ }
79
+
80
+ /**
81
+ * Handles cleanup when a channel is closed.
82
+ * Removes the channel from all topics it is subscribed to.
83
+ * Deletes the topic if no more channels are subscribed to it.
84
+ * @param channelId - The ID of the channel that was closed.
85
+ */
86
+ public onChannelClosed(channelId: string): void {
87
+ for (const [topic, channelIds] of this.subscriptions.entries()) {
88
+ channelIds.delete(channelId)
89
+ if (channelIds.size === 0) {
90
+ this.subscriptions.delete(topic) // Cleanup empty topics
91
+ }
92
+ }
93
+ this.channels.delete(channelId)
94
+ }
95
+ }
@@ -0,0 +1,20 @@
1
+ import { pikkuState } from '../pikku-state.js'
2
+ import { Logger } from '../services/index.js'
3
+
4
+ /**
5
+ * Logs all the loaded channels.
6
+ * @param logger - A logger for logging information.
7
+ */
8
+ export const logChannels = (logger: Logger) => {
9
+ const channels = pikkuState('channel', 'channels')
10
+ if (channels.size === 0) {
11
+ logger.info('No channels added')
12
+ return
13
+ }
14
+
15
+ let scheduledChannels = 'Channels:'
16
+ channels.forEach((channel) => {
17
+ scheduledChannels += `\n\t- ${channel.name} at ${channel.route}`
18
+ })
19
+ logger.info(scheduledChannels)
20
+ }
@@ -0,0 +1,52 @@
1
+ import { test, beforeEach } from 'node:test'
2
+ import * as assert from 'node:assert/strict'
3
+ import { PikkuAbstractChannelHandler } from './pikku-abstract-channel-handler.js'
4
+
5
+ // A concrete implementation of the abstract class for testing
6
+ class TestChannelHandler extends PikkuAbstractChannelHandler<
7
+ { param: string },
8
+ { msg: string }
9
+ > {
10
+ public async send(message: { msg: string }, isBinary = false): Promise<void> {
11
+ // Mock send implementation
12
+ }
13
+ }
14
+
15
+ let handler: TestChannelHandler
16
+
17
+ beforeEach(() => {
18
+ handler = new TestChannelHandler('test-channel-id', 'channel-name', {
19
+ param: 'testParam',
20
+ })
21
+ })
22
+
23
+ test('getChannel should return a channel with initial state', () => {
24
+ const channel = handler.getChannel()
25
+ assert.equal(channel.channelId, 'test-channel-id', 'Channel ID should match')
26
+ assert.equal(channel.state, 'initial', 'Initial state should be "initial"')
27
+ assert.deepEqual(
28
+ channel.openingData,
29
+ { param: 'testParam' },
30
+ 'Opening data should be accessible'
31
+ )
32
+ })
33
+
34
+ test('open should change channel state to open', () => {
35
+ handler.open()
36
+ const channel = handler.getChannel()
37
+ assert.equal(
38
+ channel.state,
39
+ 'open',
40
+ 'State should be "open" after calling open()'
41
+ )
42
+ })
43
+
44
+ test('close should change channel state to closed', () => {
45
+ handler.close()
46
+ const channel = handler.getChannel()
47
+ assert.equal(
48
+ channel.state,
49
+ 'closed',
50
+ 'State should be "closed" after calling close()'
51
+ )
52
+ })
@@ -0,0 +1,38 @@
1
+ import { PikkuChannel, PikkuChannelHandler } from './channel.types.js'
2
+
3
+ export abstract class PikkuAbstractChannelHandler<
4
+ OpeningData = unknown,
5
+ Out = unknown,
6
+ > implements PikkuChannelHandler<OpeningData, Out>
7
+ {
8
+ protected channel?: PikkuChannel<OpeningData, Out>
9
+
10
+ constructor(
11
+ public channelId: string,
12
+ public channelName: string,
13
+ protected openingData: OpeningData
14
+ ) {}
15
+
16
+ public abstract send(message: Out, isBinary?: boolean): Promise<void> | void
17
+
18
+ public getChannel(): PikkuChannel<OpeningData, Out> {
19
+ if (!this.channel) {
20
+ this.channel = {
21
+ channelId: this.channelId,
22
+ openingData: this.openingData,
23
+ send: this.send.bind(this),
24
+ close: this.close.bind(this),
25
+ state: 'initial',
26
+ }
27
+ }
28
+ return this.channel
29
+ }
30
+
31
+ public open(): void {
32
+ this.getChannel().state = 'open'
33
+ }
34
+
35
+ public close(): Promise<void> | void {
36
+ this.getChannel().state = 'closed'
37
+ }
38
+ }
@@ -0,0 +1 @@
1
+ export * from './serverless-channel-runner.js'