@lincyaw/workbench 0.2.0-rc.25 → 0.2.0-rc.26

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.25",
3
+ "version": "0.2.0-rc.26",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -39,6 +39,7 @@
39
39
  "@floating-ui/react": "0.27.20",
40
40
  "@mantine/core": "8.3.11",
41
41
  "@mantine/hooks": "8.3.11",
42
+ "@noble/hashes": "2.4.0",
42
43
  "@radix-ui/react-dialog": "^1.3.1",
43
44
  "@radix-ui/react-dropdown-menu": "^2.2.1",
44
45
  "@radix-ui/react-popover": "^1.1.15",
@@ -54,8 +55,8 @@
54
55
  "@tiptap/pm": "3.32.0",
55
56
  "katex": "0.18.10",
56
57
  "react-resizable-panels": "4.14.5",
57
- "@lincyaw/design": "1.0.0-rc.26",
58
- "@lincyaw/kernel": "1.0.0-rc.26"
58
+ "@lincyaw/design": "1.0.0-rc.27",
59
+ "@lincyaw/kernel": "1.0.0-rc.27"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "react": "^18.3.1",
@@ -66,6 +67,6 @@
66
67
  "@types/react-dom": "18.3.7",
67
68
  "react": "^18.3.1",
68
69
  "react-dom": "^18.3.1",
69
- "@lincyaw/compiler": "1.0.0-rc.26"
70
+ "@lincyaw/compiler": "1.0.0-rc.27"
70
71
  }
71
72
  }
@@ -1,9 +1,11 @@
1
1
  import type { AuthoringClientActionResult } from '@lincyaw/kernel'
2
+ import { sha256 as draftContentHash } from './sha256.ts'
3
+
4
+ export { draftContentHash }
2
5
 
3
6
  type Fragment = Extract<AuthoringClientActionResult, { jsonText: string }>
4
7
  type Fields = 'offset' | 'endOffset' | 'totalUtf16' | 'totalUtf8' | 'sha256' | 'jsonText'
5
8
  type FragmentBase = Fragment extends infer Value ? Value extends Fragment ? Omit<Value, Fields> : never : never
6
- export const draftContentHash = async (text: string): Promise<string> => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].map(value => value.toString(16).padStart(2, '0')).join('')
7
9
  const boundary = (text: string, offset: number) => !(offset > 0 && offset < text.length && /[\uD800-\uDBFF]/.test(text[offset - 1]!) && /[\uDC00-\uDFFF]/.test(text[offset]!))
8
10
 
9
11
  /** Budget the complete client receipt and WS frame, preserving exact JSON text and Unicode progress. */
@@ -1,6 +1,7 @@
1
1
  import { isRecord, randomUUID } from '@lincyaw/kernel'
2
2
  import type { CanonicalSource, ClientComponentDraftReference, JsonObject } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface ComponentPropertyTarget { identity: string, memberId: string, blockId: string, stepId?: string }
@@ -32,7 +33,6 @@ const scopedPrefix = (kind: string, identity: string, memberId: string) => `${ki
32
33
  const markerOf = (target: ComponentPropertyTarget, reference: { id: string, revision: number, token: string }) => `${markerPrefix(target)}${JSON.stringify([reference.id, reference.revision, reference.token])}`
33
34
  const marker = (backup: ComponentPropertyBackup) => markerOf(backup.record.target, { id: backup.record.id, revision: backup.record.revision, token: backup.token })
34
35
  const keyOf = (record: ComponentPropertyDraft) => `${prefix(record.target)}${record.id}`
35
- const tokenOf = async (raw: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw)))].map(byte => byte.toString(16).padStart(2, '0')).join('')
36
36
 
37
37
  function valid(value: unknown, target: ComponentPropertyTarget): value is ComponentPropertyDraft {
38
38
  return isRecord(value) && value.format === 1 && typeof value.id === 'string' && value.id.length > 0
@@ -1,6 +1,7 @@
1
1
  import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
@@ -45,10 +46,6 @@ function documentDraft(value: unknown, documentId: string): DocumentDraft | unde
45
46
  return { content: checked.document, baseVersion: value.baseVersion, baseHash: value.baseHash, input: value.input,
46
47
  pendingHash: value.pendingHash, composing: value.composing, origins: value.origins }
47
48
  }
48
- async function tokenOf(raw: string): Promise<string> {
49
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
50
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
51
- }
52
49
 
53
50
  /** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
54
51
  export class DocumentDrafts {
@@ -1,6 +1,7 @@
1
1
  import { documentCommentTargets, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
2
2
  import type { DocumentComment, DocumentThread, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from '../document-draft-store.ts'
4
+ import { sha256 as tokenOf } from '../sha256.ts'
4
5
  import type { DraftStoreResult } from '../document-draft-store.ts'
5
6
 
6
7
  export interface CommentDraftTarget { threadId: string, commentId?: string, threadCreatedAt: string, commentCreatedAt?: string, baseline?: string }
@@ -52,10 +53,6 @@ const committedValue = (comment: DocumentComment) => JSON.stringify({ id: commen
52
53
  export const sameCommentDraftTarget = (a: CommentComposerTarget, b: CommentComposerTarget) => isNewCommentDraft(a) || isNewCommentDraft(b)
53
54
  ? isNewCommentDraft(a) && isNewCommentDraft(b) && a.documentId === b.documentId && a.signature === b.signature && JSON.stringify(a.anchor) === JSON.stringify(b.anchor)
54
55
  : a.threadId === b.threadId && a.commentId === b.commentId && a.threadCreatedAt === b.threadCreatedAt && a.commentCreatedAt === b.commentCreatedAt
55
- async function tokenOf(raw: string): Promise<string> {
56
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
57
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
58
- }
59
56
  const point = (value: unknown): boolean => isRecord(value) && typeof value.blockId === 'string' && value.blockId.length > 0 && value.blockId.length <= 205 && Number.isSafeInteger(value.offset) && Number(value.offset) >= 0
60
57
  function targetShape(value: unknown): boolean {
61
58
  if (!isRecord(value)) return false
@@ -3,6 +3,7 @@ import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, D
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
  import { DocumentDrafts } from './document-drafts.ts'
6
+ import { sha256 } from './sha256.ts'
6
7
  import type { DocumentDraftChoice, DocumentDraftCommit, DocumentDraftReference, StoredDocumentDraft } from './document-drafts.ts'
7
8
 
8
9
  export interface DocumentSessionState {
@@ -88,10 +89,7 @@ function keepsEditorContent(before: TeachingDocument, after: TeachingDocument):
88
89
  }
89
90
 
90
91
  async function digest(value: TeachingDocument): Promise<string> {
91
- const text = serialize(value)
92
- if (!globalThis.crypto?.subtle) return `json:${text}`
93
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
94
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
92
+ return sha256(serialize(value))
95
93
  }
96
94
 
97
95
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
@@ -609,7 +607,12 @@ export class DocumentSession {
609
607
  const answer = await this.#client.readDocument(slot.state.directory)
610
608
  if (!current()) return
611
609
  if (answer.document !== slot.state.directory || answer.content.id !== documentId) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
612
- const [localHash, remoteHash] = await Promise.all([digest(candidate.content), digest(answer.content)])
610
+ // Older LAN HTTP drafts stored canonical JSON in place of a SHA-256 fingerprint.
611
+ const [localHash, remoteHash, candidateBaseHash, pendingHash] = await Promise.all([
612
+ digest(candidate.content), digest(answer.content),
613
+ candidate.baseHash.startsWith('json:') ? sha256(candidate.baseHash.slice(5)) : candidate.baseHash,
614
+ candidate.pendingHash?.startsWith('json:') ? sha256(candidate.pendingHash.slice(5)) : candidate.pendingHash,
615
+ ])
613
616
  if (!current()) return
614
617
  const origins = [...new Map([...(candidate.origins ?? []), { id: candidate.id, revision: candidate.revision, token: candidate.token }].map(value => [JSON.stringify([value.id, value.revision, value.token]), value])).values()]
615
618
  if (localHash === remoteHash && !candidate.composing) {
@@ -618,16 +621,16 @@ export class DocumentSession {
618
621
  slot.persistFailure = !settled
619
622
  return
620
623
  }
621
- const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidate.baseHash && remoteHash !== candidate.pendingHash
622
- const version = remoteHash === candidate.pendingHash || remoteHash === candidate.baseHash ? answer.version : candidate.baseVersion
623
- const baseHash = remoteHash === candidate.pendingHash ? remoteHash : candidate.baseHash
624
+ const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidateBaseHash && remoteHash !== pendingHash
625
+ const version = remoteHash === pendingHash || remoteHash === candidateBaseHash ? answer.version : candidate.baseVersion
626
+ const baseHash = remoteHash === pendingHash ? remoteHash : candidateBaseHash
624
627
  const record = await slot.drafts.fork(identity, { content: candidate.content, baseVersion: version, baseHash, input: input + 1,
625
- pendingHash: candidate.pendingHash, composing: Boolean(candidate.composing), origins })
628
+ pendingHash, composing: Boolean(candidate.composing), origins })
626
629
  if (!current()) { if (record) slot.drafts.archive(record); return }
627
630
  if (!record) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true }; return }
628
631
  clearTimeout(slot.timer); slot.timer = undefined
629
632
  if (slot.draft) slot.drafts.archive(slot.draft)
630
- slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = candidate.pendingHash; slot.draft = record; slot.draftOrigins = origins
633
+ slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = pendingHash; slot.draft = record; slot.draftOrigins = origins
631
634
  slot.backup = undefined; slot.persistFailure = false
632
635
  adopted = true
633
636
  slot.compositions.clear()
package/src/sha256.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { sha256 as hash } from '@noble/hashes/sha2.js'
2
+ import { bytesToHex } from '@noble/hashes/utils.js'
3
+
4
+ /** The same SHA-256 fingerprint on HTTPS, localhost and LAN HTTP. */
5
+ export async function sha256(value: string | ArrayBuffer): Promise<string> {
6
+ const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : new Uint8Array(value)
7
+ const subtle = globalThis.crypto?.subtle
8
+ return bytesToHex(subtle ? new Uint8Array(await subtle.digest('SHA-256', bytes)) : hash(bytes))
9
+ }
package/src/workbench.ts CHANGED
@@ -15,6 +15,7 @@ import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
15
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
16
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
17
  import { DocumentSession } from './document-session.ts'
18
+ import { sha256 } from './sha256.ts'
18
19
  import { reconcileRecordingAdoption } from './recording-adoption.ts'
19
20
  import { disposeTranscriptionSessions } from './transcription-session.ts'
20
21
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
@@ -1420,7 +1421,7 @@ export class Workbench {
1420
1421
  if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
1421
1422
  let pending = this.#audioFingerprints.get(file)
1422
1423
  if (!pending) {
1423
- pending = file.arrayBuffer().then(bytes => crypto.subtle.digest('SHA-256', bytes)).then(bytes => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join(''))
1424
+ pending = file.arrayBuffer().then(sha256)
1424
1425
  this.#audioFingerprints.set(file, pending)
1425
1426
  }
1426
1427
  const hash = await pending