@lincyaw/kernel 1.0.0-rc.5 → 1.0.0-rc.51

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 (52) hide show
  1. package/README.md +1 -1
  2. package/package.json +4 -2
  3. package/src/contracts/authoring-actions.ts +3 -3
  4. package/src/contracts/authoring-clients.ts +58 -1
  5. package/src/contracts/authoring-windows.ts +47 -0
  6. package/src/contracts/capture.ts +148 -0
  7. package/src/contracts/document-voice.ts +35 -2
  8. package/src/contracts/document.ts +14 -1
  9. package/src/contracts/plugin.ts +1 -3
  10. package/src/contracts/preview.ts +3 -3
  11. package/src/contracts/projects.ts +4 -1
  12. package/src/contracts/speech-settings.ts +13 -0
  13. package/src/contracts/speech.ts +16 -0
  14. package/src/contracts/voiceover-execution.ts +25 -1
  15. package/src/contracts/workspace-changes.ts +27 -0
  16. package/src/contracts/workspace-review.ts +39 -0
  17. package/src/contracts/workspace-source.ts +38 -0
  18. package/src/contracts/workspace.ts +2 -0
  19. package/src/contracts.ts +5 -0
  20. package/src/document-authoring-actions.ts +23 -4
  21. package/src/document-caption-scale.ts +17 -0
  22. package/src/document-comments.ts +30 -37
  23. package/src/document-components.ts +4 -12
  24. package/src/document-narrations.ts +57 -0
  25. package/src/document-operations.ts +15 -1
  26. package/src/document-pages.ts +8 -1
  27. package/src/document-places.ts +92 -0
  28. package/src/document-schema.ts +3 -3
  29. package/src/document.ts +13 -1
  30. package/src/embed.ts +26 -0
  31. package/src/escape-html.ts +4 -0
  32. package/src/html.ts +1 -4
  33. package/src/index.ts +15 -6
  34. package/src/ir.ts +23 -48
  35. package/src/lower-myst.ts +3 -12
  36. package/src/myst-marks.ts +15 -0
  37. package/src/node/authoring-actions.ts +3 -1
  38. package/src/node/authoring-windows.ts +11 -0
  39. package/src/node/document-voice.ts +6 -2
  40. package/src/node/fonts.ts +6 -3
  41. package/src/node/index.ts +9 -3
  42. package/src/node/operator-speech.ts +4 -0
  43. package/src/node/packages.ts +25 -0
  44. package/src/node/service-state.ts +52 -0
  45. package/src/node/workspace-changes.ts +7 -0
  46. package/src/node/workspace-review.ts +9 -0
  47. package/src/node/workspace-source.ts +10 -0
  48. package/src/preview-events.ts +6 -4
  49. package/src/preview-frame-connect.ts +1105 -0
  50. package/src/preview-frame.ts +30 -1120
  51. package/src/random-uuid.ts +8 -0
  52. package/src/stale-module.ts +15 -0
@@ -103,6 +103,15 @@ export interface VoiceCloneStatus {
103
103
  message?: string
104
104
  }
105
105
 
106
+ export interface SpeechCachePrune {
107
+ /** Entries some request uses. */
108
+ kept: number
109
+ /** Entries no request uses, with the bytes of their files. */
110
+ unused: { key: string, bytes: number }[]
111
+ /** Whether the unused entries were deleted. */
112
+ removed: boolean
113
+ }
114
+
106
115
  export interface TranscriptionRequest {
107
116
  engine?: string
108
117
  audio: Blob
@@ -124,6 +133,13 @@ export interface SpeechService {
124
133
  cached?(key: string, signal?: AbortSignal): Promise<Synthesis | undefined>
125
134
  alignWords?(key: string, options: { lang: string, transcribe?: boolean }, signal?: AbortSignal): Promise<SpeechWord[] | undefined>
126
135
  pruneLock?(keep: ReadonlySet<string>): Promise<number>
136
+ /**
137
+ * The document's cached audio that no request of `keep` (every sentence the document says) uses: kept is any entry
138
+ * made for the same request under any configuration of the voice service. With `remove`, deletes the unused entries
139
+ * with their alignments and speech lock entries. Throws `speech-prune-engine-unknown` when a request names no engine
140
+ * and no default engine is configured, since its entries cannot be told apart then.
141
+ */
142
+ pruneCache?(keep: readonly SynthesisRequest[], options?: { remove?: boolean, signal?: AbortSignal }): Promise<SpeechCachePrune>
127
143
  transcribe(request: TranscriptionRequest, signal?: AbortSignal): Promise<Transcript>
128
144
  /** Registers the consent, then starts training; only for the document's owner. Absent: the service cannot clone. */
129
145
  cloneVoice?(request: VoiceCloneRequest, signal?: AbortSignal): Promise<VoiceCloneStatus>
@@ -1,9 +1,31 @@
1
1
  import type { CanonicalSource } from '../ir.ts'
2
2
  import type { Member } from './server.ts'
3
- import type { VoiceoverCancellation, VoiceoverJob, VoiceoverRequest, VoiceoverSnapshot, VoicePreviewAnswer, VoicePreviewQuery, VoicePreviewQuote, VoicePreviewRequest } from './voice.ts'
3
+ import type { SpeechVoice, SynthesisRequest } from './speech.ts'
4
+ import type { VoiceoverCancellation, VoiceoverJob, VoiceoverRequest, VoiceoverSnapshot, VoicePreviewAnswer, VoicePreviewQuery, VoicePreviewQuote, VoicePreviewRequest, VoiceTarget } from './voice.ts'
4
5
  import { defineService } from './service.ts'
5
6
 
6
7
  export interface VoiceoverStatusQuery { source?: CanonicalSource, revision?: string }
8
+ export interface VoiceoverSentencesQuery extends VoiceoverStatusQuery {
9
+ /** Answer as if this were the document's default voice: sentences that inherit the default, or have no voice, use it. */
10
+ defaultVoice?: SpeechVoice
11
+ }
12
+ /** One sentence that a document-scope generation processes, in reading order. */
13
+ export interface VoiceoverSentence {
14
+ section: string
15
+ step: number
16
+ stepId?: string
17
+ /** The step binding for a `steps` scope; absent when the sentence cannot be generated by step (it crosses steps). */
18
+ target?: VoiceTarget
19
+ /** The spoken text, which the voice service receives (and a cloud provider charges for). */
20
+ text: string
21
+ /** The exact synthesis request; absent when the sentence has no usable voice. */
22
+ request?: SynthesisRequest
23
+ /** Exact audio for the request is in the speech cache. */
24
+ cached: boolean
25
+ /** Why it cannot be generated now: no voice, or the voice service or voice is unavailable. */
26
+ reason?: string
27
+ }
28
+ export interface VoiceoverSentences { source: CanonicalSource, revision: string, sentences: VoiceoverSentence[] }
7
29
  export type VoiceoverStart = Omit<VoiceoverRequest, 'confirmed'>
8
30
  export type VoicePreviewStart = Omit<VoicePreviewRequest, 'confirmed'>
9
31
  export type VoicePreviewCheck = VoicePreviewQuery & { source?: CanonicalSource }
@@ -23,6 +45,8 @@ export interface VoicePreviewMedia extends Omit<VoicePreviewAnswer, 'audio'> { b
23
45
  /** Stateless plugin execution. The host owns intents and jobs; discovery creates neither. */
24
46
  export interface VoiceoverExecution {
25
47
  status(query: VoiceoverStatusQuery, signal: AbortSignal): Promise<Omit<VoiceoverSnapshot, 'jobs'>>
48
+ /** Every sentence with its request and cache state; reads the cache and the voice catalog, never generates. */
49
+ sentences?(query: VoiceoverSentencesQuery, signal: AbortSignal): Promise<VoiceoverSentences>
26
50
  prepare(request: VoiceoverStart, signal: AbortSignal): Promise<PreparedVoiceover>
27
51
  quote(query: VoicePreviewCheck, signal: AbortSignal): Promise<VoicePreviewQuote>
28
52
  preview(request: VoicePreviewStart, signal: AbortSignal): Promise<VoicePreviewMedia>
@@ -0,0 +1,27 @@
1
+ import type { Member } from './server.ts'
2
+ import type { Revision, UncommittedFile } from './workspace.ts'
3
+ export const CHANGES_MAX_REQUEST_CHARS = 1 << 20
4
+ export const CHANGES_MAX_RESPONSE_CHARS = 7168
5
+ export const CHANGES_MAX_FILES = 16_384
6
+ export const CHANGES_MAX_BYTES = 512 << 20
7
+ export interface ChangesCaller { member: Member, origin: 'editor' | 'agent', boundDocument?: string, confirmed?: boolean }
8
+ export interface ChangesQuery { document?: string, offset?: number, snapshot?: string }
9
+ export interface WorkspaceChangesAnswer { available: boolean, files: (UncommittedFile & { unsupported?: true })[], snapshot?: string, nextOffset?: number }
10
+ export type WorkspaceChangesRequest = { document?: string, paths?: string[], snapshot?: string } & (
11
+ | { action: 'commit', message: string }
12
+ | { action: 'discard', confirm: true }
13
+ )
14
+ export interface WorkspaceChangesResult { action: 'commit' | 'discard', files: number, refreshed?: false, revision?: Revision, committed?: boolean }
15
+ export interface PreparedWorkspaceChanges { readonly paths: readonly string[], change(signal?: AbortSignal): Promise<WorkspaceChangesResult> }
16
+ export interface WorkspaceChanges {
17
+ list(query: ChangesQuery, caller: ChangesCaller): Promise<WorkspaceChangesAnswer>
18
+ prepare(request: WorkspaceChangesRequest, caller: ChangesCaller): Promise<PreparedWorkspaceChanges>
19
+ }
20
+ const document = { type: 'string', maxLength: 500 } as const
21
+ const snapshot = { type: 'string', pattern: '^[a-f0-9]{64}$' } as const
22
+ const paths = { type: 'array', minItems: 1, maxItems: CHANGES_MAX_FILES, uniqueItems: true, items: { type: 'string', minLength: 1, maxLength: 500 } } as const
23
+ export const CHANGES_QUERY_SCHEMA = { type: 'object', additionalProperties: false, properties: { document, snapshot, offset: { type: 'integer', minimum: 0 } } } as const
24
+ export const CHANGES_REQUEST_SCHEMA = { oneOf: [
25
+ { type: 'object', additionalProperties: false, required: ['action', 'message'], properties: { document, paths, snapshot, action: { const: 'commit' }, message: { type: 'string', minLength: 1, maxLength: 4000 } } },
26
+ { type: 'object', additionalProperties: false, required: ['action', 'confirm'], properties: { document, paths, snapshot, action: { const: 'discard' }, confirm: { const: true } } },
27
+ ] } as const
@@ -0,0 +1,39 @@
1
+ import type { Member } from './server.ts'
2
+ import type { ReviewChange, ReviewStep } from './workspace.ts'
3
+
4
+ export const WORKSPACE_REVIEW_MAX_REQUEST_CHARS = 8192
5
+ export const WORKSPACE_REVIEW_MAX_RESPONSE_CHARS = 7168
6
+ export const WORKSPACE_REVIEW_FRAGMENT_CHARS = 4000
7
+ export interface WorkspaceReviewQuery { part?: 'summary' | 'files' | 'steps' | 'diff', path?: string, step?: string, offset?: number, snapshot?: string }
8
+ export interface WorkspaceReviewSummary { id: string, document: string, running: boolean, mode: 'required' | 'auto', files: number, steps: number }
9
+ export interface WorkspaceReviewAnswer {
10
+ review: WorkspaceReviewSummary | null
11
+ snapshot?: string
12
+ files?: Omit<ReviewChange, 'diff'>[]
13
+ steps?: (Omit<ReviewStep, 'changes'> & { files: number })[]
14
+ nextOffset?: number
15
+ diff?: { path: string, step?: string, text: string, offset: number, totalChars: number, sha256: string }
16
+ }
17
+ export type WorkspaceReviewChange =
18
+ | { action: 'accept', snapshot: string, reject?: string[], message?: string }
19
+ | { action: 'reject', snapshot: string, paths?: string[], confirm: true }
20
+ | { action: 'restore', snapshot: string, step: string, confirm: true }
21
+ export interface WorkspaceReviewChanged { outcome: 'accepted' | 'rejected' | 'restored' | 'updated' | 'empty', revision?: string, files?: number, remainingFiles?: number }
22
+ /** Workspace publication authority; document-scoped agent credentials must never receive this service. */
23
+ export interface WorkspaceReview {
24
+ read(query: WorkspaceReviewQuery, member: Member): Promise<WorkspaceReviewAnswer>
25
+ check(change: WorkspaceReviewChange, member: Member): Promise<void>
26
+ change(change: WorkspaceReviewChange, member: Member, signal?: AbortSignal): Promise<WorkspaceReviewChanged>
27
+ }
28
+ const path = { type: 'string', minLength: 1, maxLength: 500 } as const
29
+ const snapshot = { type: 'string', pattern: '^[a-f0-9]{64}$' } as const
30
+ const step = { type: 'string', minLength: 1, maxLength: 100 } as const
31
+ const paths = { type: 'array', minItems: 1, maxItems: 200, uniqueItems: true, items: path } as const
32
+ export const WORKSPACE_REVIEW_QUERY_SCHEMA = { type: 'object', additionalProperties: false, properties: {
33
+ part: { enum: ['summary', 'files', 'steps', 'diff'] }, path, step, offset: { type: 'integer', minimum: 0 }, snapshot,
34
+ } } as const
35
+ export const WORKSPACE_REVIEW_CHANGE_SCHEMA = { oneOf: [
36
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot'], properties: { action: { const: 'accept' }, snapshot, reject: paths, message: { type: 'string', minLength: 1, maxLength: 4000 } } },
37
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot', 'confirm'], properties: { action: { const: 'reject' }, snapshot, paths, confirm: { const: true } } },
38
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot', 'step', 'confirm'], properties: { action: { const: 'restore' }, snapshot, step, confirm: { const: true } } },
39
+ ] } as const
@@ -0,0 +1,38 @@
1
+ import type { Member } from './server.ts'
2
+ import type { SourceFile } from './workspace.ts'
3
+
4
+ export const SOURCE_MAX_BYTES = 2 << 20
5
+ export const SOURCE_MAX_FILES = 16
6
+ export const SOURCE_MAX_REQUEST_CHARS = SOURCE_MAX_BYTES * 3 + 8192
7
+ export const SOURCE_MAX_RESPONSE_CHARS = 7168
8
+ export const SOURCE_FRAGMENT_CHARS = 4000
9
+ /** Supplied by an adapter, never accepted as model arguments. */
10
+ export interface SourceCaller { member: Member, boundDocument?: string, confirmed?: boolean, origin: 'editor' | 'agent' }
11
+ export interface SourceListQuery { document?: string, query?: string, offset?: number, snapshot?: string }
12
+ export interface SourceListAnswer { files: SourceFile[], snapshot: string, nextOffset?: number, truncated?: true }
13
+ export interface SourceReadQuery { document?: string, path: string, offset?: number, version?: string }
14
+ export interface SourceReadAnswer { path: string, version: string, text: string, offset: number, totalChars: number, nextOffset?: number }
15
+ export type SourceEditFile = { path: string, version?: string } & ({ content: string, create?: true } | { find: string, replace: string })
16
+ export type SourceEdit = ({ document?: string } & SourceEditFile) | { document?: string, edits: SourceEditFile[] }
17
+ export interface SourceSaved { saved: true, changed: boolean, path?: string, files?: number, revision?: string, current?: false }
18
+ export interface PreparedSourceEdit { change(signal?: AbortSignal): Promise<SourceSaved> }
19
+ /** Current source editor scope and transaction owner; invalid IR is readable and repairable. */
20
+ export interface WorkspaceSource {
21
+ list(query: SourceListQuery, caller: SourceCaller): Promise<SourceListAnswer>
22
+ read(query: SourceReadQuery, caller: SourceCaller): Promise<SourceReadAnswer>
23
+ prepare(edit: SourceEdit, caller: SourceCaller): Promise<PreparedSourceEdit>
24
+ }
25
+ const document = { type: 'string', maxLength: 500 } as const
26
+ const path = { type: 'string', minLength: 1, maxLength: 500 } as const
27
+ const version = { type: 'string', pattern: '^[a-f0-9]{20}$' } as const
28
+ const offset = { type: 'integer', minimum: 0 } as const
29
+ export const SOURCE_LIST_SCHEMA = { type: 'object', additionalProperties: false, properties: { document, query: { type: 'string', maxLength: 200 }, offset, snapshot: { type: 'string', pattern: '^[a-f0-9]{64}$' } } } as const
30
+ export const SOURCE_READ_SCHEMA = { type: 'object', additionalProperties: false, required: ['path'], properties: { document, path, offset, version } } as const
31
+ const fileSchema = { oneOf: [
32
+ { type: 'object', additionalProperties: false, required: ['path', 'content'], properties: { path, version, content: { type: 'string', maxLength: SOURCE_MAX_BYTES }, create: { const: true } } },
33
+ { type: 'object', additionalProperties: false, required: ['path', 'find', 'replace'], properties: { path, version, find: { type: 'string', minLength: 1, maxLength: SOURCE_MAX_BYTES }, replace: { type: 'string', maxLength: SOURCE_MAX_BYTES } } },
34
+ ] } as const
35
+ export const SOURCE_EDIT_SCHEMA = { oneOf: [
36
+ ...fileSchema.oneOf.map(schema => ({ ...schema, properties: { document, ...schema.properties } })),
37
+ { type: 'object', additionalProperties: false, required: ['edits'], properties: { document, edits: { type: 'array', minItems: 1, maxItems: SOURCE_MAX_FILES, items: fileSchema } } },
38
+ ] } as const
@@ -94,6 +94,8 @@ export interface DocumentSummary {
94
94
  description?: string
95
95
  lang?: string
96
96
  tags?: string[]
97
+ /** Whether its metadata asks for a presentation (`renderers.slides`), which a site serves below its pages. */
98
+ slides?: boolean
97
99
  }
98
100
 
99
101
  /** @experimental The workspace service's answer to `documents`. */
package/src/contracts.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './contracts/agent.ts'
2
2
  export * from './contracts/authoring.ts'
3
+ export * from './contracts/capture.ts'
3
4
  export * from './contracts/document-reads.ts'
4
5
  export * from './contracts/anchors.ts'
5
6
  export * from './contracts/checks.ts'
@@ -22,6 +23,9 @@ export * from './contracts/server.ts'
22
23
  export * from './contracts/service.ts'
23
24
  export * from './contracts/speech.ts'
24
25
  export * from './contracts/speech-settings.ts'
26
+ export * from './contracts/workspace-review.ts'
27
+ export * from './contracts/workspace-source.ts'
28
+ export * from './contracts/workspace-changes.ts'
25
29
  export * from './contracts/transcription.ts'
26
30
  export * from './contracts/transcription-adoption.ts'
27
31
  export * from './contracts/voice.ts'
@@ -31,5 +35,6 @@ export * from './contracts/document-comments.ts'
31
35
  export * from './contracts/authoring-actions.ts'
32
36
  export * from './contracts/document-history.ts'
33
37
  export * from './contracts/authoring-clients.ts'
38
+ export * from './contracts/authoring-windows.ts'
34
39
  export * from './contracts/projects.ts'
35
40
  export * from './contracts/document-image.ts'
@@ -1,15 +1,31 @@
1
1
  import { applyDocumentCaptionTiming } from './document-caption-timings.ts'
2
+ import { captionScale, changeDocumentCaptionScale } from './document-caption-scale.ts'
2
3
  import { hasRole } from './access.ts'
3
- import { applyDocumentCommentAction, DocumentCommentError, validateDocumentCommentAnchor } from './document-comments.ts'
4
+ import { applyDocumentCommentAction, degradeDocumentCommentAnchor, DocumentCommentError, validateDocumentCommentAnchor } from './document-comments.ts'
5
+ import { documentAnchorKey } from './document-places.ts'
4
6
  import { changeDocumentVoice, documentVoiceStepIds, previewDocumentVoiceChange } from './document-voices.ts'
5
7
  import { applyDocumentComponentAction } from './document-components.ts'
6
8
  import type { DocumentAuthoringAction, DocumentAuthoringActionEffect } from './contracts/authoring-actions.ts'
7
9
  import type { DocumentCommentContext } from './contracts/document-comments.ts'
8
10
  import type { TeachingDocument } from './contracts/document.ts'
9
11
 
12
+ export function enableDocumentProduction(document: TeachingDocument): TeachingDocument {
13
+ const plugins = [...new Set([...(document.metadata.plugins ?? []), '@lincyaw/addon-lecture', '@lincyaw/addon-speech'])]
14
+ if (JSON.stringify(plugins) === JSON.stringify(document.metadata.plugins) && document.metadata.renderers?.lecture) return document
15
+ return { ...document, metadata: { ...document.metadata, plugins, renderers: { ...document.metadata.renderers, lecture: document.metadata.renderers?.lecture ?? {} } } }
16
+ }
17
+
10
18
  /** Fixed context is supplied by the owning adapter exactly once per semantic plan. */
11
19
  export function applyDocumentAuthoringAction(document: TeachingDocument, action: DocumentAuthoringAction, context: DocumentCommentContext): { content: TeachingDocument, effect: DocumentAuthoringActionEffect } {
12
20
  if (!context.member || !hasRole(context.member, 'editor')) throw new DocumentCommentError(403, 'authoring-permission-denied')
21
+ if (action.type === 'production.enable') {
22
+ const content = enableDocumentProduction(document)
23
+ return { content, effect: { kind: 'production', value: { enabled: true, changed: content !== document } } }
24
+ }
25
+ if (action.type === 'caption.scale.set') {
26
+ const content = changeDocumentCaptionScale(document, action.scale)
27
+ return { content, effect: { kind: 'caption-scale', value: { scale: captionScale(content.production), changed: content !== document } } }
28
+ }
13
29
  if (action.type === 'component.parameters.patch' || action.type === 'component.step-parameters.patch' || action.type === 'component.step-parameters.reset' || action.type === 'component.definition.use') {
14
30
  const { content, effect } = applyDocumentComponentAction(document, action)
15
31
  return { content, effect: { kind: 'component', value: effect } }
@@ -29,17 +45,20 @@ export function applyDocumentAuthoringAction(document: TeachingDocument, action:
29
45
  return { content, effect: { kind: 'voice', scope: action.scope.kind, value: previewDocumentVoiceChange(document, action.scope, action.source, { replaceOverrides: action.replaceOverrides }), recordings } }
30
46
  }
31
47
  if (action.type === 'comment.create') validateDocumentCommentAnchor(document, action.anchor ?? undefined)
32
- let source = document.comments ?? {}, detached = false
48
+ let source = document.comments ?? {}, detached = false, degraded = false
33
49
  if (action.type !== 'comment.create' && Object.hasOwn(source, action.threadId)) {
34
50
  const thread = source[action.threadId]!
35
- try { validateDocumentCommentAnchor(document, thread.anchor) } catch (error) {
36
- if (!(error instanceof DocumentCommentError) || error.status !== 422) throw error
51
+ const anchor = degradeDocumentCommentAnchor(document, thread.anchor)
52
+ if (thread.anchor && !anchor) {
37
53
  const { anchor: _anchor, ...unanchored } = thread
38
54
  source = { ...source, [thread.id]: unanchored }; detached = true
55
+ } else if (anchor && documentAnchorKey(anchor) !== documentAnchorKey(thread.anchor)) {
56
+ source = { ...source, [thread.id]: { ...thread, anchor } }; degraded = true
39
57
  }
40
58
  }
41
59
  const { threads, effect } = applyDocumentCommentAction(source, action, context)
42
60
  if (detached) { effect.anchorDetached = true; effect.changed = true }
61
+ else if (degraded) effect.changed = true
43
62
  const content = { ...document }
44
63
  if (Object.keys(threads).length) content.comments = threads
45
64
  else delete content.comments
@@ -0,0 +1,17 @@
1
+ import { CAPTION_SCALE_MAX, CAPTION_SCALE_MIN } from './contracts/document.ts'
2
+ import type { Production, TeachingDocument } from './contracts/document.ts'
3
+
4
+ /** The caption size a document sets (`production.captions.scale`); 1 when it sets none or one out of range. */
5
+ export function captionScale(production: Pick<Production, 'captions'> | undefined): number {
6
+ const scale = production?.captions?.scale
7
+ return typeof scale === 'number' && scale >= CAPTION_SCALE_MIN && scale <= CAPTION_SCALE_MAX ? scale : 1
8
+ }
9
+
10
+ /** Sets the caption size, kept in range and rounded to a tenth; the default size 1 removes the setting. */
11
+ export function changeDocumentCaptionScale(document: TeachingDocument, scale: number): TeachingDocument {
12
+ if (!Number.isFinite(scale)) throw new Error('document-caption-scale')
13
+ const value = Math.round(Math.min(CAPTION_SCALE_MAX, Math.max(CAPTION_SCALE_MIN, scale)) * 10) / 10
14
+ if (value === captionScale(document.production)) return document
15
+ const { captions: _captions, ...production } = document.production
16
+ return { ...document, production: value === 1 ? production : { ...production, captions: { scale: value } } }
17
+ }
@@ -1,6 +1,10 @@
1
1
  import { hasRole } from './access.ts'
2
2
  import type { DocumentCommentAction, DocumentCommentContext, DocumentCommentEffect } from './contracts/document-comments.ts'
3
- import type { DocumentComment, DocumentThread, InlineNode, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
3
+ import { isDocumentPlaceAnchor, isDocumentTextAnchor } from './contracts/document.ts'
4
+ import { documentBlockSection, documentCommentTargets } from './document-places.ts'
5
+ import type { DocumentComment, DocumentThread, DocumentThreadAnchor, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
6
+
7
+ export { documentCommentTargets, isDocumentTextLink } from './document-places.ts'
4
8
 
5
9
  export class DocumentCommentError extends Error {
6
10
  readonly status: number
@@ -8,45 +12,19 @@ export class DocumentCommentError extends Error {
8
12
  }
9
13
  function fail(status: number, code: string): never { throw new DocumentCommentError(status, code) }
10
14
 
11
- /** Canonical anchor v1 expands only nonempty styled-text links; other inline values are atoms. */
12
- export function isDocumentTextLink(node: InlineNode): node is Extract<InlineNode, { type: 'link' }> & { children: Extract<InlineNode, { type: 'text' | 'break' }>[] } {
13
- return node.type === 'link' && node.children.length > 0 && node.children.every(child => child.type === 'text' || child.type === 'break')
14
- }
15
- function inlineText(nodes: readonly InlineNode[]): string {
16
- return nodes.map(node => node.type === 'text' ? node.text : node.type === 'break' ? '\n' : isDocumentTextLink(node) ? inlineText(node.children) : '\uFFFC').join('')
17
- }
18
-
19
- /** Only addressable canonical text identities, in native document order; opaque data is never traversed. */
20
- export function documentCommentTargets(document: TeachingDocument): Map<string, { order: number, text: string }> {
21
- const targets = new Map<string, { order: number, text: string }>()
22
- const add = (id: string, text: string) => { targets.set(id, { order: targets.size, text }) }
23
- const rich = (node: RichTextNode): void => {
24
- if (node.type === 'paragraph' || node.type === 'heading') add(node.id, inlineText(node.children))
25
- else if (node.type === 'code') add(node.id, node.value)
26
- else if (node.type === 'list') for (const item of node.children) {
27
- const [first, ...rest] = item.children
28
- add(item.id, first?.type === 'paragraph' ? inlineText(first.children) : '')
29
- ;(first?.type === 'paragraph' ? rest : item.children).forEach(rich)
30
- }
31
- else if (node.type === 'blockquote') {
32
- const [first, ...rest] = node.children
33
- if (first?.type === 'paragraph') { add(node.id, inlineText(first.children)); rest.forEach(rich) }
34
- else node.children.forEach(rich)
35
- } else if (node.type === 'table') for (const row of node.children) for (const cell of row.children) add(cell.id, inlineText(cell.children))
36
- }
37
- const block = (id: string): void => {
38
- const value = document.blocks[id]
39
- if (value?.type === 'text') value.content.forEach(rich)
40
- else if (value?.type === 'code' && value.value !== undefined) add(id, value.value)
41
- else if (value?.type === 'container' || value?.type === 'component') value.children?.forEach(block)
42
- }
43
- for (const id of document.sectionOrder) { const page = document.sections[id]!; add(`page:${id}`, page.title); page.children.forEach(block) }
44
- return targets
45
- }
46
-
47
15
  /** No ordinal, offset clamping, surrogate splitting or guessed fallback identity. */
48
16
  export function validateDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThread['anchor']): void {
49
17
  if (!anchor) return
18
+ if (isDocumentPlaceAnchor(anchor)) {
19
+ if (!Object.hasOwn(document.blocks, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
20
+ if (anchor.stepId !== undefined) {
21
+ const step = Object.hasOwn(document.steps, anchor.stepId) ? document.steps[anchor.stepId] : undefined
22
+ const section = step ? document.sections[step.sectionId] : undefined
23
+ if (!step || !section || !section.stepOrder.includes(anchor.stepId) || step.sectionId !== documentBlockSection(document, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
24
+ }
25
+ return
26
+ }
27
+ if (!isDocumentTextAnchor(anchor)) fail(422, 'comment-anchor-target-unavailable')
50
28
  const targets = documentCommentTargets(document), a = targets.get(anchor.from.blockId), b = targets.get(anchor.to.blockId)
51
29
  if (!a || !b) fail(422, 'comment-anchor-target-unavailable')
52
30
  for (const [point, target] of [[anchor.from, a], [anchor.to, b]] as const) {
@@ -57,6 +35,21 @@ export function validateDocumentCommentAnchor(document: TeachingDocument, anchor
57
35
  if (a.order > b.order || a.order === b.order && anchor.from.offset >= anchor.to.offset) fail(422, 'comment-anchor-range-invalid')
58
36
  }
59
37
 
38
+ /**
39
+ * The strongest still-valid anchor. A place whose step no longer exists keeps the block; a missing block or an
40
+ * unmappable text range leaves the discussion explicitly unanchored rather than silently pointing elsewhere.
41
+ */
42
+ export function degradeDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThreadAnchor | undefined): DocumentThreadAnchor | undefined {
43
+ if (!anchor) return undefined
44
+ try { validateDocumentCommentAnchor(document, anchor); return anchor }
45
+ catch (error) { if (!(error instanceof DocumentCommentError) || error.status !== 422) throw error }
46
+ if (isDocumentPlaceAnchor(anchor) && anchor.stepId !== undefined && Object.hasOwn(document.blocks, anchor.blockId)) {
47
+ const place: DocumentThreadAnchor = { blockId: anchor.blockId }
48
+ try { validateDocumentCommentAnchor(document, place); return place } catch { /* The block itself is not addressable. */ }
49
+ }
50
+ return undefined
51
+ }
52
+
60
53
  /** Shared native/editor permissions: editors may delete any discussion, but edit their own comment; a document owner may manage earlier authors. */
61
54
  export function applyDocumentCommentAction(source: NonNullable<TeachingDocument['comments']>, action: DocumentCommentAction, context: DocumentCommentContext): { threads: NonNullable<TeachingDocument['comments']>, effect: DocumentCommentEffect } {
62
55
  const member = context.member
@@ -1,6 +1,7 @@
1
1
  import jsonPatch from 'fast-json-patch'
2
2
  import type { Operation } from 'fast-json-patch'
3
3
  import { validateDocument } from './document.ts'
4
+ import { documentBlockSection } from './document-places.ts'
4
5
  import { documentParameterAccess } from './parameters.ts'
5
6
  import { DOCUMENT_PARAMETER_MAX_CHANGES, DOCUMENT_PARAMETER_MAX_PATH_DEPTH } from './contracts/authoring-actions.ts'
6
7
  import type { DocumentComponentAction, DocumentComponentEffect, DocumentParameterChange } from './contracts/authoring-actions.ts'
@@ -26,18 +27,9 @@ function component(document: TeachingDocument, id: string): ComponentBlock {
26
27
  }
27
28
  export function documentComponentSection(document: TeachingDocument, blockId: string): string {
28
29
  component(document, blockId)
29
- for (const sectionId of document.sectionOrder) {
30
- const pending = [...document.sections[sectionId]!.children], seen = new Set<string>()
31
- while (pending.length) {
32
- const id = pending.pop()!
33
- if (id === blockId) return sectionId
34
- if (seen.has(id)) continue
35
- seen.add(id)
36
- const block = document.blocks[id]
37
- if (block?.type === 'container' || block?.type === 'component') pending.push(...block.children ?? [])
38
- }
39
- }
40
- return fail(422, 'component-block-owner-missing', { blockId })
30
+ const section = documentBlockSection(document, blockId)
31
+ if (!section) return fail(422, 'component-block-owner-missing', { blockId })
32
+ return section
41
33
  }
42
34
  function stepOf(document: TeachingDocument, stepId: string, sectionId: string) {
43
35
  const step = own(document.steps, stepId) ? document.steps[stepId] : undefined
@@ -0,0 +1,57 @@
1
+ import { Validator } from '@cfworker/json-schema'
2
+ import { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
3
+ import type { Narration, TeachingDocument } from './contracts/document.ts'
4
+
5
+ const schema = new Validator({ $id: 'urn:presmium:step-narrations:1', $defs: structuredClone(DOCUMENT_JSON_SCHEMA.$defs), type: 'array', items: { $ref: '#/$defs/Narration' } }, '2020-12', false)
6
+
7
+ /** Replace one step's ordered script blocks, retaining entities still used by other steps. */
8
+ export function replaceStepNarrations(source: TeachingDocument, stepId: string, narrations: readonly Narration[]): TeachingDocument {
9
+ const step = source.steps[stepId]
10
+ if (!step || !source.sections[step.sectionId]?.stepOrder.includes(stepId)) throw new Error('document-narration-target')
11
+ if (!schema.validate(narrations).valid) throw new Error('document-narration-content')
12
+ const ids = narrations.map(narration => narration.id)
13
+ if (new Set(ids).size !== ids.length) throw new Error('document-narration-target')
14
+ const content = { ...source,
15
+ steps: { ...source.steps, [stepId]: { ...step, narrationIds: ids } },
16
+ narrations: { ...source.narrations },
17
+ production: { ...source.production,
18
+ ...source.production.narrationOverrides ? { narrationOverrides: { ...source.production.narrationOverrides } } : {},
19
+ ...source.production.cueTimings ? { cueTimings: { ...source.production.cueTimings } } : {},
20
+ },
21
+ }
22
+ for (const narration of narrations) {
23
+ content.narrations[narration.id] = structuredClone(narration)
24
+ }
25
+ const used = new Set(Object.values(content.steps).flatMap(step => step.narrationIds))
26
+ for (const id of step.narrationIds) if (!used.has(id)) {
27
+ delete content.narrations[id]
28
+ if (content.production.narrationOverrides) delete content.production.narrationOverrides[id]
29
+ }
30
+ const cues = new Set(Object.values(content.narrations).flatMap(narration => narration.content.flatMap(node => node.type === 'cue' ? [node.id] : [])))
31
+ for (const id of Object.keys(content.production.cueTimings ?? {})) if (!cues.has(id)) delete content.production.cueTimings![id]
32
+ return content
33
+ }
34
+
35
+ /** An exact, unique text edit keeps the existing pronunciation and cue atoms intact. */
36
+ export function replaceStepNarrationText(source: TeachingDocument, stepId: string, find: string, replacement: string): TeachingDocument {
37
+ const step = source.steps[stepId]
38
+ if (!step || !find) throw new Error('document-narration-target')
39
+ const narrations = step.narrationIds.map(id => source.narrations[id]!)
40
+ const matches: { narration: string, node: number, offset: number }[] = []
41
+ for (const narration of narrations) for (const [node, value] of narration.content.entries()) {
42
+ if (value.type !== 'text') continue
43
+ for (let at = value.text.indexOf(find); at !== -1; at = value.text.indexOf(find, at + 1)) {
44
+ matches.push({ narration: narration.id, node, offset: at })
45
+ if (matches.length > 1) throw new Error('document-narration-text-ambiguous')
46
+ }
47
+ }
48
+ const found = matches[0]
49
+ if (!found) throw new Error('document-narration-text-missing')
50
+ return replaceStepNarrations(source, stepId, narrations.map(narration => narration.id !== found.narration ? narration : {
51
+ ...narration, content: narration.content.flatMap((node, index) => {
52
+ if (index !== found.node || node.type !== 'text') return [node]
53
+ const text = node.text.slice(0, found.offset) + replacement + node.text.slice(found.offset + find.length)
54
+ return text ? [{ ...node, text }] : []
55
+ }),
56
+ }).filter(narration => narration.content.length > 0))
57
+ }
@@ -1,3 +1,5 @@
1
+ import { isDocumentPlaceAnchor } from './contracts/document.ts'
2
+ import { degradeDocumentCommentAnchor } from './document-comments.ts'
1
3
  import type { DocumentBlock, DocumentEditOperation, TeachingDocument } from './contracts/document.ts'
2
4
 
3
5
  /** Operations describe author intent; the caller validates the resulting complete document before committing it. */
@@ -69,6 +71,14 @@ export function applyDocumentOperations(source: TeachingDocument, operations: re
69
71
  if (!targetSteps.has(value.id)) value.visuals = value.visuals.filter(visual => !moved.has(visual.blockId))
70
72
  else for (const id of moved) if (!value.visuals.some(visual => visual.blockId === id)) value.visuals.push({ blockId: id, visible: true })
71
73
  }
74
+ // A step belongs to one section; a place comment stays on the block when that step no longer renders it.
75
+ for (const thread of Object.values(document.comments ?? {})) {
76
+ const anchor = thread.anchor
77
+ if (!anchor || !isDocumentPlaceAnchor(anchor) || anchor.stepId === undefined || !moved.has(anchor.blockId)) continue
78
+ const degraded = degradeDocumentCommentAnchor(document, anchor)
79
+ if (degraded) thread.anchor = degraded
80
+ else delete thread.anchor
81
+ }
72
82
  break
73
83
  }
74
84
  case 'deleteBlock': {
@@ -82,7 +92,11 @@ export function applyDocumentOperations(source: TeachingDocument, operations: re
82
92
  }
83
93
  for (const id of removed) visit(block(id))
84
94
  // A deleted range becomes an unanchored thread; its discussion survives.
85
- for (const thread of Object.values(document.comments ?? {})) if (thread.anchor && (identities.has(thread.anchor.from.blockId) || identities.has(thread.anchor.to.blockId))) delete thread.anchor
95
+ for (const thread of Object.values(document.comments ?? {})) {
96
+ const anchor = thread.anchor
97
+ if (!anchor) continue
98
+ if (isDocumentPlaceAnchor(anchor) ? identities.has(anchor.blockId) : identities.has(anchor.from.blockId) || identities.has(anchor.to.blockId)) delete thread.anchor
99
+ }
86
100
  detach(operation.blockId)
87
101
  for (const id of removed) delete document.blocks[id]
88
102
  for (const value of Object.values(document.steps)) value.visuals = value.visuals.filter(visual => !removed.has(visual.blockId))
@@ -1,3 +1,4 @@
1
+ import { isDocumentPlaceAnchor } from './contracts/document.ts'
1
2
  import type { ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
2
3
  import type { DocumentPageDeletionImpact, DocumentPageIds } from './contracts/authoring.ts'
3
4
  import type { PageDeletePlan } from './contracts/workspace.ts'
@@ -89,7 +90,13 @@ export function pageDeletionImpact(document: TeachingDocument, section: string):
89
90
  for (const id of blocks) { const block = document.blocks[id]; if (block?.type === 'text') block.content.forEach(rich) }
90
91
  return { sectionId: section, retainedEmpty: document.sectionOrder.length === 1, blocks: [...blocks], steps: [...steps], narrations: [...removed], retainedNarrations: [...candidates].filter(id => !removed.has(id)), cues,
91
92
  clips: document.production.mediaClips.filter(clip => steps.has(clip.attachment.stepId)).map(clip => clip.id),
92
- detachedComments: Object.values(document.comments ?? {}).filter(thread => thread.anchor && (targets.has(thread.anchor.from.blockId) || targets.has(thread.anchor.to.blockId))).map(thread => thread.id), references }
93
+ detachedComments: Object.values(document.comments ?? {}).filter(thread => {
94
+ const anchor = thread.anchor
95
+ if (!anchor) return false
96
+ return isDocumentPlaceAnchor(anchor)
97
+ ? targets.has(anchor.blockId) || Boolean(anchor.stepId && steps.has(anchor.stepId))
98
+ : targets.has(anchor.from.blockId) || targets.has(anchor.to.blockId)
99
+ }).map(thread => thread.id), references }
93
100
  }
94
101
 
95
102
  export function pageDeletion(document: TeachingDocument, directory: string, version: string, section: string): PageDeletePlan {
@@ -0,0 +1,92 @@
1
+ import { isDocumentPlaceAnchor, isDocumentTextAnchor } from './contracts/document.ts'
2
+ import type { DocumentThreadAnchor, InlineNode, RichTextNode, TeachingDocument } from './contracts/document.ts'
3
+
4
+ /** The stable places a discussion can point at, in document order. */
5
+ export interface DocumentPlacesVisitor {
6
+ /** A page title or a block. */
7
+ place(id: string): void
8
+ /** An addressable text identity: a rich-text node, a code block or a page title. */
9
+ text(id: string, text: string): void
10
+ }
11
+
12
+ /** Canonical anchor v1 expands only nonempty styled-text links; other inline values are atoms. */
13
+ export function isDocumentTextLink(node: InlineNode): node is Extract<InlineNode, { type: 'link' }> & { children: Extract<InlineNode, { type: 'text' | 'break' }>[] } {
14
+ return node.type === 'link' && node.children.length > 0 && node.children.every(child => child.type === 'text' || child.type === 'break')
15
+ }
16
+ function inlineText(nodes: readonly InlineNode[]): string {
17
+ return nodes.map(node => node.type === 'text' ? node.text : node.type === 'break' ? '\n' : isDocumentTextLink(node) ? inlineText(node.children) : '\uFFFC').join('')
18
+ }
19
+
20
+ /**
21
+ * One walk over the document's stable places. Only addressable canonical identities are visited; opaque plugin
22
+ * data is never traversed. A caller that only needs text targets can ignore `place`.
23
+ */
24
+ export function walkDocumentPlaces(document: TeachingDocument, visit: DocumentPlacesVisitor): void {
25
+ const rich = (node: RichTextNode): void => {
26
+ if (node.type === 'paragraph' || node.type === 'heading') visit.text(node.id, inlineText(node.children))
27
+ else if (node.type === 'code') visit.text(node.id, node.value)
28
+ else if (node.type === 'list') for (const item of node.children) {
29
+ const [first, ...rest] = item.children
30
+ visit.text(item.id, first?.type === 'paragraph' ? inlineText(first.children) : '')
31
+ ;(first?.type === 'paragraph' ? rest : item.children).forEach(rich)
32
+ }
33
+ else if (node.type === 'blockquote') {
34
+ const [first, ...rest] = node.children
35
+ if (first?.type === 'paragraph') { visit.text(node.id, inlineText(first.children)); rest.forEach(rich) }
36
+ else node.children.forEach(rich)
37
+ } else if (node.type === 'table') for (const row of node.children) for (const cell of row.children) visit.text(cell.id, inlineText(cell.children))
38
+ }
39
+ const block = (id: string): void => {
40
+ visit.place(id)
41
+ const value = document.blocks[id]
42
+ if (value?.type === 'text') value.content.forEach(rich)
43
+ else if (value?.type === 'code' && value.value !== undefined) visit.text(id, value.value)
44
+ else if (value?.type === 'container' || value?.type === 'component') value.children?.forEach(block)
45
+ }
46
+ for (const id of document.sectionOrder) {
47
+ const page = document.sections[id]
48
+ if (!page) continue
49
+ visit.place(`page:${id}`)
50
+ visit.text(`page:${id}`, page.title)
51
+ page.children.forEach(block)
52
+ }
53
+ }
54
+
55
+ /** Only addressable canonical text identities, in native document order; opaque data is never traversed. */
56
+ export function documentCommentTargets(document: TeachingDocument): Map<string, { order: number, text: string }> {
57
+ const targets = new Map<string, { order: number, text: string }>()
58
+ walkDocumentPlaces(document, { place() {}, text: (id, text) => { targets.set(id, { order: targets.size, text }) } })
59
+ return targets
60
+ }
61
+
62
+ /** Every anchorable place in document order: page titles, blocks and text identities on one scale. */
63
+ export function documentAnchorOrder(document: TeachingDocument): Map<string, number> {
64
+ const places = new Map<string, number>()
65
+ const add = (id: string) => { if (!places.has(id)) places.set(id, places.size) }
66
+ walkDocumentPlaces(document, { place: add, text: add })
67
+ return places
68
+ }
69
+
70
+ /** The section that owns a block, following container and component children. */
71
+ export function documentBlockSection(document: TeachingDocument, blockId: string): string | undefined {
72
+ for (const sectionId of document.sectionOrder) {
73
+ const pending = [...document.sections[sectionId]!.children], seen = new Set<string>()
74
+ while (pending.length) {
75
+ const id = pending.pop()!
76
+ if (id === blockId) return sectionId
77
+ if (seen.has(id)) continue
78
+ seen.add(id)
79
+ const block = document.blocks[id]
80
+ if (block?.type === 'container' || block?.type === 'component') pending.push(...block.children ?? [])
81
+ }
82
+ }
83
+ return undefined
84
+ }
85
+
86
+ /** A key-order independent identity for comparing a thread anchor with a draft target. */
87
+ export function documentAnchorKey(anchor: DocumentThreadAnchor | undefined): string | undefined {
88
+ if (!anchor) return undefined
89
+ if (isDocumentPlaceAnchor(anchor)) return JSON.stringify(['place', anchor.blockId, anchor.stepId ?? null])
90
+ if (!isDocumentTextAnchor(anchor)) return undefined
91
+ return JSON.stringify(['text', anchor.from.blockId, anchor.from.offset, anchor.to.blockId, anchor.to.offset])
92
+ }