@playfast/reform-proof 1.1.1 → 1.2.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.
@@ -1,285 +0,0 @@
1
- import { Array as Arr, Effect, Match, Option, Order, Record as Rec, Schema as S } from 'effect'
2
- import {
3
- Composition,
4
- type CompositionClass,
5
- isFeatureBinding,
6
- isStructure,
7
- type RenderEnv,
8
- type RuntimeHandle,
9
- } from '@playfast/reform'
10
- import { eventsOf, type Sink, uiNameOf } from './sink'
11
- import { slotsOf, structureFills } from './treeBindings'
12
- import { disposeTreeMounts } from './runtimeTreeDispose'
13
- import { makeTreeSettle } from './runtimeTreeSettle'
14
- import {
15
- encodeIdentityPart,
16
- type FeatureRecordInput,
17
- fillEntries,
18
- type MountIdentityInput,
19
- type RenderCompositionInput,
20
- type TreeDriver,
21
- type TreeFeatureMount,
22
- type TreeNode,
23
- type TreeRenderState,
24
- treeFingerprint,
25
- } from './runtimeTreeTypes'
26
-
27
- const encodeUnknown = S.encodeSync(S.parseJson(S.Unknown))
28
-
29
- export const makeTreeDriver = (
30
- runtime: RuntimeHandle,
31
- root: CompositionClass<unknown>,
32
- sink: Sink,
33
- ): TreeDriver => {
34
- const mounts = new Map<string, TreeFeatureMount>()
35
- const runtimeIds = new WeakMap<RuntimeHandle, number>()
36
- const bindingIds = new WeakMap<object, number>()
37
- const sequence = { runtime: 0, binding: 0 }
38
- const status = { disposed: false }
39
-
40
- const identity = (
41
- identities: WeakMap<object, number>,
42
- subject: object,
43
- next: () => number,
44
- ): number => {
45
- const current = identities.get(subject)
46
- if (current !== undefined) {
47
- return current
48
- }
49
- const created = next()
50
- identities.set(subject, created)
51
- return created
52
- }
53
-
54
- const mountId = ({ parent, parentPath, slotName, key, binding }: MountIdentityInput): string => {
55
- const runtimeId = identity(runtimeIds, parent, () => ++sequence.runtime)
56
- const bindingId = identity(bindingIds, binding, () => ++sequence.binding)
57
- return [String(runtimeId), parentPath, slotName, String(bindingId), key]
58
- .map(encodeIdentityPart)
59
- .join('')
60
- }
61
-
62
- const startMount = (record: TreeFeatureMount): void => {
63
- record.attempt += 1
64
- const attempt = record.attempt
65
- if (record.binding.strategy === 'default') {
66
- record.state = { _tag: 'Live', runtime: record.parent }
67
- record.binding.boot.forEach((event) => record.parent.dispatch('High', event))
68
- record.dispose = () => {}
69
- return
70
- }
71
- record.state = { _tag: 'Loading' }
72
- record.dispose = record.parent.mountFeature(record.binding, {
73
- props: record.props,
74
- onLive: (childRuntime) => {
75
- if (status.disposed || record.attempt !== attempt || mounts.get(record.id) !== record) {
76
- return
77
- }
78
- record.state = { _tag: 'Live', runtime: childRuntime }
79
- },
80
- onFailed: (error) => {
81
- if (status.disposed || record.attempt !== attempt || mounts.get(record.id) !== record) {
82
- return
83
- }
84
- record.state = { _tag: 'Failed', error }
85
- },
86
- })
87
- }
88
-
89
- const retryMount = (record: TreeFeatureMount): void => {
90
- if (status.disposed || mounts.get(record.id) !== record || record.state._tag !== 'Failed') {
91
- return
92
- }
93
- record.dispose()
94
- startMount(record)
95
- }
96
-
97
- const featureRecord = ({
98
- id,
99
- parent,
100
- binding,
101
- depth,
102
- props,
103
- }: FeatureRecordInput): TreeFeatureMount => {
104
- const current = mounts.get(id)
105
- if (current !== undefined && current.binding === binding && current.parent === parent) {
106
- return current
107
- }
108
- if (current !== undefined) {
109
- current.attempt += 1
110
- current.dispose()
111
- }
112
- const created: TreeFeatureMount = {
113
- id,
114
- binding,
115
- parent,
116
- depth,
117
- props,
118
- attempt: 0,
119
- state: { _tag: 'Loading' },
120
- dispose: () => {},
121
- }
122
- mounts.set(id, created)
123
- startMount(created)
124
- return created
125
- }
126
-
127
- const renderComposition = ({
128
- runtime: currentRuntime,
129
- comp,
130
- props,
131
- key,
132
- path,
133
- depth,
134
- seen,
135
- }: RenderCompositionInput): TreeNode => {
136
- const service = currentRuntime.read(comp.tag)
137
- const env: RenderEnv = { props, tracker: { add: () => {} } }
138
- const endRenderSpan = sink.instrumentation.uiRendered(uiNameOf(comp))
139
- const frame = Effect.runSync(Composition.render(service, env))
140
- endRenderSpan()
141
- if (!isStructure(frame)) {
142
- return Effect.runSync(
143
- Effect.dieMessage(`reform-proof: composition ${uiNameOf(comp)} did not return a Structure`),
144
- )
145
- }
146
- sink.api.record({
147
- name: uiNameOf(comp),
148
- props: frame.props,
149
- events: eventsOf(frame),
150
- ...(Option.isSome(key) ? { key: key.value } : {}),
151
- })
152
-
153
- const fills = structureFills(frame)
154
- const renderedSlots = Rec.map(slotsOf(comp), (slotClass, slotName) => {
155
- const fill = fills[slotName]
156
- if (fill === undefined) {
157
- return []
158
- }
159
- const child = currentRuntime.read(slotClass.tag)
160
- return fillEntries(slotName, fill).flatMap((entry) => {
161
- const childPath = `${path}${encodeIdentityPart(slotName)}${encodeIdentityPart(entry.key)}`
162
- if (!isFeatureBinding(child)) {
163
- return [
164
- renderComposition({
165
- runtime: currentRuntime,
166
- comp: child,
167
- props: entry.props,
168
- key: Option.some(entry.key),
169
- path: childPath,
170
- depth: depth + 1,
171
- seen,
172
- }),
173
- ]
174
- }
175
- const id = mountId({
176
- parent: currentRuntime,
177
- parentPath: path,
178
- slotName,
179
- key: entry.key,
180
- binding: child,
181
- })
182
- seen.add(id)
183
- const record = featureRecord({
184
- id,
185
- parent: currentRuntime,
186
- binding: child,
187
- depth: depth + 1,
188
- props: entry.props,
189
- })
190
- return Match.value(record.state).pipe(
191
- Match.when({ _tag: 'Live' }, (live) => [
192
- renderComposition({
193
- runtime: live.runtime,
194
- comp: child.composition,
195
- props: entry.props,
196
- key: Option.some(entry.key),
197
- path: childPath,
198
- depth: depth + 1,
199
- seen,
200
- }),
201
- ]),
202
- Match.when({ _tag: 'Failed' }, (failed) => {
203
- if (child.placeholder === undefined) {
204
- return []
205
- }
206
- return [
207
- renderComposition({
208
- runtime: currentRuntime,
209
- comp: child.placeholder.failed,
210
- props: { error: failed.error, retry: () => retryMount(record) },
211
- key: Option.some(entry.key),
212
- path: `${childPath}/failed`,
213
- depth: depth + 1,
214
- seen,
215
- }),
216
- ]
217
- }),
218
- Match.when({ _tag: 'Loading' }, () => {
219
- if (child.placeholder === undefined) {
220
- return []
221
- }
222
- return [
223
- renderComposition({
224
- runtime: currentRuntime,
225
- comp: child.placeholder.loading,
226
- props: entry.props,
227
- key: Option.some(entry.key),
228
- path: `${childPath}/loading`,
229
- depth: depth + 1,
230
- seen,
231
- }),
232
- ]
233
- }),
234
- Match.exhaustive,
235
- )
236
- })
237
- })
238
-
239
- return {
240
- path,
241
- depth,
242
- key,
243
- comp,
244
- props: frame.props,
245
- events: eventsOf(frame),
246
- slots: renderedSlots,
247
- }
248
- }
249
-
250
- const disposeStale = (seen: ReadonlySet<string>): void => {
251
- Arr.sortWith(
252
- Array.from(mounts.values()).filter((record) => !seen.has(record.id)),
253
- (record) => -record.depth,
254
- Order.number,
255
- ).forEach((record) => {
256
- mounts.delete(record.id)
257
- record.attempt += 1
258
- record.dispose()
259
- })
260
- }
261
-
262
- const render = (): TreeRenderState => {
263
- sink.reset()
264
- const seen = new Set<string>()
265
- const rootNode = renderComposition({
266
- runtime,
267
- comp: root,
268
- props: {},
269
- key: Option.none(),
270
- path: 'root',
271
- depth: 0,
272
- seen,
273
- })
274
- disposeStale(seen)
275
- return {
276
- root: rootNode,
277
- fingerprint: encodeUnknown(treeFingerprint(rootNode)),
278
- }
279
- }
280
-
281
- const settle = makeTreeSettle(render)
282
- const dispose = (): void => disposeTreeMounts({ status, mounts })
283
-
284
- return { render, settle, dispose }
285
- }
@@ -1,134 +0,0 @@
1
- import { Array as Arr, Effect, Option } from 'effect'
2
- import type { CompositionClass, RuntimeHandle } from '@playfast/reform'
3
- import { AssertionFailed, UnknownAction, UnknownSlot } from './errors'
4
- import { matchProps } from './assertions'
5
- import { makeTreeDriver } from './runtimeTreeDriver'
6
- import type { RuntimeTreeFacade, TreeNode } from './runtimeTreeTypes'
7
- import { keyed, type Sink, uiNameOf } from './sink'
8
- import type { MountedFacade, MountedSlotFacade } from './runtimeFacade'
9
-
10
- export type { RuntimeTreeFacade } from './runtimeTreeTypes'
11
-
12
- export const makeRuntimeTreeFacade = (
13
- runtime: RuntimeHandle,
14
- root: CompositionClass<unknown>,
15
- sink: Sink,
16
- dispatched: Set<string>,
17
- ): RuntimeTreeFacade => {
18
- const driver = makeTreeDriver(runtime, root, sink)
19
- const currentRoot = (): TreeNode => driver.render().root
20
-
21
- const nodeFacade = (resolve: () => TreeNode): MountedFacade => ({
22
- props: Effect.sync(() => resolve().props),
23
- expectProps: (partial) =>
24
- Effect.sync(() => {
25
- const mismatch = matchProps({
26
- actual: resolve().props,
27
- expected: partial,
28
- })
29
- if (mismatch !== undefined) {
30
- return Effect.runSync(
31
- Effect.dieMessage(new AssertionFailed({ detail: mismatch }).message),
32
- )
33
- }
34
- }),
35
- actions: keyed(
36
- (event) => (payload: unknown) =>
37
- Effect.gen(function* () {
38
- const node = resolve()
39
- const trigger = node.events[event]
40
- if (trigger === undefined) {
41
- return yield* Effect.dieMessage(
42
- new UnknownAction({
43
- composition: uiNameOf(node.comp),
44
- action: event,
45
- rendered: 1,
46
- }).message,
47
- )
48
- }
49
- dispatched.add(event)
50
- trigger(payload)
51
- yield* driver.settle
52
- return resolve().props
53
- }),
54
- ),
55
- slots: keyed((slotName) => slotFacade(resolve, slotName)),
56
- frame: driver.settle,
57
- })
58
-
59
- const slotFacade = (resolveParent: () => TreeNode, slotName: string): MountedSlotFacade => {
60
- const children = (): ReadonlyArray<TreeNode> => {
61
- const parent = resolveParent()
62
- const resolved = parent.slots[slotName]
63
- if (resolved === undefined) {
64
- return Effect.runSync(
65
- Effect.dieMessage(
66
- new UnknownSlot({ parent: uiNameOf(parent.comp), slot: slotName }).message,
67
- ),
68
- )
69
- }
70
- return resolved
71
- }
72
- const childAt = (index: number): MountedFacade =>
73
- nodeFacade(() => children()[index] ?? missingChild(index))
74
- const childByKey = (key: string): MountedFacade =>
75
- nodeFacade(() => {
76
- return Option.getOrElse(
77
- Arr.findFirst(children(), (candidate) => Option.contains(candidate.key, key)),
78
- () => missingKey(key),
79
- )
80
- })
81
- const missingChild = (index: number): never => {
82
- const parent = resolveParent()
83
- return Effect.runSync(
84
- Effect.dieMessage(
85
- new UnknownSlot({
86
- parent: uiNameOf(parent.comp),
87
- slot: `${slotName}[${index}]`,
88
- }).message,
89
- ),
90
- )
91
- }
92
- const missingKey = (key: string): never => {
93
- const parent = resolveParent()
94
- return Effect.runSync(
95
- Effect.dieMessage(
96
- new UnknownSlot({
97
- parent: uiNameOf(parent.comp),
98
- slot: `${slotName}[key=${key}]`,
99
- }).message,
100
- ),
101
- )
102
- }
103
- const first = childAt(0)
104
- return {
105
- first: Effect.sync(() => childAt(0)),
106
- at: (index) => Effect.sync(() => childAt(index)),
107
- all: Effect.sync(() => children().map((_child, index) => childAt(index))),
108
- byKey: (key) =>
109
- Effect.sync(() => {
110
- const child = Arr.findFirst(children(), (candidate) =>
111
- Option.contains(candidate.key, key),
112
- )
113
- return Option.isNone(child) ? missingKey(key) : childByKey(key)
114
- }),
115
- where: (predicate) =>
116
- Effect.sync(() =>
117
- children().flatMap((child, index) => (predicate(child.props) ? [childAt(index)] : [])),
118
- ),
119
- count: Effect.sync(() => children().length),
120
- props: first.props,
121
- expectProps: first.expectProps,
122
- actions: first.actions,
123
- slots: first.slots,
124
- frame: driver.settle,
125
- }
126
- }
127
-
128
- return {
129
- facade: nodeFacade(currentRoot),
130
- settle: driver.settle,
131
- dispose: driver.dispose,
132
- }
133
- }
134
-
@@ -1,34 +0,0 @@
1
- import { Effect } from 'effect'
2
- import { SETTLE_MAX_RENDERS, SETTLE_STEP, settleDrain } from './sink'
3
- import type { SettleProgress } from './treeBindings'
4
- import type { TreeRenderState } from './runtimeTreeTypes'
5
-
6
- export const makeTreeSettle: (
7
- render: () => TreeRenderState,
8
- ) => Effect.Effect<void, never, never> = Effect.fn('makeTreeSettle')(function* (
9
- render: () => TreeRenderState,
10
- ): Effect.fn.Return<void, never, never> {
11
- yield* settleDrain
12
- const first = render()
13
- yield* Effect.iterate(
14
- {
15
- previous: first.fingerprint,
16
- remaining: SETTLE_MAX_RENDERS,
17
- stable: false,
18
- },
19
- {
20
- while: (progress: SettleProgress) => !progress.stable && progress.remaining > 0,
21
- body: (progress) =>
22
- Effect.gen(function* () {
23
- yield* settleDrain
24
- yield* Effect.sleep(SETTLE_STEP)
25
- const current = render()
26
- return {
27
- previous: current.fingerprint,
28
- remaining: progress.remaining - 1,
29
- stable: current.fingerprint === progress.previous,
30
- }
31
- }),
32
- },
33
- )
34
- })
@@ -1,99 +0,0 @@
1
- import { Effect, Match, Option, Record as Rec } from 'effect'
2
- import {
3
- type CompositionClass,
4
- type FeatureBinding,
5
- type RuntimeHandle,
6
- type SlotFill,
7
- type Trigger,
8
- } from '@playfast/reform'
9
- import type { MountedFacade } from './runtimeFacade'
10
- import { uiNameOf } from './sink'
11
-
12
- export type FeatureMountState =
13
- | { readonly _tag: 'Loading' }
14
- | { readonly _tag: 'Live'; readonly runtime: RuntimeHandle }
15
- | { readonly _tag: 'Failed'; readonly error: unknown }
16
-
17
- export interface TreeFeatureMount {
18
- readonly id: string
19
- readonly binding: FeatureBinding
20
- readonly parent: RuntimeHandle
21
- readonly depth: number
22
- readonly props: unknown
23
- attempt: number
24
- state: FeatureMountState
25
- dispose: () => void
26
- }
27
-
28
- export interface TreeNode {
29
- readonly path: string
30
- readonly depth: number
31
- readonly key: Option.Option<string>
32
- readonly comp: CompositionClass<unknown>
33
- readonly props: unknown
34
- readonly events: Record<string, Trigger<unknown>>
35
- readonly slots: Readonly<Record<string, ReadonlyArray<TreeNode>>>
36
- }
37
-
38
- export interface TreeRenderState {
39
- readonly root: TreeNode
40
- readonly fingerprint: string
41
- }
42
-
43
- export interface RuntimeTreeFacade {
44
- readonly facade: MountedFacade
45
- readonly settle: Effect.Effect<void, never, never>
46
- dispose(): void
47
- }
48
-
49
- export interface TreeDriver {
50
- readonly render: () => TreeRenderState
51
- readonly settle: Effect.Effect<void, never, never>
52
- readonly dispose: () => void
53
- }
54
-
55
- export interface MountIdentityInput {
56
- readonly parent: RuntimeHandle
57
- readonly parentPath: string
58
- readonly slotName: string
59
- readonly key: string
60
- readonly binding: FeatureBinding
61
- }
62
-
63
- export interface FeatureRecordInput {
64
- readonly id: string
65
- readonly parent: RuntimeHandle
66
- readonly binding: FeatureBinding
67
- readonly depth: number
68
- readonly props: unknown
69
- }
70
-
71
- export interface RenderCompositionInput {
72
- readonly runtime: RuntimeHandle
73
- readonly comp: CompositionClass<unknown>
74
- readonly props: unknown
75
- readonly key: Option.Option<string>
76
- readonly path: string
77
- readonly depth: number
78
- readonly seen: Set<string>
79
- }
80
-
81
- export const encodeIdentityPart = (part: string): string => `${part.length}:${part}`
82
-
83
- export const fillEntries = (
84
- slotName: string,
85
- fill: SlotFill<unknown>,
86
- ): ReadonlyArray<{ readonly key: string; readonly props: unknown }> =>
87
- Match.value(fill).pipe(
88
- Match.when({ _tag: 'Each' }, (each) => each.items),
89
- Match.when({ _tag: 'One' }, (oneFill) => [{ key: `${slotName}.0`, props: oneFill.props }]),
90
- Match.when({ _tag: 'Absent' }, () => []),
91
- Match.exhaustive,
92
- )
93
-
94
- export const treeFingerprint = (node: TreeNode): unknown => [
95
- uiNameOf(node.comp),
96
- node.key,
97
- node.props,
98
- Rec.map(node.slots, (children) => children.map(treeFingerprint)),
99
- ]
package/src/sink.ts DELETED
@@ -1,73 +0,0 @@
1
- import { Effect, Layer, MutableRef } from 'effect'
2
- import {
3
- Bus,
4
- CaptureSink,
5
- type CaptureSinkApi,
6
- type CompositionClass,
7
- type CompositionService,
8
- type Instrumentation,
9
- noopInstrumentation,
10
- type Scene,
11
- type SlotChild,
12
- type Structure,
13
- type Trigger,
14
- type UiCapture,
15
- type UiContract,
16
- } from '@playfast/reform'
17
-
18
- const SETTLE_DRAIN = 30
19
- export const SETTLE_STEP = '1 milli'
20
- export const SETTLE_MAX_RENDERS = 100
21
-
22
- export const settleDrain: Effect.Effect<void> = Effect.yieldNow().pipe(Effect.repeatN(SETTLE_DRAIN))
23
-
24
- export const keyed = <V>(get: (key: string) => V): Record<string, V> => {
25
- const target: Record<string, V> = Object.create(null)
26
- return new Proxy(target, { get: (_target, key) => get(String(key)) })
27
- }
28
-
29
- export const messageOf = (error: unknown): string =>
30
- error instanceof Error ? error.message : String(error)
31
-
32
- export const uiNameOf = (comp: CompositionClass<unknown>): string => comp.manifest.ui.manifest.name
33
-
34
- export const eventsOf = (structure: Structure<UiContract>): Record<string, Trigger<unknown>> => ({
35
- ...structure.events,
36
- })
37
-
38
- export interface Sink {
39
- readonly api: CaptureSinkApi
40
- readonly captures: ReadonlyArray<UiCapture>
41
- readonly instrumentation: Instrumentation
42
- reset(): void
43
- }
44
-
45
- export const makeSink = (instrumentation: Instrumentation = noopInstrumentation): Sink => {
46
- const captures = MutableRef.make<UiCapture[]>([])
47
- return {
48
- api: {
49
- record: (capture) => {
50
- MutableRef.update(captures, (current) => [...current, capture])
51
- },
52
- },
53
- get captures() {
54
- return MutableRef.get(captures)
55
- },
56
- instrumentation,
57
- reset: () => {
58
- MutableRef.set(captures, [])
59
- },
60
- }
61
- }
62
-
63
- export type RuntimeServices = CompositionService | SlotChild | Bus
64
-
65
- export const proofLayer = (scene: Scene, sink: Sink): Layer.Layer<RuntimeServices, never, never> => {
66
- // oxlint-disable-next-line reform-rules/no-type-assertion -- the one erasure boundary: the scene's host-read `MountedServices` layer widens to the broader `RuntimeServices` a proof resolves
67
- const sceneLayer = scene.provide.reduce((merged, layer) => Layer.merge(merged, layer)) as unknown as Layer.Layer<
68
- RuntimeServices,
69
- never,
70
- never
71
- >
72
- return Layer.provideMerge(sceneLayer, Layer.succeed(CaptureSink, sink.api))
73
- }