@yaks/draft 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.
package/gateway.ts ADDED
@@ -0,0 +1,129 @@
1
+ import { type Bundle, token } from '@yaks/graph'
2
+ import { draftEid } from './desk.js'
3
+ import { merge } from './merge.js'
4
+
5
+ export type DraftDoor = {
6
+ query(q: string): Promise<Bundle[]>
7
+ apply(rows: Bundle[]): Promise<{ bundles: Bundle[] }>
8
+ }
9
+ export type DraftIdentity = {
10
+ person?: string | null
11
+ via?: string | null
12
+ browsers?: string[]
13
+ }
14
+ export class DraftRefused extends Error {}
15
+ type DraftRow = Bundle & {
16
+ draft: {
17
+ by?: string
18
+ via?: string
19
+ place: string
20
+ text: string
21
+ rev?: number
22
+ }
23
+ created?: { by?: string; via?: string }
24
+ }
25
+ export type DraftSnapshot = {
26
+ principal: string
27
+ via?: string | null
28
+ drafts: DraftRow[]
29
+ recover: string[]
30
+ }
31
+ export type DraftGateway = {
32
+ snapshot(): Promise<DraftSnapshot>
33
+ write(value: Record<string, unknown>): Promise<{ bundles: Bundle[] }>
34
+ }
35
+ let identity = (who: DraftIdentity) => {
36
+ let by = who.person || who.via
37
+ if (!by || !/^[a-f0-9-]{36}$/i.test(by)) {
38
+ throw new DraftRefused('Open this page again to recover your saved draft.')
39
+ }
40
+ return by
41
+ }
42
+ /** A private application's vouched draft door, using the same desk and merge
43
+ * protocol as a page whose graph is directly accessible. */
44
+ export let draftGateway = (db: DraftDoor, who: DraftIdentity): DraftGateway => {
45
+ let by = identity(who)
46
+ let read = (by: string) => db.query(`.draft.by=${by}`) as Promise<DraftRow[]>
47
+ let guestRows = (via: string) =>
48
+ db.query(`.draft.via=${identity({ via })} !draft.by ?created`) as Promise<
49
+ DraftRow[]
50
+ >
51
+ return {
52
+ async snapshot() {
53
+ let rows = await (who.person ? read(by) : guestRows(by)),
54
+ recover: string[] = []
55
+ if (who.person) {
56
+ // Directory sign-in receipts fill guest authorship independently of
57
+ // an app-store failure. Their original via still identifies the input.
58
+ let attributed = await db.query(
59
+ `.draft !draft.by .created.by=${by}`,
60
+ ) as DraftRow[]
61
+ let earlier = attributed.filter((row) =>
62
+ row.draft.via && row.draft.via === row.created?.via
63
+ )
64
+ let claimed = who.browsers ?? (who.via ? [who.via] : [])
65
+ let current = (await Promise.all(claimed.map(guestRows))).flat()
66
+ let guest = [
67
+ ...new Map([
68
+ ...earlier,
69
+ ...current.filter((row) =>
70
+ !row.created?.by || row.created.by === by
71
+ ),
72
+ ].map((row) => [row.entity.eid, row])).values(),
73
+ ]
74
+ recover = [
75
+ ...new Set([
76
+ ...earlier.map((row) => row.draft.via!),
77
+ ...claimed.filter((via) =>
78
+ !current.some((row) =>
79
+ row.draft.via === via && row.created?.by &&
80
+ row.created.by !== by
81
+ )
82
+ ),
83
+ ]),
84
+ ]
85
+ if (guest.length) {
86
+ let changes: Bundle[] = []
87
+ for (let row of guest) {
88
+ let existing = rows.find((r) => r.draft.place === row.draft.place)
89
+ let text = row.draft.text === ''
90
+ ? ''
91
+ : merge('', row.draft.text, existing?.draft.text ?? '')
92
+ changes.push({
93
+ entity: { eid: draftEid(by, row.draft.place) },
94
+ draft: { by, place: row.draft.place, text },
95
+ typed: { over: existing?.draft.text ?? '' },
96
+ }, {
97
+ entity: row.entity,
98
+ $delete: true,
99
+ $was: { draft: { text: token(row.draft.text) } },
100
+ })
101
+ }
102
+ await db.apply(changes)
103
+ rows = await read(by)
104
+ }
105
+ }
106
+ return { principal: by, via: who.via, drafts: rows, recover }
107
+ },
108
+ async write(value: Record<string, unknown>) {
109
+ if (value.principal !== by) {
110
+ throw new DraftRefused(
111
+ 'Your sign-in changed. This text is kept with the person who typed it.',
112
+ )
113
+ }
114
+ if (
115
+ typeof value.place !== 'string' || typeof value.text !== 'string' ||
116
+ typeof value.over !== 'string'
117
+ ) throw new DraftRefused('Send the saved draft again.')
118
+ return await db.apply([{
119
+ entity: { eid: draftEid(by, value.place) },
120
+ draft: {
121
+ ...(who.person ? { by } : { via: by }),
122
+ place: value.place,
123
+ text: value.text,
124
+ },
125
+ typed: { over: value.over },
126
+ }])
127
+ },
128
+ }
129
+ }
package/graph.js ADDED
@@ -0,0 +1,13 @@
1
+ // The graph plugins this package contributes: the module a server imports at
2
+ // `@yaks/draft/graph`, so a draft written from two interfaces at once keeps
3
+ // what both typed.
4
+ import { drafts } from "./plugin.js";
5
+ /** The draft components and the merge that keeps concurrent typing. */ export let plugins = ({ vocab })=>// An app may have held either word before this package was composed there.
6
+ // Its declaration stays its own, and its writes cannot acquire our merge.
7
+ [
8
+ 'draft',
9
+ 'typed'
10
+ ].every((name)=>vocab.comp(name)?.namespace?.label == '@yaks/draft') ? [
11
+ drafts()
12
+ ] : [];
13
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,4EAA4E;AAC5E,mBAAmB;AAInB,SAAS,MAAM,sBAAqB;AAEpC,qEAAqE,GACrE,OAAO,IAAI,UAAU,CAAC,EAAE,KAAK,EAAoB,GAC/C,2EAA2E;EAC3E,0EAA0E;EAC1E;IAAC;IAAS;GAAQ,CAAC,KAAK,CAAC,CAAC,OACtB,MAAM,IAAI,CAAC,OAAO,WAAW,SAAS,iBAEtC;IAAC;GAAS,GACV,EAAE,CAAA"}
package/graph.ts ADDED
@@ -0,0 +1,17 @@
1
+ // The graph plugins this package contributes: the module a server imports at
2
+ // `@yaks/draft/graph`, so a draft written from two interfaces at once keeps
3
+ // what both typed.
4
+
5
+ import type { Plugin } from 'jsr:@yaks/graph@0.2.36'
6
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
7
+ import { drafts } from './plugin.js'
8
+
9
+ /** The draft components and the merge that keeps concurrent typing. */
10
+ export let plugins = ({ vocab }: { vocab: Vocab }): Plugin[] =>
11
+ // An app may have held either word before this package was composed there.
12
+ // Its declaration stays its own, and its writes cannot acquire our merge.
13
+ ['draft', 'typed'].every((name) =>
14
+ vocab.comp(name)?.namespace?.label == '@yaks/draft'
15
+ )
16
+ ? [drafts()]
17
+ : []
package/input.js ADDED
@@ -0,0 +1,65 @@
1
+ // The interface's drafts and the boxes that type into them. A host supplies
2
+ // its watch/write doors, identity and storage; no draft knows its app.
3
+ import { signal } from "@preact/signals-core";
4
+ /* @ts-types="npm:@types/react@19.3.0" */ import { useCallback, useLayoutEffect, useSyncExternalStore } from "react";
5
+ import { desk } from "./desk.js";
6
+ let host;
7
+ let only = signal();
8
+ let bound;
9
+ /** Bind once before the interface reads or types a draft. */ export let configureDrafts = (value)=>{
10
+ host = value;
11
+ bound = undefined;
12
+ only.value = undefined;
13
+ };
14
+ /** A terminal without a client identity may type as the graph's lone person. */ export let lone = ()=>host.people().then((people)=>{
15
+ only.value = people.length == 1 ? people[0].entity.eid : undefined;
16
+ }).catch(()=>{});
17
+ export let currentPerson = ()=>host.by() ?? only.value;
18
+ let desked = ()=>bound ??= desk(host.client, {
19
+ by: ()=>host.by() ?? only.value,
20
+ stash: host.stash(),
21
+ report: (err)=>console.warn('drafts:', err)
22
+ });
23
+ /** The person's drafts, keyed by where they type. */ export let drafts = {
24
+ has: (place)=>desked().has(place),
25
+ places: ()=>desked().places(),
26
+ text: (place)=>desked().text(place),
27
+ type: (place, text)=>desked().type(place, text),
28
+ spend: (place, also)=>desked().spend(place, also),
29
+ restore: (place, text, over)=>desked().restore(place, text, over),
30
+ follow: (fn)=>desked().follow(fn)
31
+ };
32
+ /** Mirror the durable draft into an uncontrolled Field; sending spends it
33
+ * atomically with the bundles its words became. */ export let useDraft = (key, ref, seed)=>{
34
+ let read = useCallback(()=>key ? drafts.text(key) : '', [
35
+ key
36
+ ]);
37
+ let subscribe = useCallback((changed)=>drafts.follow(()=>{
38
+ read();
39
+ changed();
40
+ }), [
41
+ read
42
+ ]);
43
+ let useSnapshot = useSyncExternalStore;
44
+ let text = useSnapshot(subscribe, read, read);
45
+ useLayoutEffect(()=>{
46
+ let el = ref.current;
47
+ if (!el || el.value == text) return;
48
+ let at = Math.min(el.selectionStart ?? text.length, text.length);
49
+ el.value = text;
50
+ if (el.ownerDocument.activeElement == el) el.setSelectionRange(at, at);
51
+ seed?.(text);
52
+ }, [
53
+ text
54
+ ]);
55
+ return {
56
+ text,
57
+ sync: (el)=>{
58
+ if (!key) return;
59
+ drafts.type(key, el.value);
60
+ seed?.(el.value);
61
+ },
62
+ spend: (also)=>key ? drafts.spend(key, also) : also?.length && void host.client.mutate(also)
63
+ };
64
+ };
65
+ //# sourceMappingURL=input.js.map
package/input.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"input.js","sources":["./input.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,uEAAuE;AACvE,SAAS,MAAM,+BAAyC;AACxD,uCAAuC,GAAG,SAAS,WAAW,EAAE,eAAe,EAAE,oBAAoB,gBAA0B;AAE/H,SAAsB,IAAI,oBAA4C;AAQtE,IAAI;AACJ,IAAI,OAAO;AACX,IAAI;AACJ,2DAA2D,GAC3D,OAAO,IAAI,kBAAkB,CAAC;EAC5B,OAAO;EACP,QAAQ;EACR,KAAK,KAAK,GAAG;AACf,EAAC;AACD,8EAA8E,GAC9E,OAAO,IAAI,OAAO,IAChB,KAAM,MAAM,GAAG,IAAI,CAAC,CAAC;IACnB,KAAK,KAAK,GAAG,OAAO,MAAM,IAAI,IAAI,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,GAAG;EAC3D,GAAG,KAAK,CAAC,KAAO,GAAE;AACpB,OAAO,IAAI,gBAAgB,IAA0B,KAAM,EAAE,MAAM,KAAK,KAAK,CAAA;AAC7E,IAAI,SAAS,IACX,UAAU,KAAK,KAAM,MAAM,EAAE;IAC3B,IAAI,IAAM,KAAM,EAAE,MAAM,KAAK,KAAK;IAClC,OAAO,KAAM,KAAK;IAClB,QAAQ,CAAC,MAAQ,QAAQ,IAAI,CAAC,W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AAC"}
package/input.ts ADDED
@@ -0,0 +1,90 @@
1
+ // The interface's drafts and the boxes that type into them. A host supplies
2
+ // its watch/write doors, identity and storage; no draft knows its app.
3
+ import { signal } from '@preact/signals-core'
4
+ /* @ts-types="npm:@types/react@19.3.0" */ import { useCallback, useLayoutEffect, useSyncExternalStore } from 'react'
5
+ import type { Bundle } from 'jsr:@yaks/graph@0.2.36'
6
+ import { type Client, desk, type Drafts, type Stash } from './desk.js'
7
+
8
+ export type DraftHost = {
9
+ client: Client
10
+ by: () => string | undefined
11
+ people: () => Promise<Bundle[]>
12
+ stash: () => Stash | undefined
13
+ }
14
+ let host: DraftHost | undefined
15
+ let only = signal<string | undefined>()
16
+ let bound: ReturnType<typeof desk> | undefined
17
+ /** Bind once before the interface reads or types a draft. */
18
+ export let configureDrafts = (value: DraftHost): void => {
19
+ host = value
20
+ bound = undefined
21
+ only.value = undefined
22
+ }
23
+ /** A terminal without a client identity may type as the graph's lone person. */
24
+ export let lone = (): Promise<void> =>
25
+ host!.people().then((people) => {
26
+ only.value = people.length == 1 ? people[0].entity.eid : undefined
27
+ }).catch(() => {})
28
+ export let currentPerson = (): string | undefined => host!.by() ?? only.value
29
+ let desked = () =>
30
+ bound ??= desk(host!.client, {
31
+ by: () => host!.by() ?? only.value,
32
+ stash: host!.stash(),
33
+ report: (err) => console.warn('drafts:', err),
34
+ })
35
+ /** The person's drafts, keyed by where they type. */
36
+ export let drafts: Drafts = {
37
+ has: (place) => desked().has(place),
38
+ places: () => desked().places(),
39
+ text: (place) => desked().text(place),
40
+ type: (place, text) => desked().type(place, text),
41
+ spend: (place, also) => desked().spend(place, also),
42
+ restore: (place, text, over) => desked().restore(place, text, over),
43
+ follow: (fn) => desked().follow(fn),
44
+ }
45
+
46
+ type Box = HTMLInputElement | HTMLTextAreaElement
47
+ /** Mirror the durable draft into an uncontrolled Field; sending spends it
48
+ * atomically with the bundles its words became. */
49
+ export let useDraft = (
50
+ key: string,
51
+ ref: { current: Box | null },
52
+ seed?: (v: string) => void,
53
+ ): {
54
+ text: string
55
+ sync: (el: Box) => void
56
+ spend: (also?: Bundle[]) => void | false | 0 | Promise<boolean>
57
+ } => {
58
+ let read = useCallback(() => key ? drafts.text(key) : '', [key])
59
+ let subscribe = useCallback((changed: () => void) =>
60
+ drafts.follow(() => {
61
+ read()
62
+ changed()
63
+ }), [read])
64
+ let useSnapshot: (
65
+ subscribe: (changed: () => void) => () => void,
66
+ read: () => string,
67
+ server: () => string,
68
+ ) => string = useSyncExternalStore
69
+ let text = useSnapshot(subscribe, read, read)
70
+ useLayoutEffect(() => {
71
+ let el = ref.current
72
+ if (!el || el.value == text) return
73
+ let at = Math.min(el.selectionStart ?? text.length, text.length)
74
+ el.value = text
75
+ if (el.ownerDocument.activeElement == el) el.setSelectionRange(at, at)
76
+ seed?.(text)
77
+ }, [text])
78
+ return {
79
+ text,
80
+ sync: (el: Box) => {
81
+ if (!key) return
82
+ drafts.type(key, el.value)
83
+ seed?.(el.value)
84
+ },
85
+ spend: (also?: Bundle[]) =>
86
+ key
87
+ ? drafts.spend(key, also)
88
+ : also?.length && void host!.client.mutate(also),
89
+ }
90
+ }
package/merge.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Two texts typed over the same one, made one, losing neither. Each side's
3
+ * change is the one span of the text it rewrote (what differs between the
4
+ * common prefix and the common suffix). Spans apart both apply. Spans that
5
+ * overlap keep both versions of the overlap, mine first, unless one version
6
+ * already holds the other: a write sent again, or typed on from what the other
7
+ * side already has, is taken once. Pure: a store merges with it, and so does
8
+ * an interface catching up with a store.
9
+ *
10
+ * @module
11
+ */ // The one span of `base` that `text` rewrote: where it starts and ends in
12
+ // `base`, and what `text` says there.
13
+ let span = (base, text)=>{
14
+ let n = Math.min(base.length, text.length);
15
+ let a = 0;
16
+ while(a < n && base[a] == text[a])a++;
17
+ let z = 0;
18
+ while(z < n - a && base.at(-1 - z) == text.at(-1 - z))z++;
19
+ return {
20
+ from: a,
21
+ to: base.length - z,
22
+ says: text.slice(a, text.length - z)
23
+ };
24
+ };
25
+ // What `text` says over `base`'s span from `lo` to `hi`, which holds its own.
26
+ let over = (base, text, lo, hi)=>text.slice(lo, text.length - (base.length - hi));
27
+ /**
28
+ * `mine` and `theirs`, each typed over `base`, as one text keeping both.
29
+ *
30
+ * ```ts
31
+ * import { assertEquals } from '@std/assert'
32
+ * import { merge } from '@yaks/draft'
33
+ *
34
+ * assertEquals(merge('ship it', 'ship it now', 'Ship it'), 'Ship it now')
35
+ * assertEquals(merge('', 'a', 'b'), 'ab') // both typed at once: mine first
36
+ * assertEquals(merge('abc', 'aXc', 'aYc'), 'aXYc') // one span: both kept
37
+ * assertEquals(merge('', 'hello', 'hell'), 'hello') // typed on: taken once
38
+ * assertEquals(merge('a b', 'b', 'a b c'), 'b c') // a deletion holds
39
+ * ```
40
+ */ export let merge = (base, mine, theirs)=>{
41
+ if (mine == base || mine == theirs) return theirs;
42
+ if (theirs == base) return mine;
43
+ let m = span(base, mine);
44
+ let t = span(base, theirs);
45
+ // Two insertions at one point overlap: which goes first is a conflict.
46
+ let point = m.from == m.to && t.from == t.to && m.from == t.from;
47
+ if (!point && m.to <= t.from) {
48
+ return base.slice(0, m.from) + m.says + base.slice(m.to, t.from) + t.says + base.slice(t.to);
49
+ }
50
+ if (!point && t.to <= m.from) {
51
+ return base.slice(0, t.from) + t.says + base.slice(t.to, m.from) + m.says + base.slice(m.to);
52
+ }
53
+ let lo = Math.min(m.from, t.from);
54
+ let hi = Math.max(m.to, t.to);
55
+ let a = over(base, mine, lo, hi);
56
+ let b = over(base, theirs, lo, hi);
57
+ let both = a.includes(b) ? a : b.includes(a) ? b : a + b;
58
+ return base.slice(0, lo) + both + base.slice(hi);
59
+ };
60
+ //# sourceMappingURL=merge.js.map
package/merge.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merge.js","sources":["./merge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,0EAA0E;AAC1E,sCAAsC;AAGt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AAC,GAAG,EAAE,IAAI,IAAI,EAAE,IAAI,GAAG,KAAK,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE,IAAI,GACvE,KAAK,KAAK,CAAC,EAAE,EAAE;EACnB;EACA,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE,IAAI,EAAE,EAAE,IAAI;EAChC,IAAI,KAAK,KAAK,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE;EAC5B,IAAI,IAAI,KAAK,MAAM,MAAM,IAAI;EAC7B,IAAI,IAAI,KAAK,MAAM,QAAQ,IAAI;EAC/B,IAAI,OAAO,EAAE,QAAQ,CAAC,KAAK,IAAI,EAAE,QAAQ,CAAC,KAAK,IAAI,IAAI;EACvD,OAAO,KAAK,KAAK,CAAC,GAAG,MAAM,OAAO,KAAK,KAAK,CAAC;AAC/C,EAAC"}
package/merge.ts ADDED
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Two texts typed over the same one, made one, losing neither. Each side's
3
+ * change is the one span of the text it rewrote (what differs between the
4
+ * common prefix and the common suffix). Spans apart both apply. Spans that
5
+ * overlap keep both versions of the overlap, mine first, unless one version
6
+ * already holds the other: a write sent again, or typed on from what the other
7
+ * side already has, is taken once. Pure: a store merges with it, and so does
8
+ * an interface catching up with a store.
9
+ *
10
+ * @module
11
+ */
12
+
13
+ // The one span of `base` that `text` rewrote: where it starts and ends in
14
+ // `base`, and what `text` says there.
15
+ type Span = { from: number; to: number; says: string }
16
+
17
+ let span = (base: string, text: string): Span => {
18
+ let n = Math.min(base.length, text.length)
19
+ let a = 0
20
+ while (a < n && base[a] == text[a]) a++
21
+ let z = 0
22
+ while (z < n - a && base.at(-1 - z) == text.at(-1 - z)) z++
23
+ return { from: a, to: base.length - z, says: text.slice(a, text.length - z) }
24
+ }
25
+
26
+ // What `text` says over `base`'s span from `lo` to `hi`, which holds its own.
27
+ let over = (base: string, text: string, lo: number, hi: number) =>
28
+ text.slice(lo, text.length - (base.length - hi))
29
+
30
+ /**
31
+ * `mine` and `theirs`, each typed over `base`, as one text keeping both.
32
+ *
33
+ * ```ts
34
+ * import { assertEquals } from '@std/assert'
35
+ * import { merge } from '@yaks/draft'
36
+ *
37
+ * assertEquals(merge('ship it', 'ship it now', 'Ship it'), 'Ship it now')
38
+ * assertEquals(merge('', 'a', 'b'), 'ab') // both typed at once: mine first
39
+ * assertEquals(merge('abc', 'aXc', 'aYc'), 'aXYc') // one span: both kept
40
+ * assertEquals(merge('', 'hello', 'hell'), 'hello') // typed on: taken once
41
+ * assertEquals(merge('a b', 'b', 'a b c'), 'b c') // a deletion holds
42
+ * ```
43
+ */
44
+ export let merge = (base: string, mine: string, theirs: string): string => {
45
+ if (mine == base || mine == theirs) return theirs
46
+ if (theirs == base) return mine
47
+ let m = span(base, mine)
48
+ let t = span(base, theirs)
49
+ // Two insertions at one point overlap: which goes first is a conflict.
50
+ let point = m.from == m.to && t.from == t.to && m.from == t.from
51
+ if (!point && m.to <= t.from) {
52
+ return base.slice(0, m.from) + m.says + base.slice(m.to, t.from) + t.says +
53
+ base.slice(t.to)
54
+ }
55
+ if (!point && t.to <= m.from) {
56
+ return base.slice(0, t.from) + t.says + base.slice(t.to, m.from) + m.says +
57
+ base.slice(m.to)
58
+ }
59
+ let lo = Math.min(m.from, t.from)
60
+ let hi = Math.max(m.to, t.to)
61
+ let a = over(base, mine, lo, hi)
62
+ let b = over(base, theirs, lo, hi)
63
+ let both = a.includes(b) ? a : b.includes(a) ? b : a + b
64
+ return base.slice(0, lo) + both + base.slice(hi)
65
+ }
package/mod.js ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @yaks/draft: what a person has typed and not yet sent. A draft is graph
3
+ * data, kept by the store like anything else, one per person and place, on an
4
+ * entity whose eid both derive (`draftEid`), so every interface the person
5
+ * uses (another tab, a terminal, another device) finds and shows the same one
6
+ * until it is sent or discarded, which empties its text in the journal, where
7
+ * it can be undone.
8
+ *
9
+ * - `draftDoc`, `docs`: `draft{by, via, place, text, rev}` and the `typed{over}`
10
+ * event (vocab.json).
11
+ * - `drafts()`: the plugin a store composes; its hook (`merging`) merges a
12
+ * write over what another interface wrote meanwhile (plugin.ts).
13
+ * - `merge(base, mine, theirs)`: two texts typed over one, made one, losing
14
+ * neither (merge.ts).
15
+ * - `desk(client, opts)`: an interface's drafts, typed into at once, kept
16
+ * across a reload, written to the store at a pace (desk.ts).
17
+ *
18
+ * @module
19
+ */ export { docs, draftDoc } from "./vocab.js";
20
+ export { drafts, merging } from "./plugin.js";
21
+ export { merge } from "./merge.js";
22
+ export { desk, draftEid } from "./desk.js";
23
+ export { draftGateway, DraftRefused } from "./gateway.js";
24
+ //# sourceMappingURL=mod.js.map
package/mod.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mod.js","sources":["./mod.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;CAkBC,GAED,SAAS,IAAI,EAAE,QAAQ,qBAAoB;AAC3C,SAAS,MAAM,EAAE,OAAO,sBAAqB;AAC7C,SAAS,KAAK,qBAAoB;AAClC,SAEE,IAAI,EAEJ,QAAQ,oBAGQ;AAElB,SAEE,YAAY,EAEZ,YAAY,uBACO"}
package/mod.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @yaks/draft: what a person has typed and not yet sent. A draft is graph
3
+ * data, kept by the store like anything else, one per person and place, on an
4
+ * entity whose eid both derive (`draftEid`), so every interface the person
5
+ * uses (another tab, a terminal, another device) finds and shows the same one
6
+ * until it is sent or discarded, which empties its text in the journal, where
7
+ * it can be undone.
8
+ *
9
+ * - `draftDoc`, `docs`: `draft{by, via, place, text, rev}` and the `typed{over}`
10
+ * event (vocab.json).
11
+ * - `drafts()`: the plugin a store composes; its hook (`merging`) merges a
12
+ * write over what another interface wrote meanwhile (plugin.ts).
13
+ * - `merge(base, mine, theirs)`: two texts typed over one, made one, losing
14
+ * neither (merge.ts).
15
+ * - `desk(client, opts)`: an interface's drafts, typed into at once, kept
16
+ * across a reload, written to the store at a pace (desk.ts).
17
+ *
18
+ * @module
19
+ */
20
+
21
+ export { docs, draftDoc } from './vocab.js'
22
+ export { drafts, merging } from './plugin.js'
23
+ export { merge } from './merge.js'
24
+ export {
25
+ type Client,
26
+ desk,
27
+ type DeskOpts,
28
+ draftEid,
29
+ type Drafts,
30
+ type Stash,
31
+ } from './desk.js'
32
+
33
+ export {
34
+ type DraftDoor,
35
+ draftGateway,
36
+ type DraftIdentity,
37
+ DraftRefused,
38
+ } from './gateway.js'
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@yaks/draft",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.36",
4
+ "homepage": "https://jsr.io/@yaks/draft",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./_dist/mod.d.ts",
9
+ "default": "./mod.js"
10
+ },
11
+ "./vocab": {
12
+ "types": "./_dist/vocab.d.ts",
13
+ "default": "./vocab.js"
14
+ },
15
+ "./graph": {
16
+ "types": "./_dist/graph.d.ts",
17
+ "default": "./graph.js"
18
+ },
19
+ "./input": {
20
+ "types": "./_dist/input.d.ts",
21
+ "default": "./input.js"
22
+ },
23
+ "./browser": {
24
+ "types": "./_dist/browser.d.ts",
25
+ "default": "./browser.js"
26
+ }
27
+ },
28
+ "license": "Apache-2.0",
29
+ "dependencies": {
30
+ "@yaks/fp": "0.2.36",
31
+ "@yaks/graph": "0.2.36",
32
+ "@yaks/vocab": "0.2.36",
33
+ "@preact/signals-core": "1.14.5",
34
+ "@types/react": "19.3.0",
35
+ "react": "19.3.0"
36
+ },
37
+ "description": "What a person has typed and not yet sent, kept in the graph per person and place, synced to every interface they use, and merged when two type at once.",
38
+ "repository": "https://github.com/yak-sh/yak.git"
39
+ }