@lincyaw/kernel 1.0.0-rc.3 → 1.0.0-rc.31
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 +2 -1
- package/src/contracts/capture.ts +148 -0
- package/src/contracts/document.ts +14 -1
- package/src/contracts/preview.ts +3 -3
- package/src/contracts/speech.ts +16 -0
- package/src/contracts/voiceover-execution.ts +25 -1
- package/src/contracts/workspace.ts +2 -0
- package/src/contracts.ts +1 -0
- package/src/document-authoring-actions.ts +8 -4
- package/src/document-caption-scale.ts +17 -0
- package/src/document-comments.ts +30 -37
- package/src/document-components.ts +4 -12
- package/src/document-narrations.ts +33 -0
- package/src/document-operations.ts +15 -1
- package/src/document-pages.ts +8 -1
- package/src/document-places.ts +92 -0
- package/src/document-schema.ts +3 -3
- package/src/document.ts +13 -1
- package/src/embed.ts +26 -0
- package/src/escape-html.ts +4 -0
- package/src/html.ts +1 -4
- package/src/index.ts +14 -5
- package/src/ir.ts +22 -0
- package/src/lower-myst.ts +3 -12
- package/src/myst-marks.ts +15 -0
- package/src/node/authoring-actions.ts +1 -1
- package/src/node/fonts.ts +6 -3
- package/src/node/index.ts +2 -0
- package/src/node/service-state.ts +52 -0
- package/src/preview-events.ts +6 -4
- package/src/preview-frame-connect.ts +1105 -0
- package/src/preview-frame.ts +32 -1119
- package/src/random-uuid.ts +8 -0
- package/src/stale-module.ts +15 -0
|
@@ -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
|
+
}
|
package/src/document-schema.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Schema } from '@cfworker/json-schema'
|
|
2
|
-
import { ASSET_TITLE_MAX_LENGTH, DOCUMENT_SCHEMA_VERSION } from './contracts/document.ts'
|
|
2
|
+
import { ASSET_TITLE_MAX_LENGTH, CAPTION_SCALE_MAX, CAPTION_SCALE_MIN, DOCUMENT_SCHEMA_VERSION } from './contracts/document.ts'
|
|
3
3
|
|
|
4
4
|
const ref = (name: string): Schema => ({ $ref: `#/$defs/${name}` })
|
|
5
5
|
const string: Schema = { type: 'string' }
|
|
@@ -77,9 +77,9 @@ export const DOCUMENT_JSON_SCHEMA: Schema = {
|
|
|
77
77
|
StepProduction: object({ narrationStart: { enum: ['with-animation', 'after-animation'] }, minimumHoldMs: nonnegative, trailingPauseMs: nonnegative, voiceSource: ref('VoiceSource') }, []),
|
|
78
78
|
MediaClip: object({ id, assetId: id, sourceRange: object({ startMs: nonnegative, endMs: nonnegative }), attachment: object({ stepId: id, offsetMs: nonnegative }), volume: { type: 'number', minimum: 0, maximum: 1 }, muted: { type: 'boolean' } }, ['id', 'assetId', 'sourceRange', 'attachment', 'volume']),
|
|
79
79
|
CaptionTiming: object({ narrationIds: ids, sourceFingerprint: { type: 'string', pattern: '^[a-f0-9]{16}$' }, playbackFingerprint: { type: 'string', pattern: '^[a-f0-9]{16}$' }, durationMs: { type: 'integer', minimum: 1 }, segments: { type: 'array', minItems: 1, maxItems: 32, items: object({ id, from: integer, to: integer, startMs: integer, endMs: integer }) } }),
|
|
80
|
-
Production: object({ defaults: ref('StepProduction'), sectionOverrides: record(ref('StepProduction')), stepOverrides: record(ref('StepProduction')), narrationOverrides: record(object({ narrationStart: { enum: ['with-animation', 'after-animation'] } })), cueTimings: record(object({ pauseMs: nonnegative })), captionTimings: record(ref('CaptionTiming')), mediaClips: list(ref('MediaClip')) }, ['defaults', 'stepOverrides', 'mediaClips']),
|
|
80
|
+
Production: object({ defaults: ref('StepProduction'), sectionOverrides: record(ref('StepProduction')), stepOverrides: record(ref('StepProduction')), narrationOverrides: record(object({ narrationStart: { enum: ['with-animation', 'after-animation'] } })), cueTimings: record(object({ pauseMs: nonnegative })), captionTimings: record(ref('CaptionTiming')), captions: object({ scale: { type: 'number', minimum: CAPTION_SCALE_MIN, maximum: CAPTION_SCALE_MAX } }), mediaClips: list(ref('MediaClip')) }, ['defaults', 'stepOverrides', 'mediaClips']),
|
|
81
81
|
TextPoint: object({ blockId: { type: 'string', minLength: 1, maxLength: 205 }, offset: integer }),
|
|
82
82
|
Comment: object({ id, type: tag('comment'), userId: id, createdAt: string, updatedAt: string, deletedAt: string, content: list(ref('RichTextNode')), metadata: ref('JsonObject'), reactions: list(object({ emoji: string, createdAt: string, userIds: ids })) }, ['id', 'type', 'userId', 'createdAt', 'updatedAt', 'reactions']),
|
|
83
|
-
Thread: object({ id, type: tag('thread'), createdAt: string, updatedAt: string, resolved: { type: 'boolean' }, resolvedUpdatedAt: string, resolvedBy: id, metadata: ref('JsonObject'), deletedAt: string, anchor: object({ from: ref('TextPoint'), to: ref('TextPoint') }), comments: list(ref('Comment')) }, ['id', 'type', 'createdAt', 'updatedAt', 'resolved', 'comments']),
|
|
83
|
+
Thread: object({ id, type: tag('thread'), createdAt: string, updatedAt: string, resolved: { type: 'boolean' }, resolvedUpdatedAt: string, resolvedBy: id, metadata: ref('JsonObject'), deletedAt: string, anchor: { oneOf: [object({ from: ref('TextPoint'), to: ref('TextPoint') }), object({ blockId: id, stepId: id }, ['blockId'])] }, comments: list(ref('Comment')) }, ['id', 'type', 'createdAt', 'updatedAt', 'resolved', 'comments']),
|
|
84
84
|
},
|
|
85
85
|
}
|
package/src/document.ts
CHANGED
|
@@ -3,6 +3,8 @@ import { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
|
|
|
3
3
|
import { isRecord } from './errors.ts'
|
|
4
4
|
import { captionSourceFingerprint, captionTimingProblem, stepCaptionText } from './document-caption-timings.ts'
|
|
5
5
|
import { validateDocumentParameters } from './parameters.ts'
|
|
6
|
+
import { isDocumentPlaceAnchor } from './contracts/document.ts'
|
|
7
|
+
import { documentBlockSection } from './document-places.ts'
|
|
6
8
|
import type { DocumentIssue, DocumentValidation, RichTextNode, TeachingDocument } from './contracts/document.ts'
|
|
7
9
|
|
|
8
10
|
export { DOCUMENT_JSON_SCHEMA } from './document-schema.ts'
|
|
@@ -240,7 +242,17 @@ export function validateDocument(value: unknown): DocumentValidation {
|
|
|
240
242
|
const path = at('/comments', id)
|
|
241
243
|
if (id !== thread.id) issue(`${path}/id`, 'id.key', 'A thread ID must match its map key.')
|
|
242
244
|
identify(thread.id, `${path}/id`)
|
|
243
|
-
|
|
245
|
+
const anchor = thread.anchor
|
|
246
|
+
if (anchor && isDocumentPlaceAnchor(anchor)) {
|
|
247
|
+
if (!Object.hasOwn(doc.blocks, anchor.blockId)) issue(`${path}/anchor/blockId`, 'comment.target', 'A place comment must name an existing block.')
|
|
248
|
+
else if (anchor.stepId !== undefined) {
|
|
249
|
+
const step = Object.hasOwn(doc.steps, anchor.stepId) ? doc.steps[anchor.stepId] : undefined
|
|
250
|
+
const section = step ? doc.sections[step.sectionId] : undefined
|
|
251
|
+
if (!step || !section || !section.stepOrder.includes(anchor.stepId) || step.sectionId !== documentBlockSection(doc, anchor.blockId)) issue(`${path}/anchor/stepId`, 'comment.target', 'A place comment must name a step of the block\'s own section.')
|
|
252
|
+
}
|
|
253
|
+
} else if (anchor) {
|
|
254
|
+
for (const edge of ['from', 'to'] as const) if (!textTargets.has(anchor[edge].blockId)) issue(`${path}/anchor/${edge}/blockId`, 'comment.target', 'A comment anchor must name a stable rich-text node or section title.')
|
|
255
|
+
}
|
|
244
256
|
for (const [index, comment] of thread.comments.entries()) {
|
|
245
257
|
identify(comment.id, `${path}/comments/${index}/id`)
|
|
246
258
|
comment.content?.forEach((node, child) => rich(node, `${path}/comments/${index}/content/${child}`, new Set()))
|
package/src/embed.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a page tells the page that embeds it in a frame, as `postMessage` to its parent: whether its current slide is
|
|
3
|
+
* drawn (no component is still loading) and the state of its lecture. An embedding page (a site's home page playing a
|
|
4
|
+
* document's presentation) keeps its own cover until `drawn`, and offers Play when the lecture is `waiting`.
|
|
5
|
+
*/
|
|
6
|
+
export const EMBED_MESSAGE = 'presmium:state'
|
|
7
|
+
|
|
8
|
+
export type EmbeddedLecture = 'loading' | 'waiting' | 'playing' | 'paused' | 'failed'
|
|
9
|
+
|
|
10
|
+
export interface EmbedState {
|
|
11
|
+
type: typeof EMBED_MESSAGE
|
|
12
|
+
drawn: boolean
|
|
13
|
+
section?: string
|
|
14
|
+
step?: number
|
|
15
|
+
/** Absent when the page plays no lecture. `waiting`: the browser refused autoplay; the reader's Play starts it. */
|
|
16
|
+
lecture?: EmbeddedLecture
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
let last: EmbedState = { type: EMBED_MESSAGE, drawn: false }
|
|
20
|
+
|
|
21
|
+
/** Sends the page's state, merged with what was sent before, to the embedding page; nothing when not in a frame. */
|
|
22
|
+
export function notifyEmbedder(change: Partial<Omit<EmbedState, 'type'>>): void {
|
|
23
|
+
if (typeof window === 'undefined' || window.parent === window) return
|
|
24
|
+
last = { ...last, ...change }
|
|
25
|
+
window.parent.postMessage(last, '*')
|
|
26
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Text as it reads in HTML, in an element or an attribute's value; apart from `html.ts`, so that escaping loads no HTML parser. */
|
|
2
|
+
export function escapeHtml(text: string): string {
|
|
3
|
+
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
4
|
+
}
|
package/src/html.ts
CHANGED
|
@@ -1,9 +1,6 @@
|
|
|
1
1
|
import { parseFragment } from 'parse5'
|
|
2
2
|
import type { DefaultTreeAdapterMap } from 'parse5'
|
|
3
|
-
|
|
4
|
-
export function escapeHtml(text: string): string {
|
|
5
|
-
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
6
|
-
}
|
|
3
|
+
import { escapeHtml } from './escape-html.ts'
|
|
7
4
|
|
|
8
5
|
export interface HtmlAttribute {
|
|
9
6
|
name: string
|
package/src/index.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
export * from './contracts.ts'
|
|
2
|
+
export { randomUUID } from './random-uuid.ts'
|
|
2
3
|
export { applyDocumentOperations } from './document-operations.ts'
|
|
4
|
+
export { replaceStepNarrations } from './document-narrations.ts'
|
|
3
5
|
export { validateDocumentChange, DOCUMENT_CHANGE_JSON_SCHEMA } from './authoring.ts'
|
|
4
6
|
export { allocateDocumentPage, createDocumentPage, documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, duplicateDocumentPage, moveDocumentPage, pageContents, pageDeletion, pageDeletionImpact, removeDocumentPage, renameDocumentPage } from './document-pages.ts'
|
|
5
7
|
export { documentOutline, documentPart, DocumentReadError } from './document-reads.ts'
|
|
6
8
|
export { changeDocumentVoice, documentVoiceStepIds, previewDocumentVoiceChange, resolveDocumentStepVoice } from './document-voices.ts'
|
|
7
9
|
export { DOCUMENT_COLOR_NAMES, documentColorToken, documentColorValue } from './document-colors.ts'
|
|
8
10
|
export type { DocumentColorKind, DocumentColorName } from './document-colors.ts'
|
|
9
|
-
export { applyDocumentCommentAction, isDocumentTextLink, documentCommentTargets, validateDocumentCommentAnchor, DocumentCommentError } from './document-comments.ts'
|
|
11
|
+
export { applyDocumentCommentAction, degradeDocumentCommentAnchor, isDocumentTextLink, documentCommentTargets, validateDocumentCommentAnchor, DocumentCommentError } from './document-comments.ts'
|
|
12
|
+
export { documentAnchorKey, documentAnchorOrder, documentBlockSection, walkDocumentPlaces } from './document-places.ts'
|
|
10
13
|
export { applyDocumentAuthoringAction } from './document-authoring-actions.ts'
|
|
11
14
|
export { applyDocumentComponentAction, effectiveComponentParameters, createDocumentParameterChanges, documentComponentSection, DocumentComponentError } from './document-components.ts'
|
|
12
15
|
export type { DocumentStepVoice, DocumentVoiceImpact, DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
|
|
@@ -25,12 +28,14 @@ export { errorMessage, isRecord, PreviewPreparing } from './errors.ts'
|
|
|
25
28
|
export { createEventBus } from './events.ts'
|
|
26
29
|
export { CREDENTIAL_VARIABLE, environmentExecutor, failedRun, languageId } from './execution.ts'
|
|
27
30
|
export { gitConfigArgs, gitEnvironment } from './git.ts'
|
|
28
|
-
export { escapeHtml
|
|
31
|
+
export { escapeHtml } from './escape-html.ts'
|
|
32
|
+
export { htmlAttributes, mapHtmlUrls, URL_ATTRIBUTES } from './html.ts'
|
|
29
33
|
export type { HtmlAttribute } from './html.ts'
|
|
30
34
|
export { hostName, localRequestRefusal } from './requests.ts'
|
|
31
35
|
export type { RequestHeaders } from './requests.ts'
|
|
32
36
|
export { fingerprint, fnv1a64 } from './fingerprint.ts'
|
|
33
37
|
export { applyDocumentCaptionTiming, captionSourceFingerprint, captionTimingProblem, stepCaptionText, narrationCaptionText, CAPTION_TIMING_MAX_SEGMENTS, DocumentCaptionTimingError } from './document-caption-timings.ts'
|
|
38
|
+
export { captionScale, changeDocumentCaptionScale } from './document-caption-scale.ts'
|
|
34
39
|
export type { DocumentCaptionTimingAction } from './document-caption-timings.ts'
|
|
35
40
|
export { backSection, followedPlace } from './follow.ts'
|
|
36
41
|
export type { FollowAnchor } from './follow.ts'
|
|
@@ -39,9 +44,13 @@ export type { KernelOptions } from './kernel.ts'
|
|
|
39
44
|
export { deckLocale, localeOf } from './locale.ts'
|
|
40
45
|
export { ANCHOR_LOCK_PATH, AnchorLock } from './lock.ts'
|
|
41
46
|
export { prefixedLogger } from './logging.ts'
|
|
42
|
-
export { lowerMyst
|
|
47
|
+
export { lowerMyst } from './lower-myst.ts'
|
|
43
48
|
export type { LinkedType, LoweredMarkdown, LowerOptions } from './lower-myst.ts'
|
|
44
|
-
export {
|
|
49
|
+
export { isPreviewActive, isPreviewEmbedded, previewAppearance, reportPreview, siteFrameAncestors } from './preview-frame.ts'
|
|
50
|
+
export { connectPreviewFrame } from './preview-frame-connect.ts'
|
|
51
|
+
export { reportStaleModule, STALE_MODULE_EVENT, STALE_MODULE_PATTERN } from './stale-module.ts'
|
|
52
|
+
export { EMBED_MESSAGE, notifyEmbedder } from './embed.ts'
|
|
53
|
+
export type { EmbeddedLecture, EmbedState } from './embed.ts'
|
|
45
54
|
export { keyBelongsToTarget, watchFocusSource } from './keyboard.ts'
|
|
46
55
|
export type { PreviewFrame, PreviewPage, PreviewProblem, PreviewTextEdit, PreviewTextHandle } from './preview-frame.ts'
|
|
47
56
|
export { previewEditBinding } from './preview-edit.ts'
|
|
@@ -65,7 +74,7 @@ export type { StepKeys } from './step-keys.ts'
|
|
|
65
74
|
export { parseDuration } from './durations.ts'
|
|
66
75
|
export { stepStateAt } from './steps.ts'
|
|
67
76
|
export { ABSOLUTE_URL, NON_FILE_URL, urlSlug } from './urls.ts'
|
|
68
|
-
export { isButton } from './
|
|
77
|
+
export { isButton, roleMark } from './myst-marks.ts'
|
|
69
78
|
export { componentProps, findComponentRenderer, hasRendererExtension, WEB_RENDERER_PACKAGE, withPublishedAssets } from './renderer-components.ts'
|
|
70
79
|
export { htmlAsText, isProseRun } from './run-outputs.ts'
|
|
71
80
|
export { safeDecodeURIComponent } from './uri-decoding.ts'
|
package/src/ir.ts
CHANGED
|
@@ -318,6 +318,11 @@ export interface Renderer {
|
|
|
318
318
|
dev?(doc: IRDocument, ctx: RenderContext): Promise<RenderDevServer>
|
|
319
319
|
buildSite?(site: SiteSpec, ctx: RenderContext): Promise<RenderOutput>
|
|
320
320
|
devSite?(site: SiteSpec, ctx: RenderContext, compile: (dir: string) => Promise<IRDocument>): Promise<SiteDevServer>
|
|
321
|
+
/**
|
|
322
|
+
* What would fail in its output of the whole document (every form's blocks), found ahead of a build: run with the
|
|
323
|
+
* document's checks (`presmium check`). The web renderer's: the document's own code that does not bundle.
|
|
324
|
+
*/
|
|
325
|
+
check?(doc: IRDocument, ctx: RenderContext): Promise<Finding[]>
|
|
321
326
|
}
|
|
322
327
|
|
|
323
328
|
export interface SiteDocument {
|
|
@@ -326,11 +331,23 @@ export interface SiteDocument {
|
|
|
326
331
|
description?: string
|
|
327
332
|
lang?: string
|
|
328
333
|
tags?: string[]
|
|
334
|
+
/** Whether it has a presentation, before its IR is compiled (`DocumentSummary.slides`). */
|
|
335
|
+
slides?: boolean
|
|
329
336
|
doc?: IRDocument
|
|
330
337
|
translations?: { lang: string, doc: IRDocument }[]
|
|
331
338
|
nodeVitePlugins?: NodeVitePlugin[]
|
|
332
339
|
}
|
|
333
340
|
|
|
341
|
+
/**
|
|
342
|
+
* A built site keeps its viewer apps below its path, each at `<APP_DIR>/<key>/` by its content. A presentation built as
|
|
343
|
+
* part of a site (renderer option `appBase`, the site's path) names its app there, so the site's pages and all its
|
|
344
|
+
* presentations load one app.
|
|
345
|
+
*/
|
|
346
|
+
export const APP_DIR = '_app'
|
|
347
|
+
|
|
348
|
+
/** A site serves a document's presentation (`renderers.slides`) below the document's pages, at `<document>/<SLIDES_DIR>/`. */
|
|
349
|
+
export const SLIDES_DIR = 'slides'
|
|
350
|
+
|
|
334
351
|
export interface SiteSpec {
|
|
335
352
|
title: string
|
|
336
353
|
documents: SiteDocument[]
|
|
@@ -352,6 +369,11 @@ export interface SiteDevServer {
|
|
|
352
369
|
* With `wait`, a build still running after the wait rejects with `PreviewPreparing`; a failed build with its reason.
|
|
353
370
|
*/
|
|
354
371
|
app?(dir: string, wait?: boolean): Promise<string | undefined>
|
|
372
|
+
/**
|
|
373
|
+
* The files of document `dir`'s own code that the bundle its pages load now leaves out, since they do not bundle:
|
|
374
|
+
* each module that imports one fails alone when the document shows it (`app` rejects when the whole does not bundle).
|
|
375
|
+
*/
|
|
376
|
+
codeFindings?(dir: string): Finding[]
|
|
355
377
|
close(): Promise<void>
|
|
356
378
|
}
|
|
357
379
|
|
package/src/lower-myst.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import { escapeHtml as escape
|
|
1
|
+
import { escapeHtml as escape } from './escape-html.ts'
|
|
2
|
+
import { mapHtmlUrls } from './html.ts'
|
|
3
|
+
import { isButton, roleMark } from './myst-marks.ts'
|
|
2
4
|
import type { MdastNode } from './ir.ts'
|
|
3
5
|
|
|
4
6
|
export type LinkedType = 'image' | 'link' | 'definition'
|
|
@@ -198,11 +200,6 @@ function cardsAs(options: LowerOptions): 'element' | 'headings' {
|
|
|
198
200
|
return options.cards ?? (options.iframes === 'element' ? 'element' : 'headings')
|
|
199
201
|
}
|
|
200
202
|
|
|
201
|
-
/** Whether a MyST node has the class `button`, which renders a link or span as a button. */
|
|
202
|
-
export function isButton(node: MdastNode): boolean {
|
|
203
|
-
return typeof node.class === 'string' && node.class.split(/\s+/).includes('button')
|
|
204
|
-
}
|
|
205
|
-
|
|
206
203
|
function layout(node: MdastNode, ctx: Lowering): MdastNode[] {
|
|
207
204
|
const all = (nodes: MdastNode[] = []) => nodes.flatMap(child => lower(child, ctx))
|
|
208
205
|
const element = cardsAs(ctx.options) === 'element'
|
|
@@ -248,12 +245,6 @@ function layout(node: MdastNode, ctx: Lowering): MdastNode[] {
|
|
|
248
245
|
return all(items)
|
|
249
246
|
}
|
|
250
247
|
|
|
251
|
-
export function roleMark(node: MdastNode): string {
|
|
252
|
-
const options = typeof node.options === 'object' && node.options !== null ? node.options as Record<string, unknown> : {}
|
|
253
|
-
const value = typeof options.value === 'string' ? options.value.trim() : ''
|
|
254
|
-
return `〔${String(node.name ?? '')}${value ? ` ${value}` : ''}〕`
|
|
255
|
-
}
|
|
256
|
-
|
|
257
248
|
function footnoteNumber(node: MdastNode): string {
|
|
258
249
|
return String(node.enumerator ?? node.label ?? node.identifier)
|
|
259
250
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { MdastNode } from './ir.ts'
|
|
2
|
+
|
|
3
|
+
// What a viewer reads from MyST nodes as they are, apart from their lowering (`lower-myst.ts`), which rewrites HTML.
|
|
4
|
+
|
|
5
|
+
/** Whether a MyST node has the class `button`, which renders a link or span as a button. */
|
|
6
|
+
export function isButton(node: MdastNode): boolean {
|
|
7
|
+
return typeof node.class === 'string' && node.class.split(/\s+/).includes('button')
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** The mark a role without content shows: its name and value. */
|
|
11
|
+
export function roleMark(node: MdastNode): string {
|
|
12
|
+
const options = typeof node.options === 'object' && node.options !== null ? node.options as Record<string, unknown> : {}
|
|
13
|
+
const value = typeof options.value === 'string' ? options.value.trim() : ''
|
|
14
|
+
return `〔${String(node.name ?? '')}${value ? ` ${value}` : ''}〕`
|
|
15
|
+
}
|
|
@@ -24,7 +24,7 @@ export const DOCUMENT_AUTHORING_ACTION_SCHEMA: Schema = {
|
|
|
24
24
|
...object({ id, source: DOCUMENT_PAGE_DUPLICATION_SCHEMA.properties.source as unknown as Schema, action: { $ref: '#/$defs/AuthoringAction' } }),
|
|
25
25
|
$defs: { ...(structuredClone(DOCUMENT_JSON_SCHEMA) as Exclude<Schema, boolean>).$defs,
|
|
26
26
|
AuthoringAction: { oneOf: [
|
|
27
|
-
action('comment.create', { content, anchor: { oneOf: [{ type: 'null' }, object({ from: { $ref: '#/$defs/TextPoint' }, to: { $ref: '#/$defs/TextPoint' } })] }, metadata, commentMetadata: metadata }, ['content', 'anchor']),
|
|
27
|
+
action('comment.create', { content, anchor: { oneOf: [{ type: 'null' }, object({ from: { $ref: '#/$defs/TextPoint' }, to: { $ref: '#/$defs/TextPoint' } }), object({ blockId: id, stepId: id }, ['blockId'])] }, metadata, commentMetadata: metadata }, ['content', 'anchor']),
|
|
28
28
|
action('comment.reply', { threadId: id, content, metadata }, ['threadId', 'content']),
|
|
29
29
|
action('comment.update', { threadId: id, commentId: id, content, metadata }, ['threadId', 'commentId', 'content']),
|
|
30
30
|
action('comment.react', { threadId: id, commentId: id, emoji: { type: 'string', minLength: 1, maxLength: 32 }, active: { type: 'boolean' } }),
|
package/src/node/fonts.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, realpathSync } from 'node:fs'
|
|
2
2
|
import { createRequire, findPackageJSON } from 'node:module'
|
|
3
3
|
|
|
4
4
|
export const FONT_LICENSE = 'presmium/fonts/LICENSE'
|
|
@@ -10,8 +10,11 @@ const FONT_COPYRIGHTS: Record<string, string> = {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export function fontLicense(from: string | URL): string {
|
|
13
|
-
const
|
|
14
|
-
if (!
|
|
13
|
+
const found = findPackageJSON('@lincyaw/host', from)
|
|
14
|
+
if (!found) throw new Error('@lincyaw/host is not installed')
|
|
15
|
+
// findPackageJSON keeps the symlinked path; the fonts are host's own dependencies, which an isolated store (pnpm's
|
|
16
|
+
// global store) puts beside the real package, so they are resolved from there.
|
|
17
|
+
const manifest = realpathSync(found)
|
|
15
18
|
const { dependencies = {} } = JSON.parse(readFileSync(manifest, 'utf8')) as { dependencies?: Record<string, string> }
|
|
16
19
|
const require = createRequire(manifest)
|
|
17
20
|
const files = Object.keys(dependencies).filter(name => name.startsWith('@fontsource/')).sort().map((name) => {
|
package/src/node/index.ts
CHANGED
|
@@ -27,3 +27,5 @@ export { validateProjectPlan, validateProjectApply } from './projects.ts'
|
|
|
27
27
|
export { validateDocumentWorkspaceImageInspect, validateDocumentWorkspaceImageImport } from './document-image.ts'
|
|
28
28
|
export { systemLocale } from './locale.ts'
|
|
29
29
|
export { OperatorSpeechSettings, operatorSpeechSecrets, SpeechSettingsError } from './operator-speech.ts'
|
|
30
|
+
export { devStateFile, readServiceState, removeServiceState, serveStateDir } from './service-state.ts'
|
|
31
|
+
export type { ServiceState } from './service-state.ts'
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { readFileSync, rmSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { isRecord } from '../errors.ts'
|
|
6
|
+
|
|
7
|
+
/** What a running Presmium server records for local clients: its address, its MCP endpoint and token, its process. */
|
|
8
|
+
export interface ServiceState {
|
|
9
|
+
url: string
|
|
10
|
+
mcp: string
|
|
11
|
+
token: string
|
|
12
|
+
pid: number
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The state directory of the workspace service (`presmium serve`, and the one `presmium studio` starts) of `root`. */
|
|
16
|
+
export function serveStateDir(root: string, env: NodeJS.ProcessEnv = process.env): string {
|
|
17
|
+
const base = env.XDG_CACHE_HOME || join(homedir(), '.cache')
|
|
18
|
+
return join(base, 'presmium', 'serve', createHash('sha256').update(root).digest('hex').slice(0, 16))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The state file `presmium dev` writes beside the document it previews. */
|
|
22
|
+
export function devStateFile(deckDir: string): string {
|
|
23
|
+
return join(deckDir, '.presmium', 'server.json')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const alive = (pid: number): boolean => {
|
|
27
|
+
try {
|
|
28
|
+
process.kill(pid, 0)
|
|
29
|
+
return true
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The state of the server that wrote `file`, while that process runs. */
|
|
36
|
+
export function readServiceState(file: string): ServiceState | undefined {
|
|
37
|
+
try {
|
|
38
|
+
const state: unknown = JSON.parse(readFileSync(file, 'utf8'))
|
|
39
|
+
if (!isRecord(state) || typeof state.url !== 'string' || typeof state.mcp !== 'string' || typeof state.token !== 'string' || typeof state.pid !== 'number') return undefined
|
|
40
|
+
return alive(state.pid) ? { url: state.url, mcp: state.mcp, token: state.token, pid: state.pid } : undefined
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Removes `file` when it is still this process's: a server that stopped leaves no address behind. */
|
|
47
|
+
export function removeServiceState(file: string, pid = process.pid): void {
|
|
48
|
+
try {
|
|
49
|
+
const state: unknown = JSON.parse(readFileSync(file, 'utf8'))
|
|
50
|
+
if (isRecord(state) && state.pid === pid) rmSync(file, { force: true })
|
|
51
|
+
} catch {}
|
|
52
|
+
}
|
package/src/preview-events.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { PREVIEW_EVENTS_PARAM, previewEnvelope } from './contracts/preview.ts'
|
|
2
2
|
import type { PreviewCommand, PreviewEventSubscription, PreviewEventTarget, PreviewEventMessage } from './contracts/preview.ts'
|
|
3
|
-
import { previewNonce } from './preview-frame.ts'
|
|
3
|
+
import { parentOrigins, previewNonce } from './preview-frame.ts'
|
|
4
|
+
import { randomUUID } from './random-uuid.ts'
|
|
4
5
|
|
|
5
6
|
/** Uses the existing preview-ready handshake, origin fence and nonce; never opens a network connection. */
|
|
6
7
|
export interface PreviewEvents {
|
|
@@ -14,11 +15,12 @@ export function createPreviewEvents(origins: readonly string[], document: string
|
|
|
14
15
|
if (typeof window === 'undefined' || window.parent === window || !origins.length || new URL(location.href).searchParams.get(PREVIEW_EVENTS_PARAM) !== 'shared') return
|
|
15
16
|
const nonce = previewNonce()
|
|
16
17
|
if (!nonce) return
|
|
17
|
-
const connection =
|
|
18
|
+
const connection = randomUUID()
|
|
18
19
|
const readers = new Map<string, { target: PreviewEventTarget, received(message: PreviewEventMessage): void }>()
|
|
19
20
|
let ready = false, stopped = false, parked = false
|
|
21
|
+
const targets = parentOrigins(origins)
|
|
20
22
|
const post = (message: Parameters<typeof previewEnvelope>[1]) => {
|
|
21
|
-
if (!stopped) for (const origin of
|
|
23
|
+
if (!stopped) for (const origin of targets) window.parent.postMessage(previewEnvelope(nonce, message), origin)
|
|
22
24
|
}
|
|
23
25
|
const subscribe = (id: string, target: PreviewEventTarget) => post({ type: 'events-subscribe', connection, id, target })
|
|
24
26
|
const park = () => {
|
|
@@ -35,7 +37,7 @@ export function createPreviewEvents(origins: readonly string[], document: string
|
|
|
35
37
|
connection,
|
|
36
38
|
subscribe(target, received) {
|
|
37
39
|
if (stopped || target.document !== document) return () => {}
|
|
38
|
-
const id =
|
|
40
|
+
const id = randomUUID()
|
|
39
41
|
readers.set(id, { target, received })
|
|
40
42
|
if (ready && !parked) subscribe(id, target)
|
|
41
43
|
return () => { if (readers.delete(id)) post({ type: 'events-unsubscribe', connection, id }) }
|