@weft-js/start 0.1.0 → 0.1.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 (213) hide show
  1. package/README.md +36 -3
  2. package/crate/Cargo.lock +1347 -0
  3. package/crate/Cargo.toml +72 -0
  4. package/crate/rust-toolchain.toml +3 -0
  5. package/crate/src/build/emit.rs +103 -0
  6. package/crate/src/build.rs +367 -0
  7. package/crate/src/ctx.rs +186 -0
  8. package/crate/src/envelope.rs +163 -0
  9. package/crate/src/functions.rs +173 -0
  10. package/crate/src/lib.rs +118 -0
  11. package/crate/src/native.rs +212 -0
  12. package/crate/src/otel.rs +62 -0
  13. package/crate/src/server.rs +203 -0
  14. package/package.json +46 -37
  15. package/src/app.mjs +51 -10
  16. package/src/asset-receipt.d.mts +13 -0
  17. package/src/asset-receipt.mjs +61 -0
  18. package/src/auth/better-auth.ts +215 -17
  19. package/src/auth/drizzle.ts +1 -1
  20. package/src/auth.ts +21 -6
  21. package/src/boot.ts +19 -8
  22. package/src/bus/postgres.ts +32 -19
  23. package/src/bus.ts +7 -4
  24. package/src/{capture.mjs → capture.ts} +34 -1
  25. package/src/changes-sql.d.mts +8 -2
  26. package/src/changes-sql.mjs +26 -10
  27. package/src/changes.ts +165 -66
  28. package/src/channel/connections.ts +216 -0
  29. package/src/channel/socket.ts +396 -0
  30. package/src/channel-fake.ts +19 -4
  31. package/src/channel.ts +124 -490
  32. package/src/client.tsx +9 -2
  33. package/src/contract/describe.mjs +231 -0
  34. package/src/contract.mjs +146 -155
  35. package/src/data/cache.ts +354 -0
  36. package/src/data/definitions.ts +94 -0
  37. package/src/data/draft.ts +104 -0
  38. package/src/data/foundation.ts +95 -0
  39. package/src/data/live-api.ts +22 -0
  40. package/src/data/mutation.ts +138 -0
  41. package/src/data/primitives.ts +135 -0
  42. package/src/data/query.ts +106 -0
  43. package/src/data/transport.ts +121 -0
  44. package/src/data/types.ts +303 -0
  45. package/src/data.ts +69 -894
  46. package/src/db/bun-sqlite.d.ts +4 -1
  47. package/src/db/changes-mysql.ts +61 -21
  48. package/src/db/changes-postgres.ts +197 -118
  49. package/src/db/changes-sqlite.ts +131 -64
  50. package/src/db/core.ts +38 -13
  51. package/src/db/index.ts +20 -4
  52. package/src/db/mysql.ts +22 -6
  53. package/src/db/postgres.ts +49 -13
  54. package/src/db/sqlite.ts +53 -27
  55. package/src/derive.d.mts +4 -1
  56. package/src/derive.mjs +136 -39
  57. package/src/dev-runtime.mjs +8 -4
  58. package/src/exec/errors.ts +57 -0
  59. package/src/exec/landing.ts +66 -0
  60. package/src/exec/scope.ts +174 -0
  61. package/src/exec/touch.ts +80 -0
  62. package/src/exec/validation.ts +176 -0
  63. package/src/exec.ts +191 -341
  64. package/src/extension.ts +8 -2
  65. package/src/first-paint.ts +26 -9
  66. package/src/form/value.ts +15 -0
  67. package/src/form.tsx +132 -43
  68. package/src/hub/channels.ts +102 -0
  69. package/src/hub/connections.ts +147 -0
  70. package/src/hub/delivery.ts +62 -0
  71. package/src/hub/feed.ts +168 -0
  72. package/src/hub/presence.ts +64 -0
  73. package/src/hub/route.ts +158 -0
  74. package/src/hub/subscriptions.ts +212 -0
  75. package/src/hub/topic.ts +98 -0
  76. package/src/hub/tracked.ts +12 -0
  77. package/src/hub/types.ts +190 -0
  78. package/src/hub/view.ts +147 -0
  79. package/src/hub.ts +132 -758
  80. package/src/index.ts +84 -10
  81. package/src/inline.mjs +356 -0
  82. package/src/inspect/compare.mjs +162 -0
  83. package/src/inspect/routes.mjs +154 -0
  84. package/src/inspect/samples.mjs +59 -0
  85. package/src/inspect/url.mjs +2 -0
  86. package/src/inspect.mjs +146 -187
  87. package/src/link/election.ts +178 -0
  88. package/src/link/lines.ts +27 -0
  89. package/src/link.ts +97 -168
  90. package/src/list-drizzle.ts +104 -18
  91. package/src/list.ts +127 -36
  92. package/src/listen.ts +32 -6
  93. package/src/live/api.ts +18 -0
  94. package/src/live/backoff.ts +6 -0
  95. package/src/live/frames.ts +42 -0
  96. package/src/live/read.ts +77 -0
  97. package/src/live/sub-types.ts +24 -0
  98. package/src/live/transport.ts +86 -0
  99. package/src/live/types.ts +52 -0
  100. package/src/live-fake.ts +20 -5
  101. package/src/live-target.mjs +113 -35
  102. package/src/live.ts +116 -225
  103. package/src/media.ts +8 -1
  104. package/src/migrations.mjs +14 -6
  105. package/src/mux.ts +161 -64
  106. package/src/og/DefaultCard.tsx +40 -9
  107. package/src/og/fonts.mjs +16 -8
  108. package/src/og/images.mjs +43 -22
  109. package/src/og/index.mjs +119 -43
  110. package/src/og/native.mjs +11 -4
  111. package/src/range.mjs +15 -3
  112. package/src/router.ts +56 -6
  113. package/src/routes.mjs +73 -22
  114. package/src/run/admission.ts +80 -0
  115. package/src/run/boot.tsx +115 -0
  116. package/src/run/cache-presentation.ts +67 -0
  117. package/src/run/cache.ts +254 -0
  118. package/src/run/helpers.ts +197 -0
  119. package/src/run/listeners.ts +155 -0
  120. package/src/run/navigation.ts +382 -0
  121. package/src/run/page-skeleton.tsx +35 -0
  122. package/src/run/prefetch.ts +128 -0
  123. package/src/run/retain-view.ts +18 -0
  124. package/src/run/shape-preparation.ts +97 -0
  125. package/src/run/shape-styles.ts +72 -0
  126. package/src/run/source-context/pin.ts +124 -0
  127. package/src/run/source-context.ts +311 -0
  128. package/src/run.tsx +50 -174
  129. package/src/rust/common.ts +163 -0
  130. package/src/rust/native.ts +282 -0
  131. package/src/rust.ts +103 -229
  132. package/src/server/card.tsx +65 -0
  133. package/src/server/compression.ts +115 -0
  134. package/src/server/core.ts +70 -0
  135. package/src/server/dispatch.ts +70 -0
  136. package/src/server/form.ts +85 -0
  137. package/src/server/functions.ts +129 -0
  138. package/src/server/handler.ts +39 -0
  139. package/src/server/head.ts +96 -0
  140. package/src/server/media.ts +60 -0
  141. package/src/server/navigation-cache.ts +80 -0
  142. package/src/server/navigation.tsx +85 -0
  143. package/src/server/page-cold.ts +95 -0
  144. package/src/server/page-stream.tsx +181 -0
  145. package/src/server/page-types.ts +51 -0
  146. package/src/server/page-warm.ts +130 -0
  147. package/src/server/page.ts +69 -0
  148. package/src/server/payload.ts +89 -0
  149. package/src/server/prerender.ts +60 -0
  150. package/src/server/preview.tsx +67 -0
  151. package/src/server/render.ts +167 -0
  152. package/src/server/request.ts +98 -0
  153. package/src/server/resolver.ts +228 -0
  154. package/src/server/routes.ts +150 -0
  155. package/src/server/services.ts +69 -0
  156. package/src/server/text.ts +29 -0
  157. package/src/server/types.ts +160 -0
  158. package/src/server.tsx +82 -964
  159. package/src/shape.mjs +30 -6
  160. package/src/share/display.ts +50 -0
  161. package/src/share/network.ts +119 -0
  162. package/src/share/receive.ts +70 -0
  163. package/src/share/state.ts +30 -0
  164. package/src/share/tab-queue.ts +28 -0
  165. package/src/share-server.ts +128 -43
  166. package/src/share.ts +103 -209
  167. package/src/sheets.mjs +30 -18
  168. package/src/sidecar/build.mjs +170 -0
  169. package/src/sidecar/cargo.mjs +164 -0
  170. package/src/sidecar/common.mjs +17 -0
  171. package/src/sidecar/dev-build.mjs +91 -0
  172. package/src/sidecar/dev-watch.mjs +88 -0
  173. package/src/sidecar/manifest.mjs +19 -0
  174. package/src/sidecar/process.mjs +58 -0
  175. package/src/sidecar/refresh.mjs +19 -0
  176. package/src/sidecar.mjs +75 -416
  177. package/src/socket/check.ts +50 -0
  178. package/src/socket/deliver.ts +16 -0
  179. package/src/socket/publish.ts +56 -0
  180. package/src/socket/rooms.ts +41 -0
  181. package/src/socket/route.ts +79 -0
  182. package/src/socket/shared.ts +26 -0
  183. package/src/socket/types.ts +48 -0
  184. package/src/socket.ts +205 -194
  185. package/src/stream.ts +10 -1
  186. package/src/verify/app.ts +39 -0
  187. package/src/verify/cleanup.ts +27 -0
  188. package/src/verify/database.ts +11 -0
  189. package/src/verify/live.ts +63 -0
  190. package/src/verify/notify.ts +35 -0
  191. package/src/verify/skip.ts +19 -0
  192. package/src/verify/support.ts +149 -0
  193. package/src/verify/timing.ts +15 -0
  194. package/src/verify/trigger.ts +14 -0
  195. package/src/verify.ts +77 -176
  196. package/src/view.tsx +96 -11
  197. package/src/vite/asset-bytes.mjs +95 -0
  198. package/src/vite/assets.mjs +117 -0
  199. package/src/vite/config-hooks.mjs +166 -0
  200. package/src/vite/dev-hooks.mjs +103 -0
  201. package/src/vite/dev.mjs +102 -0
  202. package/src/vite/entries.mjs +145 -0
  203. package/src/vite/module-hooks.mjs +288 -0
  204. package/src/vite/route-modules.mjs +289 -0
  205. package/src/vite/server-functions.mjs +222 -0
  206. package/src/vite/shape-entry-css.mjs +187 -0
  207. package/src/vite/shape-override.mjs +226 -0
  208. package/src/vite/shared.mjs +51 -0
  209. package/src/vite/sheets.mjs +92 -0
  210. package/src/vite/state.mjs +89 -0
  211. package/src/vite/syntax.mjs +139 -0
  212. package/src/vite.mjs +152 -853
  213. package/src/capture.d.mts +0 -1
package/src/channel.ts CHANGED
@@ -3,9 +3,22 @@
3
3
  // finds its messages. The socket server is socket.ts, and `room.in(params).publish` reaches it through
4
4
  // `runtime.channels`, so nothing of the server ships here.
5
5
 
6
- import { Box, DEV, batch, collect as boxes, createRoot, derived, effect, getOwner, onCleanup, state, untrack, type Derived, type State } from '@weft-js/core'
7
- import { HANDOVER, openLine, socketDown } from './link'
8
- import { currentScope, fns, FnError, keyOf, net, rt, runtime, skip, StartError, track, type Context, type Fn, type Skip, type StandardSchemaV1 } from './data'
6
+ import { type Derived, type State } from '@weft-js/core'
7
+ import {
8
+ fns,
9
+ runtime,
10
+ StartError,
11
+ track,
12
+ type Context,
13
+ type Fn,
14
+ type Skip,
15
+ type StandardSchemaV1,
16
+ } from './data'
17
+ import { connect, shared, connectBuiltIn } from './channel/connections'
18
+ import { keepOpen, wakeSocket, setFake, type Frame, type SocketLink } from './channel/socket'
19
+
20
+ export { connectBuiltIn, keepOpen, wakeSocket }
21
+ export type { Frame, SocketLink }
9
22
 
10
23
  // ---- definitions ----------------------------------------------------------------------------------------------------
11
24
 
@@ -15,8 +28,17 @@ type Schemas = Record<string, StandardSchemaV1>
15
28
  type Inputs<T extends Schemas> = { [K in keyof T]: In<T[K]> }
16
29
  type Outputs<T extends Schemas> = { [K in keyof T]: Out<T[K]> }
17
30
 
18
- /** Where a connection stands; `unauthorized` waits for `rejoin`. */
19
- export type ChannelStatus = 'connecting' | 'open' | 'reconnecting' | 'closed' | 'unauthorized'
31
+ /**
32
+ * Where a connection stands; `unauthorized` waits for `rejoin`. `unavailable`: this deploy can't hold a socket (a
33
+ * function host, R024), so nothing connects and nothing is retried.
34
+ */
35
+ export type ChannelStatus =
36
+ | 'connecting'
37
+ | 'open'
38
+ | 'reconnecting'
39
+ | 'closed'
40
+ | 'unauthorized'
41
+ | 'unavailable'
20
42
 
21
43
  /** `room.publish`: who a message goes to, and whether it can be replayed. */
22
44
  export interface PublishOptions {
@@ -32,11 +54,19 @@ export interface PublishOptions {
32
54
  export interface Room<P, M> {
33
55
  params: P
34
56
  /** To everyone in the room, on every instance. */
35
- publish<K extends keyof M & string>(name: K, message: M[K], options?: PublishOptions): Promise<void>
57
+ publish<K extends keyof M & string>(
58
+ name: K,
59
+ message: M[K],
60
+ options?: PublishOptions,
61
+ ): Promise<void>
36
62
  }
37
63
 
38
64
  /** `channel()`: the params, the messages each side may send, and who may join. */
39
- export interface ChannelDef<P extends StandardSchemaV1 | undefined, C extends Schemas, S extends Schemas> {
65
+ export interface ChannelDef<
66
+ P extends StandardSchemaV1 | undefined,
67
+ C extends Schemas,
68
+ S extends Schemas,
69
+ > {
40
70
  params?: P
41
71
  /** Required (R001). Runs on every join and at each session re-check. `() => true` must be written out. */
42
72
  authorize: (args: { ctx: Context; params: Out<P> }) => boolean | Promise<boolean>
@@ -45,9 +75,22 @@ export interface ChannelDef<P extends StandardSchemaV1 | undefined, C extends Sc
45
75
  /** Server → client, validated in dev and tests. */
46
76
  server?: S
47
77
  /** `id` is the sender's connection, the same one `left` gets. */
48
- on?: { [K in keyof C]?: (args: { msg: Out<C[K]>; id: string; ctx: Context; params: Out<P>; room: Room<Out<P>, Inputs<S>> }) => unknown }
78
+ on?: {
79
+ [K in keyof C]?: (args: {
80
+ msg: Out<C[K]>
81
+ id: string
82
+ ctx: Context
83
+ params: Out<P>
84
+ room: Room<Out<P>, Inputs<S>>
85
+ }) => unknown
86
+ }
49
87
  /** A connection stopped being in the room: it left, closed, or lost `authorize`. Not called if its instance dies. */
50
- left?: (args: { id: string; ctx: Context; params: Out<P>; room: Room<Out<P>, Inputs<S>> }) => unknown
88
+ left?: (args: {
89
+ id: string
90
+ ctx: Context
91
+ params: Out<P>
92
+ room: Room<Out<P>, Inputs<S>>
93
+ }) => unknown
51
94
  limits?: { perSecond?: number }
52
95
  $id?: string
53
96
  }
@@ -62,7 +105,10 @@ export interface Connection<C, S> {
62
105
  /** Ticks when the server couldn't resume: messages may be missing, so refetch what the room's history is. */
63
106
  readonly resets: Derived<number>
64
107
  /** Keep a room's messages of one name, in the cache: a remount within `keep` finds them. `key` drops a repeat. */
65
- collect<K extends keyof S & string>(name: K, options?: { max?: number; key?: (message: S[K]) => unknown }): Derived<S[K][]>
108
+ collect<K extends keyof S & string>(
109
+ name: K,
110
+ options?: { max?: number; key?: (message: S[K]) => unknown },
111
+ ): Derived<S[K][]>
66
112
  /** Each message of one name, until the owner is disposed. */
67
113
  on<K extends keyof S & string>(name: K, fn: (message: S[K]) => void): () => void
68
114
  onReset(fn: () => void): () => void
@@ -74,14 +120,22 @@ export interface Connection<C, S> {
74
120
 
75
121
  type Arg<P> = P | (() => P | Skip)
76
122
  /** How long a join outlives the last component using it. */
77
- export interface ConnectOptions { keep?: string | number }
123
+ export interface ConnectOptions {
124
+ keep?: string | number
125
+ }
78
126
 
79
127
  /** What `channel()` returns: connect from a page, publish from the server. */
80
128
  export interface Channel<P, C, S> {
81
129
  /** In a component or scope. A function argument re-joins when what it reads changes; `skip` leaves. */
82
- connect(...args: [P] extends [void] ? [params?: undefined | (() => undefined | Skip), options?: ConnectOptions] : [params: Arg<P>, options?: ConnectOptions]): Connection<C, S>
130
+ connect(
131
+ ...args: [P] extends [void]
132
+ ? [params?: undefined | (() => undefined | Skip), options?: ConnectOptions]
133
+ : [params: Arg<P>, options?: ConnectOptions]
134
+ ): Connection<C, S>
83
135
  /** On the server, from a mutation or a job. */
84
- in(...args: [P] extends [void] ? [] : [params: P]): { publish<K extends keyof S & string>(name: K, message: S[K]): Promise<void> }
136
+ in(...args: [P] extends [void] ? [] : [params: P]): {
137
+ publish<K extends keyof S & string>(name: K, message: S[K]): Promise<void>
138
+ }
85
139
  readonly kind: 'channel'
86
140
  readonly $id: string
87
141
  }
@@ -90,15 +144,29 @@ const FN = Symbol.for('weft.fn')
90
144
  let auto = 0
91
145
 
92
146
  /** A named room of schema-checked messages over the shared socket. */
93
- export function channel<P extends StandardSchemaV1 | undefined = undefined, C extends Schemas = {}, S extends Schemas = {}>(def: ChannelDef<P, C, S>): Channel<In<P>, Inputs<C>, Outputs<S>> {
147
+ export function channel<
148
+ P extends StandardSchemaV1 | undefined = undefined,
149
+ C extends Schemas = {},
150
+ S extends Schemas = {},
151
+ >(def: ChannelDef<P, C, S>): Channel<In<P>, Inputs<C>, Outputs<S>> {
94
152
  const id = def.$id ?? `c${++auto}`
95
- if (!(def as { $stub?: boolean }).$stub && !def.authorize) throw new StartError('R001', `\`${id}\` has no \`authorize\`: anyone could join it`, 'add `authorize` (`() => true` must be written out)')
153
+ if (!(def as { $stub?: boolean }).$stub && !def.authorize)
154
+ throw new StartError(
155
+ 'R001',
156
+ `\`${id}\` has no \`authorize\`: anyone could join it`,
157
+ 'add `authorize` (`() => true` must be written out)',
158
+ )
96
159
  const fn: Fn = { kind: 'channel', $id: id, def: def as Fn['def'] }
97
160
  fns.set(id, fn)
98
161
  return {
99
- kind: 'channel', $id: id, [FN]: fn,
162
+ kind: 'channel',
163
+ $id: id,
164
+ [FN]: fn,
100
165
  connect: (params?: unknown, options?: ConnectOptions) => connect(fn, params, options),
101
- in: (params?: unknown) => ({ publish: (name: string, message: unknown) => runtime.channels!.publish(fn, params, name, message) }),
166
+ in: (params?: unknown) => ({
167
+ publish: (name: string, message: unknown) =>
168
+ runtime.channels!.publish(fn, params, name, message),
169
+ }),
102
170
  } as never
103
171
  }
104
172
 
@@ -109,12 +177,18 @@ export interface SharedDef<K extends StandardSchemaV1, V extends StandardSchemaV
109
177
  /** What a reader has until the server says otherwise. Kept in the client bundle, so plain data. */
110
178
  initial: Out<V>
111
179
  /** Both required (R001). */
112
- authorize: { read: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean>; write: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean> }
180
+ authorize: {
181
+ read: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean>
182
+ write: (args: { ctx: Context; key: Out<K> }) => boolean | Promise<boolean>
183
+ }
113
184
  $id?: string
114
185
  }
115
186
 
116
187
  /** A box in a scope: reads as a value, and a write is optimistic, sent, and last writer wins on the server. */
117
- export type SharedBox<T> = State<T> & { readonly status: Derived<ChannelStatus>; readonly error: unknown }
188
+ export type SharedBox<T> = State<T> & {
189
+ readonly status: Derived<ChannelStatus>
190
+ readonly error: unknown
191
+ }
118
192
 
119
193
  /** What `sharedState()` returns: read a value on a page, set it from the server. */
120
194
  export interface SharedState<K, V> {
@@ -126,491 +200,51 @@ export interface SharedState<K, V> {
126
200
  }
127
201
 
128
202
  /** One value per key that every client holding that key sees change. */
129
- export function sharedState<K extends StandardSchemaV1, V extends StandardSchemaV1>(name: string, def: SharedDef<K, V>): SharedState<In<K>, Out<V>> {
203
+ export function sharedState<K extends StandardSchemaV1, V extends StandardSchemaV1>(
204
+ name: string,
205
+ def: SharedDef<K, V>,
206
+ ): SharedState<In<K>, Out<V>> {
130
207
  const id = def.$id ?? `shared:${name}`
131
- if (!(def as { $stub?: boolean }).$stub && (!def.authorize?.read || !def.authorize?.write)) throw new StartError('R001', `\`${id}\` needs \`authorize: { read, write }\`: anyone could read or write it`, '`() => true` must be written out')
208
+ if (!(def as { $stub?: boolean }).$stub && (!def.authorize?.read || !def.authorize?.write))
209
+ throw new StartError(
210
+ 'R001',
211
+ `\`${id}\` needs \`authorize: { read, write }\`: anyone could read or write it`,
212
+ '`() => true` must be written out',
213
+ )
132
214
  const fn: Fn = { kind: 'shared', $id: id, def }
133
215
  fns.set(id, fn)
134
216
  return {
135
- kind: 'shared', $id: id, [FN]: fn,
217
+ kind: 'shared',
218
+ $id: id,
219
+ [FN]: fn,
136
220
  connect: (key: unknown, options?: ConnectOptions) => shared(fn, key, options),
137
221
  in: (key: unknown) => ({ set: (value: unknown) => runtime.channels!.set(fn, key, value) }),
138
222
  } as never
139
223
  }
140
224
 
141
- // ---- joins ----------------------------------------------------------------------------------------------------------
142
-
143
- interface ListSpec { name: string; max: number; key?: ((m: never) => unknown) | undefined }
144
- interface List extends ListSpec { box: State<unknown[]> }
145
- interface Handle { on: Map<string, Set<(m: never) => void>>; resets: Set<() => void>; value?(v: { v: unknown; at: number }): void }
146
- interface Join {
147
- n: number
148
- key: string
149
- fn: Fn
150
- params: unknown
151
- refs: number
152
- timer?: ReturnType<typeof setTimeout> | undefined
153
- cursor?: string | undefined
154
- joined: boolean
155
- refused: boolean
156
- status: State<ChannelStatus>
157
- error: State<unknown>
158
- resets: State<number>
159
- lists: Map<string, List>
160
- handles: Set<Handle>
161
- /** `send`s waiting for the join. */
162
- waiting: Set<() => void>
163
- }
164
-
165
- const joins = new Map<string, Join>()
166
- const byN = new Map<number, Join>()
167
- let nth = 0
168
-
169
- const KEEP = 30_000
170
- const ms = (keep: string | number = KEEP): number => {
171
- if (typeof keep === 'number') return keep
172
- const m = /^(\d+)(ms|s|m)$/.exec(keep)
173
- return m ? +m[1]! * { ms: 1, s: 1000, m: 60_000 }[m[2] as 'ms' | 's' | 'm'] : Infinity
174
- }
175
-
176
- function acquire(fn: Fn, params: unknown): Join {
177
- const key = keyOf(fn.$id, params)
178
- let j = joins.get(key)
179
- if (!j) {
180
- j = createRoot(() => ({ n: ++nth, key, fn, params, refs: 0, joined: false, refused: false, status: state<ChannelStatus>('connecting'), error: state<unknown>(undefined), resets: state(0), lists: new Map(), handles: new Set(), waiting: new Set() }), null)
181
- if (DEV && net() && !net()!.resets.includes(reset)) net()!.resets.push(reset)
182
- joins.set(key, j)
183
- byN.set(j.n, j)
184
- if (live) enter(j)
185
- else start()
186
- }
187
- clearTimeout(j.timer)
188
- j.timer = undefined
189
- j.refs++
190
- return j
191
- }
192
-
193
- function release(j: Join, keep?: string | number) {
194
- if (--j.refs) return
195
- const t = ms(keep)
196
- if (t === Infinity) return
197
- if (t) j.timer = setTimeout(() => drop(j), t)
198
- else drop(j)
199
- }
200
-
201
- function drop(j: Join) {
202
- joins.delete(j.key)
203
- byN.delete(j.n)
204
- j.status.value = 'closed'
205
- if (live) send(['l', j.n])
206
- for (const w of Array.from(j.waiting)) w()
207
- if (!joins.size) live?.close()
208
- }
209
-
210
- function hold(j: Join, keep?: string | number): () => void {
211
- const token = {}
212
- const stop = () => {
213
- net()?.open.delete(token)
214
- release(j, keep)
215
- }
216
- if (DEV) net()?.open.set(token, [`channel \`${j.key}\``, stop])
217
- return stop
218
- }
219
-
220
- function listOf(j: Join, spec: ListSpec): List {
221
- const id = `${spec.name}:${spec.max}:${spec.key ? String(spec.key) : ''}`
222
- let l = j.lists.get(id)
223
- if (!l) j.lists.set(id, (l = createRoot(() => ({ ...spec, box: state<unknown[]>([]) }), null)))
224
- return l
225
- }
226
-
227
- const NONE: never[] = []
228
- type View = Join | undefined
229
-
230
- /** The part `connect` and `shared` have in common: the current join, as the argument moves. */
231
- function follow(fn: Fn, arg: unknown, options: ConnectOptions | undefined, handle: Handle, joined?: (j: Join) => void): State<View> {
232
- const view = state<View>(undefined)
233
- effect(() => {
234
- const params = typeof arg === 'function' ? (arg as () => unknown)() : arg
235
- if (params === skip) return undefined
236
- return untrack(() => {
237
- const j = acquire(fn, params)
238
- j.handles.add(handle)
239
- joined?.(j)
240
- const stop = hold(j, options?.keep)
241
- onCleanup(() => {
242
- j.handles.delete(handle)
243
- stop()
244
- })
245
- return j
246
- })
247
- }, now => { view.value = now })
248
- return view
249
- }
250
-
251
- function owned(fn: Fn) {
252
- if (!getOwner()) throw new StartError('W051', DEV ? `\`${fn.$id}.connect()\` was called outside a component or scope: nothing would close it` : fn.$id, DEV ? 'call it in a component, a `defineState` setup or `createRoot(dispose => …)`' : undefined)
253
- }
254
-
255
- /** `@weft-js/start/share`'s way in: a join that nothing on the page declared, so a tab shares this socket and its lifecycle. */
256
- export const connectBuiltIn = ($id: string) => connect({ kind: 'channel', $id, def: {} }, undefined, { keep: 0 })
257
-
258
- function connect(fn: Fn, arg: unknown, options?: ConnectOptions): Connection<Record<string, never>, Record<string, never>> {
259
- owned(fn)
260
- if (currentScope()) {
261
- const closed = { value: 'connecting' as ChannelStatus }
262
- return { status: closed, room: { value: undefined }, error: undefined, resets: { value: 0 }, collect: () => ({ value: NONE }), on: () => () => {}, onReset: () => () => {}, send: () => Promise.reject(new FnError({ message: 'a channel has no socket on the server' }, 500)), retry() {} }
263
- }
264
- const handle: Handle = { on: new Map(), resets: new Set() }
265
- const wanted: ListSpec[] = []
266
- const view = follow(fn, arg, options, handle, j => { for (const w of wanted) listOf(j, w) })
267
- return {
268
- status: derived(() => view.value?.status.value ?? 'closed'),
269
- room: derived(() => view.value?.key),
270
- get error() { return view.value?.error.value },
271
- resets: derived(() => view.value?.resets.value ?? 0),
272
- collect(name, { max = 200, key } = {}) {
273
- const spec: ListSpec = { name, max, key }
274
- wanted.push(spec)
275
- const had = untrack(() => view.value)
276
- if (had) listOf(had, spec)
277
- return derived(() => {
278
- const j = view.value
279
- return (j ? listOf(j, spec).box.value : NONE) as never[]
280
- })
281
- },
282
- on(name, listener) {
283
- const set = handle.on.get(name) ?? new Set()
284
- handle.on.set(name, set)
285
- set.add(listener)
286
- const stop = () => void set.delete(listener)
287
- onCleanup(stop)
288
- return stop
289
- },
290
- onReset(listener) {
291
- handle.resets.add(listener)
292
- const stop = () => void handle.resets.delete(listener)
293
- onCleanup(stop)
294
- return stop
295
- },
296
- send(name, message) {
297
- const j = untrack(() => view.value)
298
- return j ? post(j, name, message) : Promise.reject(new FnError({ message: 'this channel is closed' }, 400))
299
- },
300
- retry() {
301
- const j = untrack(() => view.value)
302
- if (j?.refused) rejoin(j)
303
- },
304
- }
305
- }
306
-
307
- /** `Box.w` is the one way a write gets in, so a subclass sees every write, and `Instance` never touches it. */
308
- class Shared<T> extends Box<T> {
309
- declare remote?: boolean
310
- declare pending: number
311
- declare base: { v: T; at: number }
312
- declare view: State<View>
313
- declare statusOf: Derived<ChannelStatus>
314
- declare problem: State<unknown>
315
- get status() { return this.statusOf }
316
- get error() { return this.problem.value }
317
- /** A server value: applied unless a local write is still on its way. */
318
- apply(v: { v: T; at: number }) {
319
- if (v.at >= this.base.at) this.base = v
320
- if (!this.pending) this.quiet(this.base.v)
321
- }
322
- quiet(v: T) {
323
- this.remote = true
324
- this.w(v)
325
- this.remote = false
326
- }
327
- override w(v: T) {
328
- if (this.remote) return super.w(v)
329
- const j = untrack(() => this.view.value)
330
- if (!j) return super.w(v)
331
- super.w(v)
332
- this.pending++
333
- this.problem.value = undefined
334
- void track(post(j, '$set', v).then(() => { this.pending-- }, e => {
335
- this.pending--
336
- this.problem.value = e
337
- }).finally(() => { if (!this.pending) this.quiet(this.base.v) }))
338
- }
339
- }
340
-
341
- function shared(fn: Fn, arg: unknown, options?: ConnectOptions): SharedBox<unknown> {
342
- owned(fn)
343
- const initial = fn.def.initial
344
- const [b] = boxes(() => new Shared<unknown>(initial))
345
- b.pending = 0
346
- b.base = { v: initial, at: 0 }
347
- b.problem = state<unknown>(undefined)
348
- if (currentScope()) {
349
- b.statusOf = { value: 'connecting' }
350
- b.view = state<View>(undefined)
351
- return b
352
- }
353
- const handle: Handle = { on: new Map(), resets: new Set(), value: v => b.apply(v) }
354
- b.view = follow(fn, arg, options, handle, () => { b.base = { v: initial, at: 0 } })
355
- b.statusOf = derived(() => b.view.value?.status.value ?? 'closed')
356
- return b
357
- }
358
-
359
- // ---- sends ----------------------------------------------------------------------------------------------------------
360
-
361
- const ACK_WAIT = 10_000
362
- const acks = new Map<number, { ok: () => void; no: (e: unknown) => void; n: number }>()
363
- let ackId = 0
364
-
365
- async function post(j: Join, name: string, message: unknown): Promise<void> {
366
- if (!j.joined && !j.refused) {
367
- await new Promise<void>(ok => {
368
- const done = () => {
369
- clearTimeout(t)
370
- j.waiting.delete(done)
371
- ok()
372
- }
373
- const t = setTimeout(done, ACK_WAIT)
374
- j.waiting.add(done)
375
- })
376
- }
377
- if (!j.joined) throw new FnError({ ...(j.refused && { code: 'R011' }), message: j.refused ? 'not allowed in this channel' : 'no connection: not sent' }, j.refused ? 403 : 503)
378
- const ack = ++ackId
379
- const p = new Promise<void>((ok, no) => { acks.set(ack, { ok, no, n: j.n }) })
380
- send(['m', j.n, ack, name, message])
381
- return track(p)
382
- }
383
-
384
- // ---- the socket ------------------------------------------------------------------------------------------------------
385
-
386
- /** What the server sends a channel's client: the first element says which. */
387
- export type Frame =
388
- | ['h', { b?: string }]
389
- | ['j', number, string | undefined]
390
- | ['m', number, string | undefined, string, never]
391
- | ['r', number, string | undefined]
392
- | ['e', number, { code?: string; message?: string }]
393
- | ['a', number, number, { code?: string; message?: string } | undefined]
394
-
395
- /** One end of a socket, as a channel holds it. */
396
- export interface SocketLink {
397
- send(text: string): void
398
- close(): void
399
- }
400
-
401
- /** This tab's line on the browser's one socket (link.ts). `done` gets the close code. */
402
- function browser(onFrame: (d: Frame) => void, closed: (code: number) => void): SocketLink {
403
- return openLine('c', '', text => onFrame(JSON.parse(text)), closed)
404
- }
405
-
406
225
  /** @weft-js/core/test only: an opaque specifier, so a bundler keeps neither the fake nor the socket server (research 30 §10). */
407
226
  const FAKE = './channel-fake.ts' // with its extension: nothing resolves this one for a linked package
408
227
  function fake(onFrame: (d: Frame) => void, closed: (code: number) => void): SocketLink {
409
228
  let link: SocketLink | undefined
410
229
  let up!: () => void
411
- void track(new Promise<void>(ok => { up = ok }))
412
- const loading = import(/* @vite-ignore */ FAKE).then(m => m.open(onFrame, closed, up)).then(l => (link = l), e => (up(), closed(1006), Promise.reject(e))).catch(() => {})
413
- return { send: t => void track(loading.then(() => link?.send(t))), close: () => { void loading.then(() => link?.close()) } }
414
- }
415
-
416
- const BASE = 500, CAP = 30_000, PING = 20_000, DEAD = 45_000, HIDDEN = 300_000
417
-
418
- let live: SocketLink | undefined
419
- let open = false
420
- let running = false
421
- let attempt = 0
422
- let build: string | undefined
423
- let nudge: (() => void) | undefined
424
- let parked = false
425
- let hiddenAt: ReturnType<typeof setTimeout> | undefined
426
-
427
- /** A leader tab can be hidden while a sibling is looking: `@weft-js/start/share` says when this socket must stay. */
428
- export const keepOpen: { stay?: (() => boolean) | undefined } = {}
429
-
430
- const send = (f: unknown[]) => live?.send(JSON.stringify(f))
431
- const statusAll = (s: ChannelStatus) => { for (const j of joins.values()) if (!j.refused) j.status.value = s }
432
-
433
- function enter(j: Join) {
434
- if (!open || !live) return
435
- send(['j', j.n, j.fn.$id, j.params, j.cursor])
436
- }
437
-
438
- function rejoin(j: Join) {
439
- j.refused = false
440
- j.status.value = 'connecting'
441
- if (running) enter(j)
442
- else start()
443
- }
444
-
445
- function start() {
446
- if (running) return
447
- running = true
448
- queueMicrotask(() => void run())
449
- }
450
-
451
- function dispatch(j: Join, name: string, msg: never) {
452
- if (name === '$v') {
453
- for (const h of j.handles) h.value?.(msg)
454
- return
455
- }
456
- for (const l of j.lists.values()) {
457
- if (l.name !== name) continue
458
- const was = untrack(() => l.box.value)
459
- const key = l.key?.(msg)
460
- const at = l.key ? was.findIndex(m => l.key!(m as never) === key) : -1
461
- const next = at >= 0 ? was.map((m, i) => (i === at ? msg : m)) : [...was, msg]
462
- l.box.value = next.length > l.max ? next.slice(-l.max) : next
463
- }
464
- for (const h of j.handles) for (const f of h.on.get(name) ?? []) f(msg)
465
- }
466
-
467
- function frame(d: Frame) {
468
- batch(() => {
469
- const j = typeof d[1] === 'number' ? byN.get(d[1]) : undefined
470
- if (d[0] === 'h') {
471
- if (build && d[1].b && d[1].b !== build) rt.stale.value = true
472
- build = d[1].b
473
- open = true
474
- attempt = 0
475
- for (const x of joins.values()) if (!x.refused) enter(x)
476
- } else if (d[0] === 'j' && j) {
477
- j.cursor ??= d[2]
478
- j.joined = true
479
- j.error.value = undefined
480
- j.status.value = 'open'
481
- for (const w of Array.from(j.waiting)) w()
482
- } else if (d[0] === 'm' && j) {
483
- j.cursor = d[2]
484
- dispatch(j, d[3], d[4])
485
- } else if (d[0] === 'r' && j) {
486
- j.cursor = d[2]
487
- for (const l of j.lists.values()) l.box.value = []
488
- j.resets.value++
489
- for (const h of j.handles) for (const f of h.resets) f()
490
- } else if (d[0] === 'e' && j) {
491
- j.joined = false
492
- j.refused = true
493
- j.error.value = new FnError(d[2], d[2].code === 'R011' ? 403 : 400)
494
- j.status.value = d[2].code === 'R011' ? 'unauthorized' : 'closed'
495
- for (const w of Array.from(j.waiting)) w()
496
- } else if (d[0] === 'a') {
497
- const p = acks.get(d[2])
498
- acks.delete(d[2])
499
- if (d[3]) p?.no(new FnError(d[3], d[3].code === 'R011' ? 403 : 400))
500
- else p?.ok()
501
- }
502
- })
503
- }
504
-
505
- const sleep = (t: number) => new Promise<void>(ok => {
506
- const timer = setTimeout(ok, t)
507
- nudge = () => {
508
- clearTimeout(timer)
509
- nudge = undefined
510
- ok()
511
- }
512
- })
513
-
514
- async function run() {
515
- listen(true)
516
- const fakeNet = () => (DEV ? net() : undefined)
517
- while (joins.size) {
518
- if (parked || ! navigator.onLine) {
519
- statusAll('reconnecting')
520
- await sleep(CAP)
521
- continue
522
- }
523
- let code = 0
524
- let dead: ReturnType<typeof setTimeout> | undefined
525
- let ping: ReturnType<typeof setInterval> | undefined
526
- const alive = () => {
527
- clearTimeout(dead)
528
- if (!fakeNet()) dead = setTimeout(() => live?.close(), DEAD)
529
- }
530
- await new Promise<void>(done => {
531
- const take = (d: Frame) => {
532
- alive()
533
- frame(d)
534
- }
535
- live = (fakeNet() ? fake : browser)(take, c => {
536
- code = c
537
- done()
538
- })
539
- alive()
540
- if (!fakeNet()) ping = setInterval(() => send(['p']), PING)
541
- })
542
- clearTimeout(dead)
543
- clearInterval(ping)
544
- live = undefined
545
- open = false
546
- for (const j of joins.values()) j.joined = false
547
- for (const [id, p] of acks) {
548
- acks.delete(id)
549
- p.no(new FnError({ message: 'the connection dropped: this may or may not have been sent' }, 503))
550
- }
551
- if (!joins.size) break
552
- const n = fakeNet()
553
- if (n) n.reconnects++
554
- if (code === 4401) for (const j of joins.values()) j.status.value = 'unauthorized'
555
- else statusAll('reconnecting')
556
- if (!n) await sleep(code === HANDOVER ? 0 : backoff())
230
+ void track(
231
+ new Promise<void>((ok) => {
232
+ up = ok
233
+ }),
234
+ )
235
+ const loading = import(/* @vite-ignore */ FAKE)
236
+ .then((m) => m.open(onFrame, closed, up))
237
+ .then(
238
+ (l) => (link = l),
239
+ (e) => (up(), closed(1006), Promise.reject(e)),
240
+ )
241
+ .catch(() => {})
242
+ return {
243
+ send: (t) => void track(loading.then(() => link?.send(t))),
244
+ close: () => {
245
+ void loading.then(() => link?.close())
246
+ },
557
247
  }
558
- running = false
559
- attempt = 0
560
- listen(false)
561
248
  }
562
249
 
563
- /** Full jitter, 0.5 s doubling to 30 s (research 30 §6). */
564
- const backoff = () => Math.random() * Math.min(CAP, BASE * 2 ** attempt++)
565
-
566
- // ---- the page -------------------------------------------------------------------------------------------------------
567
-
568
- const wake = () => {
569
- parked = false
570
- nudge?.()
571
- }
572
- function park() {
573
- parked = true
574
- live?.close()
575
- }
576
- const parkHidden = () => {
577
- if (keepOpen.stay?.()) hiddenAt = setTimeout(parkHidden, HIDDEN)
578
- else park()
579
- }
580
- function onVisibility() {
581
- clearTimeout(hiddenAt)
582
- if (document.visibilityState === 'hidden') hiddenAt = setTimeout(parkHidden, HIDDEN)
583
- else wake()
584
- }
585
- /** A sibling came back while this tab's socket was parked. */
586
- export const wakeSocket = () => wake()
587
- const onOffline = () => {
588
- socketDown()
589
- live?.close()
590
- }
591
-
592
- function listen(on: boolean) {
593
- if (typeof window === 'undefined') return
594
- const m = on ? 'addEventListener' : 'removeEventListener'
595
- window[m]('online', wake)
596
- window[m]('offline', onOffline)
597
- window[m]('pagehide', park)
598
- window[m]('pageshow', wake)
599
- document[m]('visibilitychange', onVisibility)
600
- if (!on) clearTimeout(hiddenAt)
601
- }
602
-
603
- /** @weft-js/core/test, after each test. */
604
- function reset() {
605
- for (const j of joins.values()) clearTimeout(j.timer)
606
- joins.clear()
607
- byN.clear()
608
- acks.clear()
609
- live?.close()
610
- nudge?.()
611
- build = undefined
612
- parked = false
613
- attempt = 0
614
- net()!.reconnects = 0
615
- untrack(() => { rt.stale.value = false })
616
- }
250
+ setFake(fake)