@yaks/browse 0.0.0-stage → 0.2.36

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 (271) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +324 -2
  3. package/_dist/app.d.ts +8 -0
  4. package/_dist/app.d.ts.map +1 -0
  5. package/_dist/cli.d.ts +16 -0
  6. package/_dist/cli.d.ts.map +1 -0
  7. package/_dist/hosting.d.ts +24 -0
  8. package/_dist/hosting.d.ts.map +1 -0
  9. package/_dist/mod.d.ts +7 -0
  10. package/_dist/mod.d.ts.map +1 -0
  11. package/_dist/types.d.ts +5 -0
  12. package/_dist/types.d.ts.map +1 -0
  13. package/_dist/url.d.ts +2 -0
  14. package/_dist/url.d.ts.map +1 -0
  15. package/app.js +10 -0
  16. package/app.js.map +1 -0
  17. package/app.ts +10 -0
  18. package/browser-links.js +22 -0
  19. package/browser-links.js.map +1 -0
  20. package/browser-links.ts +28 -0
  21. package/cli.js +172 -0
  22. package/cli.js.map +1 -0
  23. package/cli.ts +168 -0
  24. package/client.js +748 -0
  25. package/client.js.map +1 -0
  26. package/client.ts +734 -0
  27. package/clipboard.js +18 -0
  28. package/clipboard.js.map +1 -0
  29. package/clipboard.ts +17 -0
  30. package/commands.js +1157 -0
  31. package/commands.js.map +1 -0
  32. package/commands.ts +1108 -0
  33. package/components/Ansi.tsx +160 -0
  34. package/components/App.tsx +446 -0
  35. package/components/Canvas.tsx +625 -0
  36. package/components/Card.tsx +276 -0
  37. package/components/Chat.tsx +205 -0
  38. package/components/Configuration.tsx +218 -0
  39. package/components/Decision.tsx +49 -0
  40. package/components/Dot.tsx +52 -0
  41. package/components/Entity.tsx +609 -0
  42. package/components/Fault.tsx +43 -0
  43. package/components/Filter.tsx +103 -0
  44. package/components/Keybindings.tsx +100 -0
  45. package/components/Keys.tsx +67 -0
  46. package/components/Markdown.tsx +90 -0
  47. package/components/Navigation.tsx +161 -0
  48. package/components/New.tsx +490 -0
  49. package/components/Peek.tsx +168 -0
  50. package/components/Prio.tsx +20 -0
  51. package/components/Run.tsx +263 -0
  52. package/components/Search.tsx +280 -0
  53. package/components/Stamp.tsx +44 -0
  54. package/components/Status.tsx +514 -0
  55. package/components/Sync.tsx +173 -0
  56. package/components/Tile.tsx +50 -0
  57. package/components/answered.js +23 -0
  58. package/components/answered.js.map +1 -0
  59. package/components/answered.ts +25 -0
  60. package/components/comp.js +11 -0
  61. package/components/comp.js.map +1 -0
  62. package/components/comp.ts +10 -0
  63. package/components/drag.js +173 -0
  64. package/components/drag.js.map +1 -0
  65. package/components/drag.ts +198 -0
  66. package/components/fields.tsx +90 -0
  67. package/components/fixtures/README.md +10 -0
  68. package/components/fixtures/archetypes.json +3646 -0
  69. package/components/hits.js +63 -0
  70. package/components/hits.js.map +1 -0
  71. package/components/hits.ts +84 -0
  72. package/components/icons.tsx +177 -0
  73. package/components/inspect.tsx +331 -0
  74. package/components/mount.ts +79 -0
  75. package/components/nav.tsx +479 -0
  76. package/components/offers.js +26 -0
  77. package/components/offers.js.map +1 -0
  78. package/components/offers.ts +54 -0
  79. package/components/page.js +21 -0
  80. package/components/page.js.map +1 -0
  81. package/components/page.ts +18 -0
  82. package/components/read.js +5 -0
  83. package/components/read.js.map +1 -0
  84. package/components/read.ts +7 -0
  85. package/components/registry.js +285 -0
  86. package/components/registry.js.map +1 -0
  87. package/components/registry.ts +317 -0
  88. package/components/session_status.tsx +115 -0
  89. package/components/subscriptions.js +149 -0
  90. package/components/subscriptions.js.map +1 -0
  91. package/components/subscriptions.ts +161 -0
  92. package/components/title.tsx +21 -0
  93. package/components/useQuery.js +166 -0
  94. package/components/useQuery.js.map +1 -0
  95. package/components/useQuery.ts +211 -0
  96. package/components/views/Board.tsx +450 -0
  97. package/components/views/BoardTile.tsx +65 -0
  98. package/components/views/Dashboard.tsx +148 -0
  99. package/components/views/Debug.tsx +445 -0
  100. package/components/views/Dependency.tsx +51 -0
  101. package/components/views/Entry.tsx +500 -0
  102. package/components/views/Gist.tsx +28 -0
  103. package/components/views/Inline.tsx +54 -0
  104. package/components/views/Json.tsx +19 -0
  105. package/components/views/Layout.tsx +211 -0
  106. package/components/views/List.tsx +238 -0
  107. package/components/views/Md.tsx +43 -0
  108. package/components/views/Media.tsx +48 -0
  109. package/components/views/Memory.tsx +32 -0
  110. package/components/views/Relate.tsx +205 -0
  111. package/components/views/Search.tsx +42 -0
  112. package/components/views/Session.tsx +850 -0
  113. package/components/views/SessionManage.tsx +127 -0
  114. package/components/views/Show.tsx +758 -0
  115. package/components/views/Shown.tsx +72 -0
  116. package/components/views/Split.tsx +58 -0
  117. package/components/views/TaskTile.tsx +37 -0
  118. package/components/views/Title.tsx +105 -0
  119. package/components/views/Wake.tsx +77 -0
  120. package/components/views/Web.tsx +49 -0
  121. package/components/wells.js +30 -0
  122. package/components/wells.js.map +1 -0
  123. package/components/wells.ts +33 -0
  124. package/configuration.js +38 -0
  125. package/configuration.js.map +1 -0
  126. package/configuration.ts +41 -0
  127. package/decision_sync.js +88 -0
  128. package/decision_sync.js.map +1 -0
  129. package/decision_sync.ts +93 -0
  130. package/deno.json +1 -0
  131. package/domain-host.tsx +108 -0
  132. package/edge.js +193 -0
  133. package/edge.js.map +1 -0
  134. package/edge.ts +196 -0
  135. package/entry_log.js +241 -0
  136. package/entry_log.js.map +1 -0
  137. package/entry_log.ts +214 -0
  138. package/failure.js +22 -0
  139. package/failure.js.map +1 -0
  140. package/failure.ts +34 -0
  141. package/front.json +61 -0
  142. package/highlight.js +143 -0
  143. package/highlight.js.map +1 -0
  144. package/highlight.ts +149 -0
  145. package/history.js +68 -0
  146. package/history.js.map +1 -0
  147. package/history.ts +72 -0
  148. package/host_commands.js +107 -0
  149. package/host_commands.js.map +1 -0
  150. package/host_commands.ts +38 -0
  151. package/hosting.js +53 -0
  152. package/hosting.js.map +1 -0
  153. package/hosting.ts +72 -0
  154. package/idb.js +14 -0
  155. package/idb.js.map +1 -0
  156. package/idb.ts +15 -0
  157. package/index.js +232 -0
  158. package/index.js.map +1 -0
  159. package/index.ts +252 -0
  160. package/keybindings.js +136 -0
  161. package/keybindings.js.map +1 -0
  162. package/keybindings.ts +37 -0
  163. package/kit.js +103 -0
  164. package/kit.js.map +1 -0
  165. package/kit.ts +119 -0
  166. package/layout.js +254 -0
  167. package/layout.js.map +1 -0
  168. package/layout.ts +210 -0
  169. package/legacy_outbox.js +53 -0
  170. package/legacy_outbox.js.map +1 -0
  171. package/legacy_outbox.ts +63 -0
  172. package/live.js +2883 -0
  173. package/live.js.map +1 -0
  174. package/live.ts +3334 -0
  175. package/live_archetypes.js +92 -0
  176. package/live_archetypes.js.map +1 -0
  177. package/live_archetypes.ts +113 -0
  178. package/live_client.js +145 -0
  179. package/live_client.js.map +1 -0
  180. package/live_client.ts +120 -0
  181. package/main.tsx +5 -0
  182. package/mod.js +7 -0
  183. package/mod.js.map +1 -0
  184. package/mod.ts +7 -0
  185. package/mount.tsx +50 -0
  186. package/navigation.js +120 -0
  187. package/navigation.js.map +1 -0
  188. package/navigation.ts +152 -0
  189. package/near.js +83 -0
  190. package/near.js.map +1 -0
  191. package/near.ts +83 -0
  192. package/new.js +295 -0
  193. package/new.js.map +1 -0
  194. package/new.ts +361 -0
  195. package/outbox.js +112 -0
  196. package/outbox.js.map +1 -0
  197. package/outbox.ts +129 -0
  198. package/owner.js +39 -0
  199. package/owner.js.map +1 -0
  200. package/owner.ts +37 -0
  201. package/package.json +81 -4
  202. package/paste.js +157 -0
  203. package/paste.js.map +1 -0
  204. package/paste.ts +122 -0
  205. package/props.js +303 -0
  206. package/props.js.map +1 -0
  207. package/props.ts +358 -0
  208. package/providers.js +136 -0
  209. package/providers.js.map +1 -0
  210. package/providers.ts +194 -0
  211. package/query.js +987 -0
  212. package/query.js.map +1 -0
  213. package/query.ts +1113 -0
  214. package/remote.js +37 -0
  215. package/remote.js.map +1 -0
  216. package/remote.ts +46 -0
  217. package/resolver.js +149 -0
  218. package/resolver.js.map +1 -0
  219. package/resolver.ts +213 -0
  220. package/rfc2047.js +37 -0
  221. package/rfc2047.js.map +1 -0
  222. package/rfc2047.ts +40 -0
  223. package/row_holds.js +107 -0
  224. package/row_holds.js.map +1 -0
  225. package/row_holds.ts +93 -0
  226. package/served.ts +42 -0
  227. package/session_worktree.js +7 -0
  228. package/session_worktree.js.map +1 -0
  229. package/session_worktree.ts +16 -0
  230. package/sessions.js +57 -0
  231. package/sessions.js.map +1 -0
  232. package/sessions.ts +53 -0
  233. package/sha.js +161 -0
  234. package/sha.js.map +1 -0
  235. package/sha.ts +164 -0
  236. package/styles.css +2823 -0
  237. package/subs.js +36 -0
  238. package/subs.js.map +1 -0
  239. package/subs.ts +40 -0
  240. package/terminal-route.js +13 -0
  241. package/terminal-route.js.map +1 -0
  242. package/terminal-route.ts +17 -0
  243. package/terminal.js +251 -0
  244. package/terminal.js.map +1 -0
  245. package/terminal.ts +186 -0
  246. package/time.js +142 -0
  247. package/time.js.map +1 -0
  248. package/time.ts +133 -0
  249. package/title.js +25 -0
  250. package/title.js.map +1 -0
  251. package/title.ts +50 -0
  252. package/tui/doc.ts +6 -0
  253. package/tui/testing.ts +19 -0
  254. package/twin.js +11 -0
  255. package/twin.js.map +1 -0
  256. package/twin.ts +13 -0
  257. package/types.js +456 -0
  258. package/types.js.map +1 -0
  259. package/types.ts +1370 -0
  260. package/url.js +77 -0
  261. package/url.js.map +1 -0
  262. package/url.ts +85 -0
  263. package/verb.js +82 -0
  264. package/verb.js.map +1 -0
  265. package/verb.ts +137 -0
  266. package/warmth.js +41 -0
  267. package/warmth.js.map +1 -0
  268. package/warmth.ts +54 -0
  269. package/wire.js +86 -0
  270. package/wire.js.map +1 -0
  271. package/wire.ts +63 -0
package/new.ts ADDED
@@ -0,0 +1,361 @@
1
+ // New entities, sketched before they are made. A sketch is what a person has
2
+ // typed toward them: the components chosen, the text typed in each property,
3
+ // and an outline whose lines become more entities, nested by `contains`. It is
4
+ // the person's draft (@yaks/draft), so it is kept as it is typed and seen in
5
+ // every interface; the batch it writes is derived from it here, whole, so it
6
+ // can be shown before it is sent. The batch names what it makes by alias
7
+ // (`$1`), and the graph mints each id, or derives it where a component's
8
+ // identity says (a link's ends and relation), so the page never guesses one.
9
+ //
10
+ // Nothing here reads the page: the vocabulary, and a reader for typed text,
11
+ // are handed in.
12
+ import type { Bundle, Comp } from 'jsr:@yaks/graph@0.2.36'
13
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
14
+
15
+ /** What a person has typed toward new entities: each component chosen, with
16
+ * the text typed in each of its properties, and an outline. */
17
+ export type Sketch = {
18
+ comps: Record<string, Record<string, string>>
19
+ outline: string
20
+ }
21
+
22
+ /** Where a sketch is made: in an entity (`contains`), like another. Each is
23
+ * an eid. */
24
+ export type At = { in?: string; like?: string }
25
+
26
+ /** The draft a sketch is kept in: one per place it is made from.
27
+ *
28
+ * ```ts
29
+ * import { equal } from '@yaks/testing'
30
+ * equal(placeOf({}), 'new')
31
+ * equal(placeOf({ in: 'p', like: 'l' }), 'new:in:p:like:l')
32
+ * ```
33
+ */
34
+ export let placeOf = (at: At): string =>
35
+ [
36
+ 'new',
37
+ ...(at.in ? ['in', at.in] : []),
38
+ ...(at.like ? ['like', at.like] : []),
39
+ ].join(':')
40
+
41
+ /// sketchOf('') -> undefined
42
+ /// sketchOf('{"comps":{"task":{}},"outline":"a"}') -> {comps: {task: {}}, outline: 'a'}
43
+ export let sketchOf = (text: string): Sketch | undefined => {
44
+ if (!text) return undefined
45
+ let s = JSON.parse(text) as Partial<Sketch>
46
+ return { comps: s.comps ?? {}, outline: s.outline ?? '' }
47
+ }
48
+
49
+ /** A sketch as its draft's text. */
50
+ export let textOf = (s: Sketch): string => JSON.stringify(s)
51
+
52
+ // What a client may write: never the spine, never a word only the server
53
+ // writes.
54
+ let writable = (v: Vocab, name: string) =>
55
+ name != 'entity' && !!v.comp(name)?.wire
56
+
57
+ // A component that records what happened to one entity (a stamp, a mark, a
58
+ // claim) is its history, not the kind of thing it is.
59
+ let history = (v: Vocab, name: string) =>
60
+ v.props(name).some((p) => v.prop(name, p)?.stamped)
61
+
62
+ /** A blank sketch of what an entity is made of: each component it carries
63
+ * that a client may write, without its values or its history. */
64
+ export let like = (v: Vocab, has: Record<string, unknown>): Sketch => ({
65
+ comps: Object.fromEntries(
66
+ Object.keys(has)
67
+ .filter((n) => writable(v, n) && !history(v, n))
68
+ .map((n) => [n, {}]),
69
+ ),
70
+ outline: '',
71
+ })
72
+
73
+ /** A component as the owner reads one: its name and its properties. */
74
+ export let signature = (v: Vocab, name: string): string =>
75
+ `${name}{${v.props(name).join(', ')}}`
76
+
77
+ // A description's first sentence: enough to choose by.
78
+ let brief = (text = '') => text.split(/(?<=[.;])\s/)[0]
79
+
80
+ /** A component a search offers. */
81
+ export type Hit = { name: string; signature: string; about: string }
82
+
83
+ // How well a word names a component: its name, the start of its name, inside
84
+ // its name, or inside what it is said to be. Unnamed, it doesn't.
85
+ let fit = (name: string, about: string, word: string) =>
86
+ name == word
87
+ ? 0
88
+ : name.startsWith(word)
89
+ ? 1
90
+ : name.includes(word)
91
+ ? 2
92
+ : about.toLowerCase().includes(word)
93
+ ? 3
94
+ : Infinity
95
+
96
+ /** The components a search names, best first, leaving out those `held`: every
97
+ * word of `q` in its name or its description. */
98
+ export let find = (
99
+ v: Vocab,
100
+ q: string,
101
+ held: string[] = [],
102
+ most = 8,
103
+ ): Hit[] => {
104
+ let words = q.toLowerCase().split(/\s+/).filter(Boolean)
105
+ return v.all
106
+ .filter((name) => writable(v, name) && !held.includes(name))
107
+ .map((name) => {
108
+ let about = brief(v.def(name)?.description)
109
+ let rank = Math.max(0, ...words.map((w) => fit(name, about, w)))
110
+ return { name, about, rank }
111
+ })
112
+ .filter((h) => h.rank < Infinity)
113
+ .sort((a, b) => a.rank - b.rank || a.name.localeCompare(b.name))
114
+ .slice(0, most)
115
+ .map(({ name, about }) => ({ name, signature: signature(v, name), about }))
116
+ }
117
+
118
+ /** One line of an outline: what it says, and the line it nests under. */
119
+ export type Line = { title: string; under?: number }
120
+
121
+ /** An outline's lines: each nests under the nearest line above it that is
122
+ * indented less, and a list's bullet is not part of what it says.
123
+ *
124
+ * ```ts
125
+ * import { equal } from '@yaks/testing'
126
+ * equal(lines('Plan\n - Name it\n Ask\n Buy\n\nShip'), [
127
+ * { title: 'Plan' },
128
+ * { title: 'Name it', under: 0 },
129
+ * { title: 'Ask', under: 1 },
130
+ * { title: 'Buy', under: 0 },
131
+ * { title: 'Ship' },
132
+ * ])
133
+ * ```
134
+ */
135
+ export let lines = (text: string): Line[] => {
136
+ let out: Line[] = [], open: { indent: number; at: number }[] = []
137
+ for (let raw of text.replaceAll('\t', ' ').split('\n')) {
138
+ let title = raw.trim().replace(/^[-*+]\s+/, '')
139
+ if (!title) continue
140
+ let indent = raw.length - raw.trimStart().length
141
+ while (open.length && open.at(-1)!.indent >= indent) open.pop()
142
+ let under = open.at(-1)?.at
143
+ open.push({ indent, at: out.length })
144
+ out.push(under == null ? { title } : { title, under })
145
+ }
146
+ return out
147
+ }
148
+
149
+ /** An outline typed into, as a key leaves it: Enter starts a line at the
150
+ * indent of the one the caret is on, Tab indents that line and Shift+Tab
151
+ * takes an indent off it. Any other key is the field's own.
152
+ *
153
+ * ```ts
154
+ * import { equal } from '@yaks/testing'
155
+ * equal(press('A\n B', 6, 'Enter'), { text: 'A\n B\n ', at: 9 })
156
+ * equal(press('A\nB', 3, 'Tab'), { text: 'A\n B', at: 5 })
157
+ * equal(press('A\n B', 5, 'Tab', true), { text: 'A\nB', at: 3 })
158
+ * equal(press('A', 1, 'x'), undefined)
159
+ * ```
160
+ */
161
+ export let press = (
162
+ text: string,
163
+ at: number,
164
+ key: string,
165
+ shift = false,
166
+ ): { text: string; at: number } | undefined => {
167
+ let start = text.lastIndexOf('\n', at - 1) + 1
168
+ let indent = /^ */.exec(text.slice(start))![0]
169
+ let put = (from: number, to: number, add: string, caret: number) => ({
170
+ text: text.slice(0, from) + add + text.slice(to),
171
+ at: caret,
172
+ })
173
+ if (key == 'Enter') return put(at, at, `\n${indent}`, at + 1 + indent.length)
174
+ if (key != 'Tab') return undefined
175
+ if (!shift) return put(start, start, ' ', at + 2)
176
+ let cut = Math.min(2, indent.length)
177
+ return put(start, start + cut, '', Math.max(start, at - cut))
178
+ }
179
+
180
+ /** What writing a sketch needs besides the sketch. */
181
+ export type Context = {
182
+ vocab: Vocab
183
+ /** a property's typed text as its value; throws what it could not read */
184
+ read: (comp: string, prop: string, text: string) => unknown
185
+ /** the entity it is made in, and the place in that entity's list to start
186
+ * from */
187
+ in?: string
188
+ ord?: number
189
+ }
190
+
191
+ /** Input the sketch holds that cannot be written as it stands: a field it
192
+ * is about, or an outline line, and why. */
193
+ export type Said = { comp?: string; prop?: string; line?: number; said: string }
194
+
195
+ /** A sketch as the batch it writes: its bundles, what in it cannot be read,
196
+ * and each entity it makes by alias, with the outline line it came from. */
197
+ export type Batch = {
198
+ bundles: Bundle[]
199
+ said: Said[]
200
+ made: { alias: string; line?: number }[]
201
+ }
202
+
203
+ // Every typed property read as its value; what cannot be read is said, and
204
+ // left out.
205
+ let values = (s: Sketch, cx: Context, said: Said[]) =>
206
+ Object.fromEntries(
207
+ Object.entries(s.comps).map(([comp, typed]) => [
208
+ comp,
209
+ Object.fromEntries(
210
+ Object.entries(typed).flatMap(([prop, text]) => {
211
+ if (!text.trim()) return []
212
+ try {
213
+ return [[prop, cx.read(comp, prop, text.trim())]]
214
+ } catch (e) {
215
+ said.push({
216
+ comp,
217
+ prop,
218
+ said: e instanceof Error ? e.message : String(e),
219
+ })
220
+ return []
221
+ }
222
+ }),
223
+ ),
224
+ ]),
225
+ ) as Record<string, Comp>
226
+
227
+ // What identifies a component's entity among its kind: the properties its id
228
+ // is derived from, or else one no two of them share (a topic's name).
229
+ let keyOf = (v: Vocab, name: string): string[] => {
230
+ let identity = v.identity(name)
231
+ return identity.length
232
+ ? identity
233
+ : v.indexes(name).flatMap((i) =>
234
+ i.unique && !i.present && i.props.length == 1 ? i.props : []
235
+ )
236
+ }
237
+
238
+ // Whether what was typed names the entity: a title, or what identifies it.
239
+ let named = (v: Vocab, comps: Record<string, Comp>) =>
240
+ comps.doc?.title != null ||
241
+ Object.entries(comps).some(([name, c]) =>
242
+ keyOf(v, name).some((p) => c[p] != null)
243
+ )
244
+
245
+ // An outline line's entity: the sketch's values, its line the title and what
246
+ // identifies it where the sketch left that empty.
247
+ let titled = (v: Vocab, comps: Record<string, Comp>, title: string) => {
248
+ let out: Record<string, Comp> = { ...comps }
249
+ if (v.comp('doc')) out.doc = { ...out.doc, title }
250
+ for (let [name, c] of Object.entries(comps)) {
251
+ for (let p of keyOf(v, name)) {
252
+ if (c[p] == null) out[name] = { ...out[name], [p]: title }
253
+ }
254
+ }
255
+ return out
256
+ }
257
+
258
+ // That `from` contains `to`, `ord` its place in the list.
259
+ let contains = (alias: string, from: string, to: string, ord: number) => ({
260
+ entity: { eid: alias },
261
+ edge: { from, to, ord },
262
+ contains: {},
263
+ })
264
+
265
+ // The `contains` edges, each list in order: one in an entity that already
266
+ // exists goes on from `cx.ord`.
267
+ let edges = (cx: Context, links: [string | undefined, string][]) => {
268
+ if (!cx.vocab.comp('contains')) return []
269
+ let next = new Map<string, number>()
270
+ return links
271
+ .filter((l): l is [string, string] => !!l[0])
272
+ .map(([from, to], i) => {
273
+ let ord = next.get(from) ?? (from == cx.in ? cx.ord ?? 0 : 0)
274
+ next.set(from, ord + 1)
275
+ return contains(`$e${i + 1}`, from, to, ord)
276
+ })
277
+ }
278
+
279
+ /**
280
+ * The batch a sketch writes. With no outline it makes one entity. With one,
281
+ * each line is an entity like the sketch, titled by its line and nested by
282
+ * `contains` as it is indented; the sketch itself is the entity they are made
283
+ * in when it names one (a title, or what identifies it). Whatever is made at
284
+ * the top goes in `cx.in`.
285
+ */
286
+ export let batch = (s: Sketch, cx: Context): Batch => {
287
+ let said: Said[] = []
288
+ let comps = values(s, cx, said)
289
+ let outline = lines(s.outline)
290
+ let root = Object.keys(comps).length > 0 &&
291
+ (!outline.length || named(cx.vocab, comps))
292
+ let alias = (line: number) => `$${line + (root ? 2 : 1)}`
293
+ let made: Batch['made'] = [
294
+ ...(root ? [{ alias: '$1' }] : []),
295
+ ...outline.map((_, line) => ({ alias: alias(line), line })),
296
+ ]
297
+ let bundles: Bundle[] = made.map(({ alias, line }) => ({
298
+ entity: { eid: alias },
299
+ ...(line == null ? comps : titled(cx.vocab, comps, outline[line].title)),
300
+ }))
301
+ let under = (line?: number) => {
302
+ let up = line == null ? undefined : outline[line].under
303
+ return line == null ? cx.in : up != null ? alias(up) : root ? '$1' : cx.in
304
+ }
305
+ let links = made.map((m) =>
306
+ [under(m.line), m.alias] as [string | undefined, string]
307
+ )
308
+ return { bundles: [...bundles, ...edges(cx, links)], said, made }
309
+ }
310
+
311
+ /** A bundle as one line of what a batch writes: the entity, then each
312
+ * component with what it says, an existing entity named as `name` calls it.
313
+ *
314
+ * ```ts
315
+ * import { equal } from '@yaks/testing'
316
+ * let edge = {
317
+ * entity: { eid: '$e1' },
318
+ * edge: { from: 'p', to: '$1', ord: 0 },
319
+ * contains: {},
320
+ * }
321
+ * equal(written(edge, () => 'T-9'), '$e1 edge{from: T-9, to: $1, ord: 0} contains{}')
322
+ * equal(written({ entity: { eid: '$1' }, doc: { title: 'Go' } }), '$1 doc{title: "Go"}')
323
+ * ```
324
+ */
325
+ export let written = (
326
+ b: Bundle,
327
+ name: (eid: string) => string | undefined = () => undefined,
328
+ ): string => {
329
+ let face = (v: unknown) =>
330
+ typeof v == 'string' && (v.startsWith('$') ? v : name(v)) ||
331
+ JSON.stringify(v)
332
+ let { entity, ...rest } = b
333
+ return [
334
+ entity.eid,
335
+ ...Object.entries(rest as Record<string, Comp>).map(([comp, c]) =>
336
+ `${comp}{${
337
+ Object.entries(c).map(([k, v]) => `${k}: ${face(v)}`).join(', ')
338
+ }}`
339
+ ),
340
+ ].join(' ')
341
+ }
342
+
343
+ /** A write refused, placed where it belongs: on the field it names, when the
344
+ * sketch has that field, and on the outline line whose entity it names. A
345
+ * refusal from the server arrives as an error's `refusal`, one from the
346
+ * page's own admission as the error itself. */
347
+ export let placed = (error: unknown, b: Batch, s: Sketch): Said => {
348
+ let r = ((error as { refusal?: unknown })?.refusal ?? error) as {
349
+ eid?: string
350
+ comp?: string
351
+ prop?: string
352
+ message?: string
353
+ }
354
+ let line = b.made.find((m) => m.alias == r?.eid)?.line
355
+ let field = r?.comp && r.prop && s.comps[r.comp]
356
+ return {
357
+ ...field && { comp: r.comp, prop: r.prop },
358
+ ...line != null && { line },
359
+ said: r?.message ?? String(error),
360
+ }
361
+ }
package/outbox.js ADDED
@@ -0,0 +1,112 @@
1
+ import { outboxIdb } from "@yaks/sync";
2
+ import { Refused } from "@yaks/graph/errors";
3
+ import { bundlesOf } from "./wire.js";
4
+ import { DECISION_SETTLED } from "@yaks/task";
5
+ import { decisionWrite } from "./decision_sync.js";
6
+ // Older hosts returned this before applying any part of a keyed write.
7
+ let missingWriteLog = 'Idempotency-Key needs a host with a write log';
8
+ // What a write on a page whose host names no person is told.
9
+ export let NOBODY = 'This page is read-only: its graph names no person to write as';
10
+ // Cookie-authenticated pages cannot name a durable queue until the host has
11
+ // identified the person. Only writes wait on that lookup; watches open at once.
12
+ // A host with no person has no queue: nothing was ever saved for nobody, and a
13
+ // write is refused.
14
+ //
15
+ // `former` names a queue this page once wrote under a scope that named no
16
+ // person (@yaks/sync's default, before T-133002). Its writes are the owner's
17
+ // own: they load beside the owner's, replay under their own keys, and leave
18
+ // the former queue only when accepted or dismissed. Only a host whose writes
19
+ // can have one owner passes it.
20
+ export let scopedOutbox = (opts)=>{
21
+ let open = opts.open ?? outboxIdb;
22
+ let opening;
23
+ let formerly;
24
+ let closed = false;
25
+ let scopedOwner;
26
+ let settled = new Set();
27
+ let store = ()=>opening ??= opts.owner().then((owner)=>{
28
+ if (closed) throw new Error('Outbox closed');
29
+ scopedOwner = owner;
30
+ if (!owner) return undefined;
31
+ if (opts.former) formerly = open(opts.former);
32
+ return open(JSON.stringify([
33
+ opts.endpoint,
34
+ opts.storage ?? '',
35
+ owner
36
+ ]));
37
+ });
38
+ let writable = async ()=>{
39
+ let opened = await store();
40
+ if (!opened) throw new Refused(NOBODY);
41
+ return opened;
42
+ };
43
+ let loading;
44
+ let load = ()=>loading ??= (async ()=>{
45
+ let destination = await store();
46
+ if (!destination) return [];
47
+ let rows = await destination.load();
48
+ for (let [id, old] of await opts.legacy?.load() ?? []){
49
+ let key = id.startsWith('outbox:') ? id : `outbox:${id}`;
50
+ let existing = rows.find((r)=>r.key === key);
51
+ let sent = bundlesOf(old.changes);
52
+ if (existing && JSON.stringify(existing.sent) !== JSON.stringify(sent)) {
53
+ throw new Error('Legacy write key names different intent');
54
+ }
55
+ if (!existing) {
56
+ let entry = {
57
+ key,
58
+ sent,
59
+ state: 'pending',
60
+ at: old.at
61
+ };
62
+ await destination.put(entry);
63
+ rows.push(entry);
64
+ }
65
+ await opts.legacy.remove(id);
66
+ }
67
+ for (let entry of await formerly?.load() ?? []){
68
+ if (!rows.some((r)=>r.key === entry.key)) rows.push(entry);
69
+ }
70
+ return rows.map((entry)=>{
71
+ if (entry.state != 'refused' || entry.refusal?.name != 'Refused') {
72
+ return entry;
73
+ }
74
+ let message = entry.refusal.message;
75
+ if (message == DECISION_SETTLED && decisionWrite(entry.sent)) {
76
+ // Read the settled decision and recover the attempted answer text.
77
+ settled.add(entry.key);
78
+ } else if (message != missingWriteLog) return entry;
79
+ // The original batch stays on disk until its replay is accepted.
80
+ opts.reconcile?.(entry.key);
81
+ let { refusal: _, ...pending } = entry;
82
+ return {
83
+ ...pending,
84
+ state: 'pending'
85
+ };
86
+ });
87
+ })();
88
+ return {
89
+ assertOwner: async ()=>{
90
+ await writable();
91
+ let owner = await opts.owner();
92
+ if (owner !== scopedOwner) {
93
+ throw new Error('The authenticated write owner changed; reload to switch accounts');
94
+ }
95
+ },
96
+ settled: (key)=>settled.has(key),
97
+ load,
98
+ put: async (entry)=>(await writable()).put(entry),
99
+ remove: async (key)=>{
100
+ await (await store())?.remove(key);
101
+ await formerly?.remove(key);
102
+ settled.delete(key);
103
+ },
104
+ close: ()=>{
105
+ closed = true;
106
+ opts.legacy?.close?.();
107
+ formerly?.close?.();
108
+ void opening?.then((s)=>s?.close?.(), ()=>{});
109
+ }
110
+ };
111
+ };
112
+ //# sourceMappingURL=outbox.js.map
package/outbox.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox.js","sources":["./outbox.ts"],"names":[],"mappings":"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"}
package/outbox.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { outboxIdb, type OutboxStore } from '@yaks/sync'
2
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
3
+ import { Refused } from '@yaks/graph/errors'
4
+ import type { LegacyOutbox } from './legacy_outbox.ts'
5
+ import { bundlesOf } from './wire.js'
6
+ import { DECISION_SETTLED } from '@yaks/task'
7
+ import { decisionWrite } from './decision_sync.js'
8
+
9
+ // Older hosts returned this before applying any part of a keyed write.
10
+ let missingWriteLog = 'Idempotency-Key needs a host with a write log'
11
+
12
+ // What a write on a page whose host names no person is told.
13
+ export let NOBODY =
14
+ 'This page is read-only: its graph names no person to write as'
15
+
16
+ // Cookie-authenticated pages cannot name a durable queue until the host has
17
+ // identified the person. Only writes wait on that lookup; watches open at once.
18
+ // A host with no person has no queue: nothing was ever saved for nobody, and a
19
+ // write is refused.
20
+ //
21
+ // `former` names a queue this page once wrote under a scope that named no
22
+ // person (@yaks/sync's default, before T-133002). Its writes are the owner's
23
+ // own: they load beside the owner's, replay under their own keys, and leave
24
+ // the former queue only when accepted or dismissed. Only a host whose writes
25
+ // can have one owner passes it.
26
+ export let scopedOutbox = (opts: {
27
+ endpoint: string
28
+ storage?: string
29
+ owner: () => Promise<string | undefined>
30
+ legacy?: LegacyOutbox
31
+ former?: string
32
+ reconcile?: (key: string) => void
33
+ open?: (scope: string) => OutboxStore<Bundle[]>
34
+ }): OutboxStore<Bundle[]> & {
35
+ assertOwner: () => Promise<void>
36
+ settled: (key: string) => boolean
37
+ } => {
38
+ let open = opts.open ?? outboxIdb<Bundle[]>
39
+ let opening: Promise<OutboxStore<Bundle[]> | undefined> | undefined
40
+ let formerly: OutboxStore<Bundle[]> | undefined
41
+ let closed = false
42
+ let scopedOwner: string | undefined
43
+ let settled = new Set<string>()
44
+ let store = () =>
45
+ opening ??= opts.owner().then((owner) => {
46
+ if (closed) throw new Error('Outbox closed')
47
+ scopedOwner = owner
48
+ if (!owner) return undefined
49
+ if (opts.former) formerly = open(opts.former)
50
+ return open(JSON.stringify([opts.endpoint, opts.storage ?? '', owner]))
51
+ })
52
+ let writable = async () => {
53
+ let opened = await store()
54
+ if (!opened) throw new Refused(NOBODY)
55
+ return opened
56
+ }
57
+ let loading:
58
+ | Promise<Awaited<ReturnType<OutboxStore<Bundle[]>['load']>>>
59
+ | undefined
60
+ let load = () =>
61
+ loading ??= (async () => {
62
+ let destination = await store()
63
+ if (!destination) return []
64
+ let rows = await destination.load()
65
+ for (let [id, old] of await opts.legacy?.load() ?? []) {
66
+ let key = id.startsWith('outbox:') ? id : `outbox:${id}`
67
+ let existing = rows.find((r) => r.key === key)
68
+ let sent = bundlesOf(old.changes)
69
+ if (
70
+ existing && JSON.stringify(existing.sent) !== JSON.stringify(sent)
71
+ ) {
72
+ throw new Error('Legacy write key names different intent')
73
+ }
74
+ if (!existing) {
75
+ let entry = {
76
+ key,
77
+ sent,
78
+ state: 'pending' as const,
79
+ at: old.at,
80
+ }
81
+ await destination.put(entry)
82
+ rows.push(entry)
83
+ }
84
+ await opts.legacy!.remove(id)
85
+ }
86
+ for (let entry of await formerly?.load() ?? []) {
87
+ if (!rows.some((r) => r.key === entry.key)) rows.push(entry)
88
+ }
89
+ return rows.map((entry) => {
90
+ if (entry.state != 'refused' || entry.refusal?.name != 'Refused') {
91
+ return entry
92
+ }
93
+ let message = entry.refusal.message
94
+ if (message == DECISION_SETTLED && decisionWrite(entry.sent)) {
95
+ // Read the settled decision and recover the attempted answer text.
96
+ settled.add(entry.key)
97
+ } else if (message != missingWriteLog) return entry
98
+ // The original batch stays on disk until its replay is accepted.
99
+ opts.reconcile?.(entry.key)
100
+ let { refusal: _, ...pending } = entry
101
+ return { ...pending, state: 'pending' }
102
+ })
103
+ })()
104
+ return {
105
+ assertOwner: async () => {
106
+ await writable()
107
+ let owner = await opts.owner()
108
+ if (owner !== scopedOwner) {
109
+ throw new Error(
110
+ 'The authenticated write owner changed; reload to switch accounts',
111
+ )
112
+ }
113
+ },
114
+ settled: (key) => settled.has(key),
115
+ load,
116
+ put: async (entry) => (await writable()).put(entry),
117
+ remove: async (key) => {
118
+ await (await store())?.remove(key)
119
+ await formerly?.remove(key)
120
+ settled.delete(key)
121
+ },
122
+ close: () => {
123
+ closed = true
124
+ opts.legacy?.close?.()
125
+ formerly?.close?.()
126
+ void opening?.then((s) => s?.close?.(), () => {})
127
+ },
128
+ }
129
+ }
package/owner.js ADDED
@@ -0,0 +1,39 @@
1
+ // Start identifying this page's write owner while its vocabulary is loading.
2
+ // Only boot may consume that in-flight read. Outbox checks always ask again:
3
+ // an account change must never replay writes as the owner of a prior request.
4
+ // A host that names no person answers no owner: its page reads, and refuses
5
+ // writes (outbox.ts). Only a failed or malformed answer is an error.
6
+ export let ownerReads = (request = (url)=>fetch(url))=>{
7
+ let first;
8
+ let fresh = async (url)=>{
9
+ let response = await request(url);
10
+ if (!response.ok) throw new Error('Could not identify the write owner');
11
+ let identity = (await response.json()).owner;
12
+ if (identity == null) return undefined;
13
+ if (typeof identity !== 'string' || !identity) {
14
+ throw new Error('Could not identify the write owner');
15
+ }
16
+ return identity;
17
+ };
18
+ return {
19
+ fresh,
20
+ begin: (url)=>{
21
+ if (first) return;
22
+ let answer = fresh(url);
23
+ // Boot observes a failure after vocabulary/module evaluation finishes.
24
+ // The eagerly started request must not reject unhandled in the meantime.
25
+ void answer.catch(()=>{});
26
+ first = {
27
+ url,
28
+ answer
29
+ };
30
+ },
31
+ initial: (url)=>{
32
+ let started = first;
33
+ first = undefined;
34
+ return started?.url == url ? started.answer : fresh(url);
35
+ }
36
+ };
37
+ };
38
+ export let writeOwner = ownerReads();
39
+ //# sourceMappingURL=owner.js.map
package/owner.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"owner.js","sources":["./owner.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,qEAAqE;AACrE,OAAO,IAAI,aAAa,CACtB,UAA8C,CAAC,MAAQ,MAAM,IAAI;EAEjE,IAAI;EACJ,IAAI,QAAQ,OAAO;IACjB,IAAI,WAAW,MAAM,QAAQ;IAC7B,IAAI,CAAC,SAAS,EAAE,EAAE,MAAM,IAAI,MAAM;IAClC,IAAI,WAAW,CAAC,MAAM,SAAS,IAAI,EAAE,EAAE,KAAK;IAC5C,IAAI,YAAY,MAAM,OAAO;IAC7B,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU;MAC7C,MAAM,IAAI,MAAM;IAClB;IACA,OAAO;EACT;EACA,OAAO;IACL;IACA,OAAO,CAAC;MACN,IAAI,OAAO;MACX,IAAI,SAAS,MAAM;MACnB,uEAAuE;MACvE,yEAAyE;MACzE,KAAK,OAAO,KAAK,CAAC,KAAO;MACzB,QAAQ;QAAE;QAAK;MAAO;IACxB;IACA,SAAS,CAAC;MACR,IAAI,UAAU;MACd,QAAQ;MACR,OAAO,SAAS,OAAO,MAAM,QAAQ,MAAM,GAAG,MAAM;IACtD;EACF;AACF,EAAC;AACD,OAAO,IAAI,aAAa,aAAY"}
package/owner.ts ADDED
@@ -0,0 +1,37 @@
1
+ // Start identifying this page's write owner while its vocabulary is loading.
2
+ // Only boot may consume that in-flight read. Outbox checks always ask again:
3
+ // an account change must never replay writes as the owner of a prior request.
4
+ // A host that names no person answers no owner: its page reads, and refuses
5
+ // writes (outbox.ts). Only a failed or malformed answer is an error.
6
+ export let ownerReads = (
7
+ request: (url: string) => Promise<Response> = (url) => fetch(url),
8
+ ) => {
9
+ let first: { url: string; answer: Promise<string | undefined> } | undefined
10
+ let fresh = async (url: string) => {
11
+ let response = await request(url)
12
+ if (!response.ok) throw new Error('Could not identify the write owner')
13
+ let identity = (await response.json()).owner
14
+ if (identity == null) return undefined
15
+ if (typeof identity !== 'string' || !identity) {
16
+ throw new Error('Could not identify the write owner')
17
+ }
18
+ return identity
19
+ }
20
+ return {
21
+ fresh,
22
+ begin: (url: string) => {
23
+ if (first) return
24
+ let answer = fresh(url)
25
+ // Boot observes a failure after vocabulary/module evaluation finishes.
26
+ // The eagerly started request must not reject unhandled in the meantime.
27
+ void answer.catch(() => {})
28
+ first = { url, answer }
29
+ },
30
+ initial: (url: string) => {
31
+ let started = first
32
+ first = undefined
33
+ return started?.url == url ? started.answer : fresh(url)
34
+ },
35
+ }
36
+ }
37
+ export let writeOwner = ownerReads()