@tylix/client 0.0.0-stage → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mbiyrukzz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,65 @@
1
- # Temporary Holding Version
1
+ # @tylix/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The browser side of a Tylix app, with no framework dependency: API
4
+ requests, the logged-in session, and live channels. `@tylix/react`,
5
+ `@tylix/vue`, `@tylix/svelte` and `@tylix/angular` are built on it, so
6
+ every frontend behaves the same.
7
+
8
+ ```sh
9
+ npm install @tylix/client
10
+ ```
11
+
12
+ ## API requests
13
+
14
+ ```js
15
+ import { api } from '@tylix/client'
16
+
17
+ const posts = await api('/api/posts')
18
+ if (posts.ok) console.log(posts.data)
19
+
20
+ const saved = await api.post('/api/posts', { title: 'Hello' })
21
+ if (!saved.ok) console.log(saved.status, saved.error, saved.errors)
22
+ ```
23
+
24
+ Every call resolves to `{ ok, status, data, error, errors }` and never
25
+ throws for HTTP errors. Session cookies are sent automatically. When the
26
+ access token has expired, the client renews the session once (shared by
27
+ all requests in flight) and retries.
28
+
29
+ ## The session
30
+
31
+ ```js
32
+ import { auth } from '@tylix/client'
33
+
34
+ await auth.init()
35
+ auth.subscribe((state) => console.log(state.status, state.user))
36
+
37
+ await auth.login(email, password)
38
+ await auth.register({ name, email, password })
39
+ await auth.logout()
40
+ await auth.forgotPassword(email)
41
+ await auth.resetPassword({ email, token, password })
42
+ ```
43
+
44
+ `state.status` is `loading`, `authenticated` or `guest`. Logging in or out
45
+ in one tab updates every other tab.
46
+
47
+ ## Channels
48
+
49
+ Live messages from `tylix channels:work`:
50
+
51
+ ```js
52
+ import { channel } from '@tylix/client'
53
+
54
+ const chat = channel('chat')
55
+ chat.onMessage((message) => console.log(message))
56
+ chat.send({ text: 'hi' })
57
+ chat.close()
58
+ ```
59
+
60
+ The channel reconnects on its own and queues messages sent while it is
61
+ connecting. During server rendering it does nothing.
62
+
63
+ ## License
64
+
65
+ MIT
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@tylix/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Browser client for Tylix apps: API requests and the auth session, with no framework dependency.",
5
+ "license": "MIT",
6
+ "author": "Mbiyrukzz",
7
+ "type": "module",
8
+ "keywords": [
9
+ "tylix",
10
+ "client",
11
+ "auth",
12
+ "fetch",
13
+ "websocket"
14
+ ],
15
+ "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/client#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Mbiyrukzz/tylix.git",
19
+ "directory": "packages/client"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/Mbiyrukzz/tylix/issues"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.13"
26
+ },
27
+ "sideEffects": false,
28
+ "main": "./src/index.js",
29
+ "types": "./src/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./src/index.d.ts",
33
+ "default": "./src/index.js"
34
+ }
35
+ },
36
+ "files": [
37
+ "src",
38
+ "!**/*.test.js",
39
+ "!**/*.test.mjs",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test src/*.test.js"
48
+ }
49
+ }
package/src/channel.js ADDED
@@ -0,0 +1,163 @@
1
+ // Live channels: a WebSocket to the channel server ("tylix channels:work")
2
+ // for one channel, e.g. "chat". Messages are JSON both ways.
3
+ //
4
+ // const chat = channel('chat')
5
+ // const stop = chat.onMessage((data) => console.log(data))
6
+ // chat.send({ text: 'hi' })
7
+ // chat.close()
8
+ //
9
+ // It reconnects on its own (0.5s, 1s, 2s … up to 10s apart) when the
10
+ // connection drops, and keeps messages sent while connecting until the
11
+ // socket opens. Where there is no WebSocket (server rendering) it does
12
+ // nothing, so pages can create channels unconditionally.
13
+
14
+ const MAX_QUEUE = 100
15
+ const MAX_DELAY_MS = 10_000
16
+
17
+ function channelUrl(name, { port, url }) {
18
+ if (url) return url
19
+ const location = globalThis.location
20
+ const scheme = location?.protocol === 'https:' ? 'wss' : 'ws'
21
+ const host = location?.hostname ?? 'localhost'
22
+ // The Tylix server puts CHANNELS_PORT in the page; 6001 is its default.
23
+ const finalPort = port ?? globalThis.__TYLIX_CHANNELS_PORT__ ?? 6001
24
+ return `${scheme}://${host}:${finalPort}/${encodeURIComponent(name)}`
25
+ }
26
+
27
+ export function channel(name, options = {}) {
28
+ if (typeof name !== 'string' || name === '') throw new TypeError('channel(name) needs a channel name.')
29
+ const { reconnect = true } = options
30
+ // An explicit WebSocket option wins, even undefined (no sockets here).
31
+ const WebSocketImpl = Object.hasOwn(options, 'WebSocket') ? options.WebSocket : globalThis.WebSocket
32
+
33
+ const messageListeners = new Set()
34
+ const statusListeners = new Set()
35
+ const queue = []
36
+ let socket = null
37
+ let status = 'connecting'
38
+ let closedByUs = false
39
+ let attempt = 0
40
+ let retryTimer = null
41
+
42
+ const setStatus = (next) => {
43
+ if (next === status) return
44
+ status = next
45
+ for (const fn of [...statusListeners]) fn(status)
46
+ }
47
+
48
+ if (typeof WebSocketImpl !== 'function') {
49
+ // Server rendering or a very old browser: an inert channel.
50
+ status = 'closed'
51
+ return {
52
+ send() {},
53
+ onMessage: () => () => {},
54
+ onStatus: () => () => {},
55
+ get status() {
56
+ return 'closed'
57
+ },
58
+ close() {},
59
+ }
60
+ }
61
+
62
+ function connect() {
63
+ setStatus('connecting')
64
+ try {
65
+ socket = new WebSocketImpl(channelUrl(name, options))
66
+ } catch (err) {
67
+ console.error(`[tylix] channel("${name}") could not connect:`, err)
68
+ scheduleRetry()
69
+ return
70
+ }
71
+ socket.addEventListener('open', () => {
72
+ attempt = 0
73
+ setStatus('open')
74
+ while (queue.length && socket.readyState === 1) socket.send(queue.shift())
75
+ })
76
+ socket.addEventListener('message', (event) => {
77
+ let data
78
+ try {
79
+ data = JSON.parse(event.data)
80
+ } catch {
81
+ return // not JSON: not for us
82
+ }
83
+ for (const fn of [...messageListeners]) fn(data)
84
+ })
85
+ socket.addEventListener('close', () => {
86
+ socket = null
87
+ if (closedByUs) {
88
+ setStatus('closed')
89
+ return
90
+ }
91
+ scheduleRetry()
92
+ })
93
+ }
94
+
95
+ function scheduleRetry() {
96
+ if (closedByUs || !reconnect) {
97
+ setStatus('closed')
98
+ return
99
+ }
100
+ setStatus('reconnecting')
101
+ const delay = Math.min(500 * 2 ** attempt, MAX_DELAY_MS)
102
+ attempt++
103
+ retryTimer = setTimeout(connect, delay)
104
+ }
105
+
106
+ connect()
107
+
108
+ return {
109
+ send(data) {
110
+ const message = JSON.stringify(data)
111
+ if (socket && socket.readyState === 1) socket.send(message)
112
+ else if (!closedByUs) {
113
+ queue.push(message)
114
+ if (queue.length > MAX_QUEUE) queue.shift() // keep the newest
115
+ }
116
+ },
117
+ // Returns a function that removes the listener.
118
+ onMessage(fn) {
119
+ messageListeners.add(fn)
120
+ return () => messageListeners.delete(fn)
121
+ },
122
+ onStatus(fn) {
123
+ statusListeners.add(fn)
124
+ return () => statusListeners.delete(fn)
125
+ },
126
+ get status() {
127
+ return status
128
+ },
129
+ close() {
130
+ closedByUs = true
131
+ clearTimeout(retryTimer)
132
+ queue.length = 0
133
+ if (socket) socket.close()
134
+ else setStatus('closed')
135
+ },
136
+ }
137
+ }
138
+
139
+ // A channel opened later, for framework bindings: components create it
140
+ // while rendering (on the server too), open() it once mounted in the
141
+ // browser and close() it when unmounted. send() before open() is queued.
142
+ export function lazyChannel(name, { onMessage, onStatus } = {}) {
143
+ let live = null
144
+ const pending = []
145
+ return {
146
+ open() {
147
+ if (live) return
148
+ live = channel(name)
149
+ live.onMessage((data) => onMessage?.(data))
150
+ live.onStatus((status) => onStatus?.(status))
151
+ onStatus?.(live.status)
152
+ for (const data of pending.splice(0)) live.send(data)
153
+ },
154
+ close() {
155
+ live?.close()
156
+ live = null
157
+ },
158
+ send(data) {
159
+ if (live) live.send(data)
160
+ else pending.push(data)
161
+ },
162
+ }
163
+ }
@@ -0,0 +1,219 @@
1
+ // The request function every frontend uses to talk to the Tylix backend.
2
+ //
3
+ // It returns the same result shape as the native useApi:
4
+ // { ok, status, data, error, errors }
5
+ // and never throws for HTTP or network failures, so UI code can branch on
6
+ // `result.ok` instead of wrapping every call in try/catch.
7
+ //
8
+ // Sessions live in httpOnly cookies that JavaScript can't read, so every
9
+ // request is sent with credentials. When a request comes back 401, the
10
+ // access token has probably expired: the client calls /api/auth/refresh
11
+ // once and replays the request. Concurrent 401s share that single refresh.
12
+
13
+ // Endpoints whose 401 means "wrong credentials" or "no session to refresh",
14
+ // never "access token expired". Refreshing on these would loop.
15
+ const AUTH_PATHS = new Set([
16
+ '/api/login',
17
+ '/api/register',
18
+ '/api/auth/refresh',
19
+ '/api/auth/logout',
20
+ ])
21
+
22
+ const REFRESH_PATH = '/api/auth/refresh'
23
+
24
+ function pathnameOf(url) {
25
+ try {
26
+ return new URL(url, 'http://tylix.local').pathname
27
+ } catch {
28
+ return String(url).split('?')[0]
29
+ }
30
+ }
31
+
32
+ function isNativeBody(body) {
33
+ return (
34
+ (typeof FormData !== 'undefined' && body instanceof FormData) ||
35
+ (typeof Blob !== 'undefined' && body instanceof Blob) ||
36
+ (typeof URLSearchParams !== 'undefined' &&
37
+ body instanceof URLSearchParams) ||
38
+ body instanceof ArrayBuffer ||
39
+ ArrayBuffer.isView(body) ||
40
+ (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
41
+ )
42
+ }
43
+
44
+ // A stream can only be read once, so a request with one can't be replayed
45
+ // after a refresh.
46
+ function isReplayable(body) {
47
+ return !(typeof ReadableStream !== 'undefined' && body instanceof ReadableStream)
48
+ }
49
+
50
+ function errorMessage(data, status) {
51
+ if (data && typeof data === 'object') {
52
+ if (typeof data.error === 'string') return data.error
53
+ if (typeof data.message === 'string') return data.message
54
+ // 422 validation errors: { errors: { field: ["message"] } }
55
+ if (data.errors && typeof data.errors === 'object') {
56
+ const first = Object.values(data.errors)[0]
57
+ if (Array.isArray(first) && first.length > 0) return String(first[0])
58
+ }
59
+ }
60
+ return `Request failed (HTTP ${status})`
61
+ }
62
+
63
+ // The result every request resolves to, built from an HTTP status and the
64
+ // parsed JSON body. Exported so server-side rendering can turn in-process
65
+ // responses into exactly what api() returns in the browser.
66
+ export function resultFromResponse(status, data) {
67
+ const ok = status >= 200 && status < 300
68
+ if (ok) return { ok, status, data, error: null, errors: null }
69
+ return {
70
+ ok,
71
+ status,
72
+ data,
73
+ error: errorMessage(data, status),
74
+ errors: data && typeof data === 'object' && data.errors ? data.errors : null,
75
+ }
76
+ }
77
+
78
+ function logDebug(debug, method, url) {
79
+ // Only present when the server runs with APP_DEBUG=true.
80
+ try {
81
+ console.groupCollapsed(`[tylix] ${debug.status ?? ''} ${method} ${url}: ${debug.title || debug.message}`)
82
+ if (debug.hint) console.log('How to fix:', debug.hint)
83
+ if (debug.message) console.log('Message:', debug.message)
84
+ if (debug.sql) console.log('SQL:', debug.sql)
85
+ if (debug.source) console.log('Source:', `${debug.source.file}:${debug.source.line}`)
86
+ console.groupEnd()
87
+ } catch {
88
+ // Logging must never break a request.
89
+ }
90
+ }
91
+
92
+ export function createApi({
93
+ baseUrl = '',
94
+ fetch: fetchImpl,
95
+ onSessionExpired = () => {},
96
+ } = {}) {
97
+ let refreshing = null
98
+
99
+ const getFetch = () => {
100
+ const f = fetchImpl ?? globalThis.fetch
101
+ if (typeof f !== 'function') {
102
+ throw new Error('[tylix] fetch is not available in this environment.')
103
+ }
104
+ return f
105
+ }
106
+
107
+ async function send(url, options = {}) {
108
+ const {
109
+ method = 'GET',
110
+ body,
111
+ headers = {},
112
+ credentials = 'include',
113
+ timeout = 0,
114
+ signal,
115
+ } = options
116
+
117
+ const upper = String(method).toUpperCase()
118
+ const finalHeaders = { Accept: 'application/json', ...headers }
119
+ const hasHeader = (name) =>
120
+ Object.keys(finalHeaders).some((k) => k.toLowerCase() === name)
121
+
122
+ let finalBody = body
123
+ if (body !== undefined && body !== null && typeof body === 'object' && !isNativeBody(body)) {
124
+ if (!hasHeader('content-type')) finalHeaders['Content-Type'] = 'application/json'
125
+ finalBody = JSON.stringify(body)
126
+ }
127
+ if ((upper === 'GET' || upper === 'HEAD') && finalBody !== undefined) {
128
+ console.warn(`[tylix] ${upper} ${url}: a ${upper} request cannot have a body, so it was ignored.`)
129
+ finalBody = undefined
130
+ }
131
+
132
+ let controller = null
133
+ let timer = null
134
+ let fetchSignal = signal
135
+ if (timeout > 0) {
136
+ controller = new AbortController()
137
+ timer = setTimeout(() => controller.abort(), timeout)
138
+ if (signal) {
139
+ if (signal.aborted) controller.abort()
140
+ else signal.addEventListener('abort', () => controller.abort(), { once: true })
141
+ }
142
+ fetchSignal = controller.signal
143
+ }
144
+
145
+ try {
146
+ const response = await getFetch()(baseUrl + url, {
147
+ method: upper,
148
+ headers: finalHeaders,
149
+ body: finalBody,
150
+ credentials,
151
+ signal: fetchSignal,
152
+ })
153
+
154
+ let data = null
155
+ try {
156
+ const text = await response.text()
157
+ if (text) data = JSON.parse(text)
158
+ } catch {
159
+ // empty or non-JSON body
160
+ }
161
+
162
+ if (!response.ok) {
163
+ const debug = data && typeof data === 'object' && data.debug ? data.debug : null
164
+ if (debug) logDebug(debug, upper, url)
165
+ }
166
+ return resultFromResponse(response.status, data)
167
+ } catch (err) {
168
+ if (signal?.aborted) {
169
+ return { ok: false, status: 0, data: null, error: 'Request was cancelled', errors: null, aborted: true }
170
+ }
171
+ const timedOut = controller?.signal.aborted
172
+ const message = timedOut ? `Request timed out after ${timeout}ms` : err.message
173
+ console.warn(`[tylix] ${upper} ${url} could not reach the server: ${message}`)
174
+ return { ok: false, status: 0, data: null, error: message, errors: null }
175
+ } finally {
176
+ if (timer) clearTimeout(timer)
177
+ }
178
+ }
179
+
180
+ // One refresh at a time: every request that hits a 401 while a refresh
181
+ // is running waits for that same refresh instead of starting another.
182
+ function refreshSession() {
183
+ if (!refreshing) {
184
+ refreshing = send(REFRESH_PATH, { method: 'POST' })
185
+ .then((result) => result.ok)
186
+ .finally(() => {
187
+ refreshing = null
188
+ })
189
+ }
190
+ return refreshing
191
+ }
192
+
193
+ async function api(url, options = {}) {
194
+ const result = await send(url, options)
195
+
196
+ const canRefresh =
197
+ result.status === 401 &&
198
+ options.refresh !== false &&
199
+ !AUTH_PATHS.has(pathnameOf(url)) &&
200
+ isReplayable(options.body)
201
+
202
+ if (!canRefresh) return result
203
+
204
+ if (await refreshSession()) {
205
+ return send(url, options)
206
+ }
207
+ onSessionExpired()
208
+ return result
209
+ }
210
+
211
+ api.get = (url, options) => api(url, { ...options, method: 'GET' })
212
+ api.post = (url, body, options) => api(url, { ...options, method: 'POST', body })
213
+ api.put = (url, body, options) => api(url, { ...options, method: 'PUT', body })
214
+ api.patch = (url, body, options) => api(url, { ...options, method: 'PATCH', body })
215
+ api.delete = (url, options) => api(url, { ...options, method: 'DELETE' })
216
+ api.refreshSession = refreshSession
217
+
218
+ return api
219
+ }
@@ -0,0 +1,177 @@
1
+ // The auth session store shared by every frontend binding.
2
+ //
3
+ // State is always one of:
4
+ // { status: 'loading', user: null } before the first check
5
+ // { status: 'authenticated', user: {...} }
6
+ // { status: 'guest', user: null, expired? }
7
+ //
8
+ // The state object is replaced (never mutated) on every change, so
9
+ // framework bindings can compare snapshots by reference (React's
10
+ // useSyncExternalStore relies on this).
11
+ //
12
+ // Tokens are httpOnly cookies set by the server. This store never sees or
13
+ // stores them: it only knows who the server says is logged in.
14
+
15
+ const CHANNEL_NAME = 'tylix:auth'
16
+
17
+ export function createAuth({ api, channel } = {}) {
18
+ if (typeof api !== 'function') {
19
+ throw new Error('createAuth needs an api function.')
20
+ }
21
+
22
+ let state = { status: 'loading', user: null }
23
+ const listeners = new Set()
24
+ let initPromise = null
25
+
26
+ // Logging out in one tab logs out the others; logging in makes them
27
+ // re-check the session. Skipped where BroadcastChannel doesn't exist.
28
+ const bus =
29
+ channel !== undefined
30
+ ? channel
31
+ : typeof BroadcastChannel !== 'undefined'
32
+ ? new BroadcastChannel(CHANNEL_NAME)
33
+ : null
34
+
35
+ function setState(next) {
36
+ state = next
37
+ for (const listener of [...listeners]) {
38
+ try {
39
+ listener(state)
40
+ } catch (err) {
41
+ console.error('[tylix] auth listener failed:', err)
42
+ }
43
+ }
44
+ }
45
+
46
+ function authenticated(user) {
47
+ setState({ status: 'authenticated', user })
48
+ }
49
+
50
+ function guest(extra = {}) {
51
+ setState({ status: 'guest', user: null, ...extra })
52
+ }
53
+
54
+ function announce(type) {
55
+ try {
56
+ bus?.postMessage({ type })
57
+ } catch {
58
+ // A closed channel must not break login or logout.
59
+ }
60
+ }
61
+
62
+ // In Node (SSR, tests) an open channel would keep the process alive.
63
+ if (bus && channel === undefined) bus.unref?.()
64
+
65
+ if (bus) {
66
+ bus.onmessage = (event) => {
67
+ const type = event?.data?.type
68
+ if (type === 'logout') guest()
69
+ else if (type === 'login') reload()
70
+ }
71
+ }
72
+
73
+ async function fetchMe() {
74
+ const result = await api('/api/me')
75
+ if (result.ok && result.data) authenticated(result.data)
76
+ else guest()
77
+ return result
78
+ }
79
+
80
+ // Runs the first session check once, however many components ask.
81
+ // The server may have put the session in the page (__TYLIX_SESSION__):
82
+ // { user: {...} } logged in: used as-is, no /api/me round trip
83
+ // { user: null } no valid access token: start as guest right away (so
84
+ // server-rendered guest pages hydrate without a flash),
85
+ // but still check in the background, because a valid
86
+ // refresh token may bring the session back
87
+ // The state is set synchronously, so calling init() before hydrating
88
+ // makes the first client render match the server's.
89
+ function init() {
90
+ if (!initPromise) {
91
+ const injected = globalThis.__TYLIX_SESSION__
92
+ if (injected && injected.user) {
93
+ authenticated(injected.user)
94
+ initPromise = Promise.resolve()
95
+ } else if (injected) {
96
+ guest()
97
+ initPromise = fetchMe().then(() => undefined)
98
+ } else {
99
+ initPromise = fetchMe().then(() => undefined)
100
+ }
101
+ }
102
+ return initPromise
103
+ }
104
+
105
+ function reload() {
106
+ initPromise = fetchMe().then(() => undefined)
107
+ return initPromise
108
+ }
109
+
110
+ async function login(email, password) {
111
+ const result = await api('/api/login', {
112
+ method: 'POST',
113
+ body: { email, password },
114
+ })
115
+ if (result.ok) {
116
+ authenticated(result.data?.user ?? null)
117
+ initPromise = Promise.resolve()
118
+ announce('login')
119
+ }
120
+ return result
121
+ }
122
+
123
+ // Registering does not log in: the account must verify its email first.
124
+ function register({ name, email, password }) {
125
+ return api('/api/register', {
126
+ method: 'POST',
127
+ body: { name, email, password },
128
+ })
129
+ }
130
+
131
+ async function logout() {
132
+ const result = await api('/api/auth/logout', { method: 'POST' })
133
+ // Cleared locally even if the request failed: the user asked to leave.
134
+ guest()
135
+ initPromise = Promise.resolve()
136
+ announce('logout')
137
+ return result
138
+ }
139
+
140
+ function forgotPassword(email) {
141
+ return api('/api/auth/forgot-password', { method: 'POST', body: { email } })
142
+ }
143
+
144
+ // The reset link carries both the token and the email it was sent to;
145
+ // the server checks them together.
146
+ function resetPassword({ email, token, password }) {
147
+ return api('/api/auth/reset-password', {
148
+ method: 'POST',
149
+ body: { email, token, password },
150
+ })
151
+ }
152
+
153
+ // Called by the api client when a refresh fails. Only a user who was
154
+ // logged in can have a session "expire"; a first visit with no session
155
+ // (status still 'loading') is just a guest.
156
+ function expire() {
157
+ if (state.status === 'authenticated') guest({ expired: true })
158
+ }
159
+
160
+ // Bound functions (closures, not methods) so they can be passed around
161
+ // or destructured without losing `this`.
162
+ return {
163
+ getState: () => state,
164
+ subscribe(listener) {
165
+ listeners.add(listener)
166
+ return () => listeners.delete(listener)
167
+ },
168
+ init,
169
+ reload,
170
+ login,
171
+ register,
172
+ logout,
173
+ forgotPassword,
174
+ resetPassword,
175
+ expire,
176
+ }
177
+ }
@@ -0,0 +1,38 @@
1
+ // A stand-in WebSocket for binding tests: records sockets, opens on the next
2
+ // tick, and lets a test push messages in.
3
+ export function installFakeWebSocket(target = globalThis) {
4
+ const sockets = []
5
+ class FakeWebSocket {
6
+ constructor(url) {
7
+ this.url = url
8
+ this.readyState = 0
9
+ this.sent = []
10
+ this.listeners = {}
11
+ sockets.push(this)
12
+ setTimeout(() => {
13
+ if (this.readyState !== 0) return
14
+ this.readyState = 1
15
+ this.emit('open', {})
16
+ }, 0)
17
+ }
18
+ addEventListener(type, fn) {
19
+ ;(this.listeners[type] ??= []).push(fn)
20
+ }
21
+ emit(type, event) {
22
+ for (const fn of this.listeners[type] ?? []) fn(event)
23
+ }
24
+ send(data) {
25
+ this.sent.push(JSON.parse(data))
26
+ }
27
+ receive(data) {
28
+ this.emit('message', { data: JSON.stringify(data) })
29
+ }
30
+ close() {
31
+ this.readyState = 3
32
+ this.emit('close', {})
33
+ }
34
+ }
35
+ const previous = target.WebSocket
36
+ target.WebSocket = FakeWebSocket
37
+ return { sockets, restore: () => (target.WebSocket = previous) }
38
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,140 @@
1
+ export interface ApiOptions {
2
+ method?: string
3
+ body?: unknown
4
+ headers?: Record<string, string>
5
+ credentials?: RequestCredentials
6
+ /** Abort after this many milliseconds. 0 or omitted means no timeout. */
7
+ timeout?: number
8
+ signal?: AbortSignal
9
+ /** Set to false to skip the automatic session refresh on a 401. */
10
+ refresh?: boolean
11
+ }
12
+
13
+ export interface ApiResult<T = any> {
14
+ ok: boolean
15
+ /** HTTP status, or 0 when the server could not be reached. */
16
+ status: number
17
+ data: T
18
+ error: string | null
19
+ /** Field errors from a 422 response: { field: ["message"] }. */
20
+ errors: Record<string, string[]> | null
21
+ aborted?: boolean
22
+ }
23
+
24
+ export type Body = unknown
25
+
26
+ export interface Api {
27
+ <T = any>(url: string, options?: ApiOptions): Promise<ApiResult<T>>
28
+ get<T = any>(url: string, options?: ApiOptions): Promise<ApiResult<T>>
29
+ post<T = any>(url: string, body?: Body, options?: ApiOptions): Promise<ApiResult<T>>
30
+ put<T = any>(url: string, body?: Body, options?: ApiOptions): Promise<ApiResult<T>>
31
+ patch<T = any>(url: string, body?: Body, options?: ApiOptions): Promise<ApiResult<T>>
32
+ delete<T = any>(url: string, options?: ApiOptions): Promise<ApiResult<T>>
33
+ }
34
+
35
+ export interface TylixUser {
36
+ id: number | string
37
+ name: string
38
+ email: string
39
+ [key: string]: unknown
40
+ }
41
+
42
+ export type AuthState =
43
+ | { status: 'loading'; user: null }
44
+ | { status: 'authenticated'; user: TylixUser }
45
+ | { status: 'guest'; user: null; expired?: boolean }
46
+
47
+ export interface RegisterDetails {
48
+ name: string
49
+ email: string
50
+ password: string
51
+ }
52
+
53
+ export interface Auth {
54
+ getState(): AuthState
55
+ subscribe(listener: (state: AuthState) => void): () => void
56
+ init(): Promise<void>
57
+ reload(): Promise<void>
58
+ login(email: string, password: string): Promise<ApiResult<{ user: TylixUser }>>
59
+ register(details: RegisterDetails): Promise<ApiResult<{ user: TylixUser; message: string }>>
60
+ logout(): Promise<ApiResult<null>>
61
+ forgotPassword(email: string): Promise<ApiResult<{ ok: boolean; message: string }>>
62
+ resetPassword(details: { email: string; token: string; password: string }): Promise<ApiResult<{ ok: boolean; message: string }>>
63
+ }
64
+
65
+ export interface ClientOptions {
66
+ baseUrl?: string
67
+ fetch?: typeof fetch
68
+ channel?: BroadcastChannel | null
69
+ }
70
+
71
+ export const api: Api
72
+ export const auth: Auth
73
+
74
+ /** The ApiResult for an HTTP status and parsed JSON body, as api() builds it. */
75
+ export function resultFromResponse<T = any>(status: number, data: T): ApiResult<T>
76
+
77
+ /**
78
+ * Renews the session with the same single shared refresh api() uses, for
79
+ * other HTTP layers (Angular's HttpClient). Resolves true when renewed; on
80
+ * false the session is already marked expired.
81
+ */
82
+ export function refreshSession(): Promise<boolean>
83
+
84
+ export function createClient(options?: ClientOptions): {
85
+ api: Api & { refreshSession(): Promise<boolean> }
86
+ auth: Auth & { expire(): void }
87
+ }
88
+
89
+ export function createApi(
90
+ options?: ClientOptions & { onSessionExpired?: () => void },
91
+ ): Api & { refreshSession(): Promise<boolean> }
92
+
93
+ export function createAuth(options: { api: Api; channel?: BroadcastChannel | null }): Auth & {
94
+ expire(): void
95
+ }
96
+
97
+ export type ChannelStatus = 'connecting' | 'open' | 'reconnecting' | 'closed'
98
+
99
+ export interface Channel<T = unknown> {
100
+ /** Sends JSON; queued while connecting. */
101
+ send(data: unknown): void
102
+ /** Returns a function that removes the listener. */
103
+ onMessage(listener: (data: T) => void): () => void
104
+ onStatus(listener: (status: ChannelStatus) => void): () => void
105
+ readonly status: ChannelStatus
106
+ close(): void
107
+ }
108
+
109
+ export interface ChannelOptions {
110
+ /** Channel server port; default: what the page says, else 6001. */
111
+ port?: number
112
+ /** Full WebSocket URL, instead of host + port + name. */
113
+ url?: string
114
+ /** Reconnect after a dropped connection. Default true. */
115
+ reconnect?: boolean
116
+ }
117
+
118
+ /** A live channel on the channel server ("tylix channels:work"). */
119
+ export function channel<T = unknown>(name: string, options?: ChannelOptions): Channel<T>
120
+
121
+ /** For framework bindings: open() once mounted, close() when unmounted; send() queues until open. */
122
+ export function lazyChannel<T = unknown>(
123
+ name: string,
124
+ handlers?: { onMessage?: (data: T) => void; onStatus?: (status: ChannelStatus) => void },
125
+ ): { open(): void; close(): void; send(data: unknown): void }
126
+
127
+ declare global {
128
+ // Set by the server when it already knows the session at page load.
129
+ // eslint-disable-next-line no-var
130
+ var __TYLIX_SESSION__: { user: TylixUser | null } | undefined
131
+ // Set when the server rendered the page (SSR): hydrate instead of render.
132
+ // eslint-disable-next-line no-var
133
+ var __TYLIX_SSR__: boolean | undefined
134
+ // The channel server's port (CHANNELS_PORT), put in the page by Tylix.
135
+ // eslint-disable-next-line no-var
136
+ var __TYLIX_CHANNELS_PORT__: number | undefined
137
+ // API results the server render loaded, by url, reused while hydrating.
138
+ // eslint-disable-next-line no-var
139
+ var __TYLIX_DATA__: Record<string, ApiResult> | undefined
140
+ }
package/src/index.js ADDED
@@ -0,0 +1,56 @@
1
+ import { createApi, resultFromResponse } from './createApi.js'
2
+ import { createAuth } from './createAuth.js'
3
+ export { channel, lazyChannel } from './channel.js'
4
+
5
+ export { createApi, createAuth, resultFromResponse }
6
+
7
+ // Builds a matching api + auth pair: when the api can't refresh an expired
8
+ // session, the auth store switches to guest.
9
+ export function createClient(options = {}) {
10
+ let auth = null
11
+ const api = createApi({
12
+ ...options,
13
+ onSessionExpired: () => auth?.expire(),
14
+ })
15
+ auth = createAuth({ api, channel: options.channel })
16
+ return { api, auth }
17
+ }
18
+
19
+ // The shared instance apps import. Created lazily so merely importing this
20
+ // module (during SSR or in tests) opens no BroadcastChannel.
21
+ let defaultClient = null
22
+ function getDefault() {
23
+ if (!defaultClient) defaultClient = createClient()
24
+ return defaultClient
25
+ }
26
+
27
+ export function api(url, options) {
28
+ return getDefault().api(url, options)
29
+ }
30
+ api.get = (url, options) => getDefault().api.get(url, options)
31
+ api.post = (url, body, options) => getDefault().api.post(url, body, options)
32
+ api.put = (url, body, options) => getDefault().api.put(url, body, options)
33
+ api.patch = (url, body, options) => getDefault().api.patch(url, body, options)
34
+ api.delete = (url, options) => getDefault().api.delete(url, options)
35
+
36
+ // For HTTP layers other than api(), e.g. Angular's HttpClient interceptor:
37
+ // the same single shared refresh that api() uses, and the same "session
38
+ // over" handling when it fails. Resolves true if the session was renewed.
39
+ export async function refreshSession() {
40
+ const client = getDefault()
41
+ const renewed = await client.api.refreshSession()
42
+ if (!renewed) client.auth.expire()
43
+ return renewed
44
+ }
45
+
46
+ export const auth = {
47
+ getState: () => getDefault().auth.getState(),
48
+ subscribe: (listener) => getDefault().auth.subscribe(listener),
49
+ init: () => getDefault().auth.init(),
50
+ reload: () => getDefault().auth.reload(),
51
+ login: (email, password) => getDefault().auth.login(email, password),
52
+ register: (details) => getDefault().auth.register(details),
53
+ logout: () => getDefault().auth.logout(),
54
+ forgotPassword: (email) => getDefault().auth.forgotPassword(email),
55
+ resetPassword: (details) => getDefault().auth.resetPassword(details),
56
+ }