Documentation
¶
Overview ¶
Package margo compiles Markdown into immutable semantic documents and projects them to HTML.
The shortest library path compiles one source, renders its semantic content, then places that content in a standalone HTML document:
compiler := margo.New()
document, err := compiler.Compile(ctx, margo.Source{
Name: "guide.md",
Content: markdown,
})
if err != nil {
return err
}
rendered, err := compiler.Render(ctx, document)
if err != nil {
return err
}
page, err := margo.RenderStandalone(rendered)
if err != nil {
return err
}
return page.Render(ctx, output)
A Compiler freezes its options at construction and supports concurrent Compile and Render calls. A compiled Document remains bound to the Compiler configuration that created it. Pass WithExtension to New to register optional integrations such as charts.
The root package is the common compile/render layer, not a high-level filesystem converter. Choose the boundary after rendering: use RenderStandalone for one offline HTML page, RenderHTML and RenderHTMLPage for a host-composed page, package site for linked-site artifacts, package deck for a presentation, and package pdf with pdf/chromium for browser-backed PDF output. The site, PDF, and deck packages document the additional publication and runtime-descriptor steps; the margo CLI is the shortest path when the host does not need to own those seams.
Check performs read-only compatibility analysis without rendering. Host applications own capability policy through WithHostPolicy and WithCheckPolicy; document metadata cannot grant capabilities. Raw HTML is denied by default; a trusted host can explicitly opt into authored HTML and iframe passthrough with WithUnsafeHTML.
RenderHTML exposes a semantic fragment and its dependency requirements. RenderHTMLPage composes that result into a host-owned page, while RenderStandalone creates Margo's self-contained document shell. Host-owned static sites can compose RenderHTML output; PDF and deck workflows reuse the same compilation and runtime contracts.
Package margo does not provide a production HTTP server. The margo serve CLI command is a local development preview with file watching and live reload.
templ: version: v0.3.1020
templ: version: v0.3.1020
templ: version: v0.3.1020
Index ¶
- Constants
- Variables
- func AssetHandler() http.Handler
- func CanonicalRuntimeProjection(report RuntimeReport) ([]byte, error)
- func HTMLAssetHandler() http.Handler
- func HTMLRequirementCapability(requirement HTMLRequirement) (string, error)
- func OutputSchema(kind SchemaKind) ([]byte, error)
- func RenderHTMLDependencies(requirements HTMLRequirements, mode HTMLDependencyMode) (templ.Component, error)
- func RenderHTMLPage(result *HTMLResult, input HTMLPageInput) (templ.Component, error)
- func RenderStandalone(result *RenderResult, options ...any) (templ.Component, error)
- func Schema(kind SchemaKind) ([]byte, error)
- func Standalone(result *RenderResult, options ...any) (templ.Component, error)
- func ValidateDocumentToken(token DocumentToken, value string) error
- func ValidateHTML(fragment string) error
- func ValidateRenderInstanceID(value RenderInstanceID) error
- func ValidateResourceSize(size int64, limits ResourceLimits) error
- func ValidateRuntimeDescriptor(descriptor RuntimeDescriptor) error
- func ValidateRuntimeReport(descriptor RuntimeDescriptor, executionID ExecutionID, report RuntimeReport) error
- func ValidateToken(name, value string) error
- type AdjacentMapper
- type ArtifactDigest
- type ArtifactFingerprint
- type ArtifactSink
- type AssetRef
- type AssetSet
- type AtomicFileSink
- type BlockedRequest
- type Brand
- type CheckAssetReader
- type CheckOption
- type ColorMode
- type CommitOutcome
- type CommitResult
- type Compiler
- type CompilerConfigFingerprint
- type Diagnostic
- type DiagnosticError
- type Document
- type DocumentFingerprint
- type DocumentPreferences
- type DocumentToken
- type EffectivePolicy
- type ExecutionID
- type ExtensionCheck
- type ExtensionFactory
- type ExtensionIdentity
- type ExtensionNode
- type ExtensionRegistration
- type ExtensionSession
- type FilesystemCheckAssetReader
- type FlatMapper
- type FontCheck
- type HTMLDependencyMode
- type HTMLFingerprint
- type HTMLMetadata
- type HTMLOption
- type HTMLPageInput
- type HTMLRequirement
- type HTMLRequirementKind
- type HTMLRequirements
- type HTMLResult
- type IframePolicy
- type InstanceAllocator
- type InstanceRegistry
- type LayoutMetrics
- type Manifest
- type ManifestEntry
- type Metadata
- type Option
- type OutputMapper
- type PDFMode
- type PageActions
- type PageMarginPreference
- type PagePreference
- type Policy
- type PreserveMapper
- type Projection
- type RawHTMLMode
- type ReferrerPolicy
- type RenderContext
- type RenderIDAllocator
- type RenderInstanceID
- type RenderOption
- type RenderResult
- func (r *RenderResult) Assets() AssetSet
- func (r *RenderResult) Content() templ.Component
- func (r *RenderResult) Diagnostics() []Diagnostic
- func (r *RenderResult) DocumentFingerprint() DocumentFingerprint
- func (r *RenderResult) Metadata() Metadata
- func (r *RenderResult) RuntimeDescriptor(instance RenderInstanceID) (RuntimeDescriptor, error)
- func (r *RenderResult) Target() RenderTarget
- type RenderTarget
- type ResourceLimits
- type RuntimeDescriptor
- type RuntimeReport
- type RuntimeStatus
- type RuntimeTask
- type RuntimeTaskReport
- type RuntimeTaskStatus
- type RuntimeValidationIdentity
- type RuntimeValidationRequest
- type SandboxToken
- type SchemaKind
- type Severity
- type Source
- type SourcePosition
- type Spool
- type SpoolOptions
- type StandaloneOption
- func WithAssetOverride(name string, asset AssetRef) StandaloneOption
- func WithBrand(brand Brand) StandaloneOption
- func WithPDFBrand(name string, logo AssetRef) StandaloneOption
- func WithPageDescription(description string) StandaloneOption
- func WithPageLanguage(language string) StandaloneOption
- func WithPageTitle(title string) StandaloneOption
- func WithStandaloneColorMode(mode ColorMode) StandaloneOption
- func WithStandaloneTheme(theme ThemeName) StandaloneOption
- func WithTableOfContents() StandaloneOption
- func WithThemeTokens(tokens map[DocumentToken]string) StandaloneOption
- type StdoutSink
- type TableSortMode
- type TargetProjections
- type TerminalReport
- type ThemeName
Constants ¶
const ( HTMLStylesURL = "/margo-assets/document.css" TableSortRuntimeURL = "/margo-assets/table-sort.js" CodeCopyRuntimeURL = "/margo-assets/code-copy.js" )
const ( // MinOutputBytes and MaxOutputBytes are the immutable root output policy // bounds. They are deliberately int64 so optional modules can copy the value // without narrowing it before their own checked arithmetic. MinOutputBytes int64 = 1 MaxOutputBytes int64 = 64 << 20 )
const ( ThemeModern = "modern" ThemeGoshtoso = "goshtoso" ThemeMinimal = "minimal" )
const MaxDocumentBytes int64 = 16 << 20
MaxDocumentBytes bounds source bytes before any renderer or extension runs.
const MaxPolicyBytes = 64 << 10
const RuntimeProtocolV1 = "margo-runtime/v1"
const RuntimeProtocolV2 = "margo-runtime/v2"
Variables ¶
var ( ErrCheckAssetOutsideRoot = errors.New("check asset is outside its source root") ErrCheckAssetTooLarge = errors.New("check asset exceeds its byte limit") ErrCheckAssetNotRegular = errors.New("check asset is not a regular file") )
var ( ErrNilDocument = errors.New("margo: nil document") ErrCompilerDocumentMismatch = errors.New("compiler.document_config_mismatch") )
Functions ¶
func AssetHandler ¶
AssetHandler serves only the embedded non-runtime asset set. Mount it at /assets/ in an embedded application.
func CanonicalRuntimeProjection ¶
func CanonicalRuntimeProjection(report RuntimeReport) ([]byte, error)
func HTMLAssetHandler ¶
func HTMLRequirementCapability ¶
func HTMLRequirementCapability(requirement HTMLRequirement) (string, error)
func OutputSchema ¶ added in v0.0.18
func OutputSchema(kind SchemaKind) ([]byte, error)
OutputSchema returns the exact JSON Schema shipped for a versioned Margo output envelope. These schemas are also available to the jsonschema fence through margo://schema/v1/output/<name> references.
func RenderHTMLDependencies ¶ added in v0.0.3
func RenderHTMLDependencies(requirements HTMLRequirements, mode HTMLDependencyMode) (templ.Component, error)
RenderHTMLDependencies materializes a validated requirement graph as HTML tags. Inline mode produces a self-contained component; local mode preserves the reviewed local URLs from the graph.
func RenderHTMLPage ¶
func RenderHTMLPage(result *HTMLResult, input HTMLPageInput) (templ.Component, error)
func RenderStandalone ¶
func RenderStandalone(result *RenderResult, options ...any) (templ.Component, error)
RenderStandalone assembles a deterministic, offline HTML component. The variadic any accepts both standalone options and the existing compiler WithTheme option for ergonomic compatibility; unsupported compiler options are rejected.
func Schema ¶ added in v0.0.5
func Schema(kind SchemaKind) ([]byte, error)
Schema returns detached exact bytes shipped with this Margo version.
func Standalone ¶
func Standalone(result *RenderResult, options ...any) (templ.Component, error)
Standalone is a short alias for RenderStandalone.
func ValidateDocumentToken ¶
func ValidateDocumentToken(token DocumentToken, value string) error
ValidateDocumentToken validates both the versioned key and a conservative value grammar. CSS declarations, URLs, braces, and control characters are never accepted through this API.
func ValidateHTML ¶
ValidateHTML validates a fragment against the versioned margo-html-v1 allowlist. It deliberately returns an error instead of rewriting unsafe markup so callers cannot mistake a partially sanitized tree for accepted document content.
func ValidateRenderInstanceID ¶
func ValidateRenderInstanceID(value RenderInstanceID) error
func ValidateResourceSize ¶
func ValidateResourceSize(size int64, limits ResourceLimits) error
ValidateResourceSize applies a positive configured limit without allowing integer wraparound or an accidental unlimited zero value.
func ValidateRuntimeDescriptor ¶
func ValidateRuntimeDescriptor(descriptor RuntimeDescriptor) error
func ValidateRuntimeReport ¶
func ValidateRuntimeReport(descriptor RuntimeDescriptor, executionID ExecutionID, report RuntimeReport) error
func ValidateToken ¶
ValidateToken accepts only bounded, value-only theme tokens. In particular, it never accepts CSS functions that can resolve host state or external data.
Types ¶
type AdjacentMapper ¶
type AdjacentMapper struct {
Extension string
}
AdjacentMapper writes the HTML sibling of a source file.
type ArtifactDigest ¶
type ArtifactDigest [32]byte
ArtifactDigest identifies the exact bytes emitted by an exporter.
func ArtifactDigestOf ¶
func ArtifactDigestOf(data []byte) ArtifactDigest
ArtifactDigestOf hashes the exact emitted bytes without a domain prefix.
func (ArtifactDigest) String ¶
func (f ArtifactDigest) String() string
type ArtifactFingerprint ¶
type ArtifactFingerprint [32]byte
ArtifactFingerprint identifies the deterministic meaning of one emitted artifact. It intentionally excludes transport-only execution identity.
func (ArtifactFingerprint) String ¶
func (f ArtifactFingerprint) String() string
type ArtifactSink ¶
type ArtifactSink interface {
Commit(context.Context, io.Reader, ArtifactDigest) (CommitResult, error)
}
ArtifactSink publishes a completely staged artifact. Implementations must not make destination bytes visible until the input has passed all pre-publication validation owned by the caller.
type AssetRef ¶
AssetRef identifies a validated asset and, for overrides, carries its already-materialized bytes. Callers cannot make an override fetch at render time.
func EmbeddedAsset ¶
EmbeddedAsset returns one of the assets reviewed into the binary.
type AssetSet ¶
type AssetSet struct {
IDs []string
}
AssetSet is the defensive asset identity projection for a result.
type AtomicFileSink ¶
AtomicFileSink stages one complete artifact beside its destination and publishes it with the platform's atomic no-replace primitive. O2 never replaces an existing destination; force replacement is owned by O3.
func (*AtomicFileSink) Commit ¶
func (s *AtomicFileSink) Commit(ctx context.Context, r io.Reader, expected ArtifactDigest) (CommitResult, error)
Commit implements ArtifactSink. Before the visibility linearization point, every failure is not_committed and the destination is left untouched. An ambiguous platform result is classified with a read-back instead of being guessed as a failed publication.
type BlockedRequest ¶
type Brand ¶
type Brand struct {
Header templ.Component
Logo AssetRef
LogoAlt string
Backdrop AssetRef
Watermark string
Stamps []string
Tokens map[DocumentToken]string
}
Brand is the trusted, declarative subset of standalone branding. Header and Footer are Go components; document-authored markup never populates them.
type CheckAssetReader ¶ added in v0.0.4
type CheckAssetReader interface {
ReadAsset(context.Context, string, string, int64) ([]byte, error)
}
CheckAssetReader supplies local assets to Check without coupling library users to the host filesystem.
type CheckOption ¶ added in v0.0.4
type CheckOption func(*checkConfig) error
CheckOption configures compatibility analysis.
func WithCheckAssetReader ¶ added in v0.0.4
func WithCheckAssetReader(reader CheckAssetReader) CheckOption
WithCheckAssetReader enables missing-asset and SVG compatibility checks.
func WithCheckExtension ¶ added in v0.0.4
func WithCheckExtension(registration ExtensionRegistration) CheckOption
WithCheckExtension enables an extension's read-only fence validation during compatibility analysis.
func WithCheckPolicy ¶ added in v0.0.4
func WithCheckPolicy(policy Policy) CheckOption
WithCheckPolicy evaluates compatibility against the same host capability ceiling used for compilation. Document metadata has no capability authority.
func WithCheckTarget ¶ added in v0.0.5
func WithCheckTarget(target RenderTarget) CheckOption
WithCheckTarget selects the output projection analyzed by Check.
func WithCheckUnsafeHTML ¶ added in v0.0.18
func WithCheckUnsafeHTML() CheckOption
WithCheckUnsafeHTML mirrors WithUnsafeHTML for the read-only compatibility checker. It is intentionally opt-in because raw HTML and iframe content are otherwise denied before any renderer is invoked.
type ColorMode ¶
type ColorMode string
ColorMode selects the light or dark Goshtoso token family independently from the document theme.
type CommitOutcome ¶
type CommitOutcome string
CommitOutcome describes what is known about a destination after an artifact sink returns. Sinks must never collapse an uncertain filesystem state into a successful commit or a claim that the destination is unchanged.
const ( CommitNotCommitted CommitOutcome = "not_committed" CommitCommitted CommitOutcome = "committed" CommitDurabilityUncertain CommitOutcome = "durability_uncertain" CommitUnknown CommitOutcome = "unknown" )
type CommitResult ¶
type CommitResult struct {
Outcome CommitOutcome
Target string
Digest ArtifactDigest
Bytes int64
}
CommitResult is the transport identity returned by an ArtifactSink.
type Compiler ¶
type Compiler struct {
// contains filtered or unexported fields
}
Compiler owns one immutable configuration snapshot and is safe for concurrent Compile and Render calls.
func (*Compiler) Render ¶
func (c *Compiler) Render(ctx context.Context, document *Document, options ...RenderOption) (*RenderResult, error)
Render creates an immutable result. Semantic rendering is added by the later render-plan task; this early contract still enforces compiler binding.
func (*Compiler) SupportsRenderIDAllocator ¶ added in v0.0.7
SupportsRenderIDAllocator reports whether every registered extension has opted into the deck render-wide identity capability.
type CompilerConfigFingerprint ¶
type CompilerConfigFingerprint [32]byte
CompilerConfigFingerprint identifies the frozen compiler configuration.
func (CompilerConfigFingerprint) String ¶
func (f CompilerConfigFingerprint) String() string
type Diagnostic ¶
type Diagnostic struct {
Code string `json:"code"`
Severity Severity `json:"severity"`
Source string `json:"source"`
Line int `json:"line"`
Column int `json:"column"`
Pointer string `json:"pointer"`
Message string `json:"message"`
Hint string `json:"hint"`
}
Diagnostic is a stable, serializable problem projection.
func Check ¶ added in v0.0.4
func Check(ctx context.Context, source Source, options ...CheckOption) ([]Diagnostic, error)
Check performs read-only compatibility analysis without rendering. Findings are deterministic and carry stable source positions and remediation hints.
type DiagnosticError ¶
type DiagnosticError struct {
Diagnostics []Diagnostic
}
DiagnosticError carries one or more stable diagnostics without exposing parser internals.
func (*DiagnosticError) Error ¶
func (e *DiagnosticError) Error() string
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is an immutable compiled source. Its internal representation is deliberately opaque so parser and policy details remain versioned internals.
func (*Document) Diagnostics ¶
func (d *Document) Diagnostics() []Diagnostic
Diagnostics returns a defensive slice copy.
type DocumentFingerprint ¶
type DocumentFingerprint [32]byte
DocumentFingerprint identifies the immutable compiled meaning.
func (DocumentFingerprint) MarshalJSON ¶
func (f DocumentFingerprint) MarshalJSON() ([]byte, error)
func (DocumentFingerprint) String ¶
func (f DocumentFingerprint) String() string
func (*DocumentFingerprint) UnmarshalJSON ¶
func (f *DocumentFingerprint) UnmarshalJSON(data []byte) error
type DocumentPreferences ¶ added in v0.0.5
type DocumentPreferences struct {
Page *PagePreference
Actions *PageActions
}
type DocumentToken ¶
type DocumentToken string
DocumentToken is the versioned, bounded CSS custom-property surface.
const ( TokenFontBody DocumentToken = "--document-font-body" TokenFontHeading DocumentToken = "--document-font-heading" TokenContentWidth DocumentToken = "--document-content-width" TokenLineHeight DocumentToken = "--document-line-height" TokenCodeTheme DocumentToken = "--document-code-theme" TokenPageBackground DocumentToken = "--document-page-background" )
type EffectivePolicy ¶
type EffectivePolicy struct {
RawHTML RawHTMLMode `json:"rawHTML"`
InputBytes int64 `json:"inputBytes"`
OutputBytes int64 `json:"outputBytes"`
Iframe *IframePolicy `json:"iframe,omitempty"`
AllowUnsafeHTML bool `json:"allowUnsafeHTML,omitempty"`
}
EffectivePolicy is the immutable intersection stored on a compiled Document. It is a value, not a pointer, so renderers cannot mutate the compiler's decision after Compile.
type ExecutionID ¶
type ExecutionID string
type ExtensionCheck ¶ added in v0.0.4
type ExtensionCheck func(context.Context, ExtensionNode) error
ExtensionCheck performs read-only preflight validation for one detached fence payload under the same immutable extension configuration.
type ExtensionFactory ¶
type ExtensionFactory func(RenderContext) (ExtensionSession, error)
ExtensionFactory creates an independent render session for one operation.
type ExtensionIdentity ¶
type ExtensionIdentity struct {
Name string `json:"name"`
Version string `json:"version"`
ConfigurationHash string `json:"configurationHash,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
}
ExtensionIdentity is the stable, serialized identity of one registered extension. ConfigurationHash is optional for the small root fixtures but is included in the compiler fingerprint whenever supplied.
type ExtensionNode ¶
type ExtensionNode struct {
Fence string
// Info is the complete fenced-code info string, including the fence name
// and any optional key/value arguments after it. Extensions that need a
// source reference (for example, jsonschema) can interpret it without
// having to re-parse Goldmark nodes.
Info string
Payload []byte
Source SourcePosition
// BaseURL and AssetReader are populated for compatibility checks. They are
// intentionally optional so existing third-party extensions remain source
// compatible while extensions can safely resolve bounded local resources.
BaseURL string
AssetReader CheckAssetReader
// Target identifies the output projection being checked. Rendered
// extension nodes leave this unset because render options are applied
// after compilation; compatibility checkers can use it for target-specific
// authoring contracts.
Target RenderTarget
// contains filtered or unexported fields
}
ExtensionNode is an immutable detached fence payload.
type ExtensionRegistration ¶
type ExtensionRegistration struct {
Identity ExtensionIdentity
Fences []string
Factory ExtensionFactory
Check ExtensionCheck
// contains filtered or unexported fields
}
ExtensionRegistration binds one immutable factory to its owned fences.
type ExtensionSession ¶
ExtensionSession is a per-render instance returned by a factory.
type FilesystemCheckAssetReader ¶ added in v0.0.4
type FilesystemCheckAssetReader struct{}
FilesystemCheckAssetReader reads bounded regular files after resolving symlinks and proving that the real target remains below the real root.
type FlatMapper ¶
FlatMapper writes each known source file directly below OutputDir.
type HTMLDependencyMode ¶
type HTMLDependencyMode string
const ( HTMLDependenciesLocal HTMLDependencyMode = "local" HTMLDependenciesInline HTMLDependencyMode = "inline" )
type HTMLFingerprint ¶
type HTMLFingerprint [32]byte
func (HTMLFingerprint) String ¶
func (f HTMLFingerprint) String() string
type HTMLMetadata ¶
type HTMLMetadata struct {
Title string `json:"title"`
Description string `json:"description"`
Language string `json:"language"`
Slug string `json:"slug"`
Authors []string `json:"authors,omitempty"`
PublishedAt string `json:"publishedAt,omitempty"`
ModifiedAt string `json:"modifiedAt,omitempty"`
Tags []string `json:"tags,omitempty"`
}
type HTMLOption ¶
type HTMLOption func(*htmlConfig) error
func WithHTMLHeader ¶
func WithHTMLHeader() HTMLOption
type HTMLPageInput ¶
type HTMLPageInput struct {
Theme ThemeName
ColorMode ColorMode
DependencyMode HTMLDependencyMode
ThemeStylesheet AssetRef
Head templ.Component
Header templ.Component
BeforeContent templ.Component
// contains filtered or unexported fields
}
HTMLPageInput configures a generic complete HTML document. Head, Header, BeforeContent, and Footer are caller-owned composition seams; Margo does not infer canonical URLs, social metadata, or publication semantics here.
type HTMLRequirement ¶
type HTMLRequirementKind ¶
type HTMLRequirementKind string
const ( HTMLStylesheet HTMLRequirementKind = "stylesheet" HTMLScript HTMLRequirementKind = "script" HTMLRuntimeRole HTMLRequirementKind = "runtime-role" )
type HTMLRequirements ¶
type HTMLRequirements struct {
// contains filtered or unexported fields
}
func MergeHTMLRequirements ¶ added in v0.0.3
func MergeHTMLRequirements(groups ...HTMLRequirements) (HTMLRequirements, error)
MergeHTMLRequirements validates, deduplicates, and dependency-orders one or more requirement groups without exposing Margo's internal storage.
func (HTMLRequirements) List ¶
func (r HTMLRequirements) List() []HTMLRequirement
type HTMLResult ¶
type HTMLResult struct {
// contains filtered or unexported fields
}
func RenderHTML ¶
func RenderHTML(result *RenderResult, options ...HTMLOption) (*HTMLResult, error)
func (*HTMLResult) Diagnostics ¶
func (r *HTMLResult) Diagnostics() []Diagnostic
func (*HTMLResult) Fingerprint ¶
func (r *HTMLResult) Fingerprint() HTMLFingerprint
func (*HTMLResult) Fragment ¶
func (r *HTMLResult) Fragment() templ.Component
func (*HTMLResult) Metadata ¶
func (r *HTMLResult) Metadata() HTMLMetadata
func (*HTMLResult) PlainText ¶
func (r *HTMLResult) PlainText() string
func (*HTMLResult) Requirements ¶
func (r *HTMLResult) Requirements() HTMLRequirements
type IframePolicy ¶ added in v0.0.5
type IframePolicy struct {
AllowedOrigins []string `json:"allowedOrigins"`
Sandbox []SandboxToken `json:"sandbox"`
ReferrerPolicy ReferrerPolicy `json:"referrerPolicy"`
Projections TargetProjections `json:"projections"`
}
IframePolicy is host-owned. Documents provide only src, title, width, and height; they cannot widen these capabilities.
type InstanceAllocator ¶
type InstanceAllocator struct {
// contains filtered or unexported fields
}
func NewInstanceAllocator ¶
func NewInstanceAllocator() *InstanceAllocator
func (*InstanceAllocator) Next ¶
func (a *InstanceAllocator) Next() (RenderInstanceID, error)
type InstanceRegistry ¶
type InstanceRegistry struct {
// contains filtered or unexported fields
}
func NewInstanceRegistry ¶
func NewInstanceRegistry() *InstanceRegistry
func (*InstanceRegistry) Reserve ¶
func (r *InstanceRegistry) Reserve(value RenderInstanceID) error
type LayoutMetrics ¶
type LayoutMetrics struct {
ScrollWidth int64 `json:"scrollWidth"`
ScrollHeight int64 `json:"scrollHeight"`
}
LayoutMetrics is the quantized layout projection used by artifact identity. Runtime implementations may carry richer metrics in their own schema; C8 only commits the stable dimensions needed by the core identity seam.
type Manifest ¶
type Manifest struct {
Entries []ManifestEntry `json:"entries"`
}
Manifest is a defensive, deterministic collection of output identities.
type ManifestEntry ¶
type ManifestEntry struct {
Path string `json:"path"`
Digest ArtifactDigest `json:"digest"`
}
ManifestEntry binds one output path to its exact artifact bytes.
type Metadata ¶
type Metadata struct {
Name string
BaseURL string
Title string
Description string
Language string
Slug string
Authors []string
PublishedAt string
ModifiedAt string
Tags []string
Margo DocumentPreferences
Additional map[string]any
}
Metadata is the immutable normalized metadata projection exposed by a RenderResult. Additional frontmatter fields are added by the parser task.
type Option ¶
type Option func(*compilerConfig) error
Option configures a Compiler before it is frozen by New.
func WithExtension ¶
func WithExtension(registration ExtensionRegistration) Option
WithExtension registers one factory before New freezes the registry.
func WithHostPolicy ¶
WithHostPolicy supplies the host ceiling. Validation happens at Compile so an invalid value produces a stable diagnostic rather than a construction panic.
func WithTheme ¶
WithTheme is the small root theme option consumed by the C4 binding tests; the full token/theme registry is owned by later root tasks.
func WithUnsafeHTML ¶ added in v0.0.18
func WithUnsafeHTML() Option
WithUnsafeHTML opts a compiler into passing through document-authored HTML, including arbitrary iframe markup. The option is intentionally separate from Policy so a project cannot accidentally persist this capability in a reusable policy file; callers must make the decision at compiler setup.
type OutputMapper ¶
OutputMapper maps one known source file to one output path. It performs no discovery, globbing, collision resolution, or filesystem writes.
type PDFMode ¶ added in v0.0.6
type PDFMode string
PDFMode selects how a site's PDF action is fulfilled.
type PageActions ¶ added in v0.0.6
type PageActions struct {
Markdown bool `json:"markdown,omitempty"`
PDF bool `json:"pdf,omitempty"`
PDFMode PDFMode `json:"pdfMode,omitempty"`
PrintChartData bool `json:"printChartData,omitempty"`
}
PageActions selects optional artifacts and controls emitted by a site generator. PDF publication also retains the Markdown source for the page.
func (PageActions) EffectivePDFMode ¶ added in v0.0.6
func (actions PageActions) EffectivePDFMode() PDFMode
func (PageActions) UsesClientPDF ¶ added in v0.0.6
func (actions PageActions) UsesClientPDF() bool
type PageMarginPreference ¶ added in v0.0.5
PageMarginPreference keeps every side optional so an author can override one side without discarding the built-in values for the others. Pointers distinguish an omitted side from an explicit zero used for full bleed.
type PagePreference ¶ added in v0.0.5
type PagePreference struct {
Size string
Orientation string
ImageOverflow string
Margins *PageMarginPreference
}
type Policy ¶
type Policy struct {
SchemaVersion string `json:"schemaVersion,omitempty"`
RawHTML RawHTMLMode `json:"rawHTML"`
InputBytes int64 `json:"inputBytes"`
OutputBytes int64 `json:"outputBytes"`
Iframe *IframePolicy `json:"iframe,omitempty"`
}
Policy describes a host capability ceiling. A zero Policy is not a valid explicit host policy; callers that do not provide one receive the built-in deny/MaxOutputBytes ceiling.
func DefaultPolicy ¶ added in v0.0.5
func DefaultPolicy() Policy
DefaultPolicy returns the least-authoritative host policy and documented resource defaults for this Margo version.
func ParsePolicyJSON ¶ added in v0.0.5
ParsePolicyJSON validates canonical v1 JSON before applying documented defaults and semantic origin normalization.
type PreserveMapper ¶
PreserveMapper preserves a source file's path relative to SourceRoot under OutputDir.
type Projection ¶ added in v0.0.5
type Projection string
Projection selects how an authorized iframe is represented for one target.
const ( ProjectionDeny Projection = "deny" ProjectionStaticLink Projection = "static-link" ProjectionInteractive Projection = "interactive" )
type RawHTMLMode ¶
type RawHTMLMode string
RawHTMLMode is the versioned raw-HTML capability vocabulary.
const ( RawHTMLDeny RawHTMLMode = "deny" RawHTMLSanitized RawHTMLMode = "sanitized" )
type ReferrerPolicy ¶ added in v0.0.5
type ReferrerPolicy string
const ReferrerNoReferrer ReferrerPolicy = "no-referrer"
type RenderContext ¶
type RenderContext struct {
EffectivePolicy EffectivePolicy
}
RenderContext is the only root-to-extension policy delivery seam. It is a value so a session cannot mutate the compiler or another render operation.
type RenderIDAllocator ¶ added in v0.0.7
type RenderIDAllocator interface {
Allocate(kind, sourceKey string) string
Resolve(kind, sourceKey string) (string, bool)
}
RenderIDAllocator is the render-wide identity capability used by deck and trusted extensions. The pair (kind, sourceKey) is idempotent and resolves to one stable HTML ID for the lifetime of a render.
type RenderInstanceID ¶
type RenderInstanceID string
type RenderOption ¶
type RenderOption func(*renderOptions) error
RenderOption configures one immutable render operation.
func WithRenderIDAllocator ¶ added in v0.0.7
func WithRenderIDAllocator(allocator RenderIDAllocator) RenderOption
WithRenderIDAllocator provides a trusted render-wide identity allocator.
func WithRenderTarget ¶ added in v0.0.5
func WithRenderTarget(target RenderTarget) RenderOption
WithRenderTarget selects iframe and security projection for this render. Omission defaults to HTML for backward-compatible library calls.
func WithTableSort ¶
func WithTableSort(mode TableSortMode) RenderOption
WithTableSort selects the table sorting projection for one render.
type RenderResult ¶
type RenderResult struct {
// contains filtered or unexported fields
}
RenderResult is an immutable render projection safe for concurrent access.
func PrepareHTMLRenderResult ¶ added in v0.0.7
func PrepareHTMLRenderResult(result *RenderResult) (*RenderResult, error)
PrepareHTMLRenderResult relocates trusted chart extension scripts out of an editorial fragment and into the result's dependency graph. Complete HTML shells (standalone pages and presentation decks) can then place those dependencies in their own lifecycle-controlled region without weakening the fragment policy that rejects executable markup.
func (*RenderResult) Assets ¶
func (r *RenderResult) Assets() AssetSet
Assets returns a defensive asset copy.
func (*RenderResult) Content ¶
func (r *RenderResult) Content() templ.Component
Content returns the immutable templ component.
func (*RenderResult) Diagnostics ¶
func (r *RenderResult) Diagnostics() []Diagnostic
Diagnostics returns a defensive diagnostic slice.
func (*RenderResult) DocumentFingerprint ¶ added in v0.0.3
func (r *RenderResult) DocumentFingerprint() DocumentFingerprint
func (*RenderResult) Metadata ¶
func (r *RenderResult) Metadata() Metadata
Metadata returns a defensive metadata copy.
func (*RenderResult) RuntimeDescriptor ¶ added in v0.0.3
func (r *RenderResult) RuntimeDescriptor(instance RenderInstanceID) (RuntimeDescriptor, error)
func (*RenderResult) Target ¶ added in v0.0.5
func (r *RenderResult) Target() RenderTarget
Target returns the normalized output target used for this render.
type RenderTarget ¶ added in v0.0.5
type RenderTarget string
RenderTarget selects one explicit artifact projection without changing the target-neutral compiled document.
const ( TargetHTML RenderTarget = "html" TargetSite RenderTarget = "site" TargetPDF RenderTarget = "pdf" TargetDeck RenderTarget = "deck" )
type ResourceLimits ¶
type ResourceLimits struct {
DocumentBytes int64
}
ResourceLimits contains the host's document resource ceilings.
type RuntimeDescriptor ¶
type RuntimeDescriptor struct {
Protocol string `json:"protocol"`
DocumentFingerprint DocumentFingerprint `json:"documentFingerprint"`
RenderInstanceID RenderInstanceID `json:"renderInstanceID"`
Tasks []RuntimeTask `json:"tasks"`
ValidationRequest *RuntimeValidationRequest `json:"validationRequest,omitempty"`
}
func ComposeRuntimeDescriptors ¶ added in v0.0.3
func ComposeRuntimeDescriptors(document DocumentFingerprint, instance RenderInstanceID, parts ...RuntimeDescriptor) (RuntimeDescriptor, error)
func ParseRuntimeDescriptor ¶
func ParseRuntimeDescriptor(data []byte) (RuntimeDescriptor, error)
type RuntimeReport ¶
type RuntimeReport struct {
Protocol string `json:"protocol"`
DocumentFingerprint DocumentFingerprint `json:"documentFingerprint"`
RenderInstanceID RenderInstanceID `json:"renderInstanceID"`
ExecutionID ExecutionID `json:"executionID"`
Status RuntimeStatus `json:"status"`
Tasks []RuntimeTaskReport `json:"tasks"`
FontChecks []FontCheck `json:"fontChecks"`
BlockedRequests []BlockedRequest `json:"blockedRequests"`
Layout LayoutMetrics `json:"layout"`
Diagnostic *Diagnostic `json:"diagnostic"`
ValidationIdentity *RuntimeValidationIdentity `json:"validationIdentity,omitempty"`
}
func ParseRuntimeReport ¶
func ParseRuntimeReport(data []byte) (RuntimeReport, error)
type RuntimeStatus ¶
type RuntimeStatus string
const ( RuntimePending RuntimeStatus = "pending" RuntimeRunning RuntimeStatus = "running" RuntimeReady RuntimeStatus = "ready" RuntimeFailed RuntimeStatus = "failed" )
type RuntimeTask ¶
type RuntimeTaskReport ¶
type RuntimeTaskStatus ¶
type RuntimeTaskStatus string
const ( RuntimeTaskPending RuntimeTaskStatus = "pending" RuntimeTaskRunning RuntimeTaskStatus = "running" RuntimeTaskSucceeded RuntimeTaskStatus = "succeeded" RuntimeTaskFailed RuntimeTaskStatus = "failed" )
type RuntimeValidationIdentity ¶ added in v0.0.7
type RuntimeValidationIdentity struct {
BrowserProfile string `json:"browserProfile"`
EngineName string `json:"engineName"`
EngineVersion string `json:"engineVersion"`
PlatformProfile string `json:"platformProfile"`
FontBundleDigest string `json:"fontBundleDigest"`
}
RuntimeValidationIdentity records values observed by the validator rather than caller assertions.
func (RuntimeValidationIdentity) Validate ¶ added in v0.0.7
func (identity RuntimeValidationIdentity) Validate() error
type RuntimeValidationRequest ¶ added in v0.0.7
type RuntimeValidationRequest struct {
ViewportWidth uint `json:"viewportWidth"`
ViewportHeight uint `json:"viewportHeight"`
DeviceScaleFactor float64 `json:"deviceScaleFactor"`
Zoom float64 `json:"zoom"`
BrowserProfile string `json:"browserProfile"`
ExpectedFontBundleDigest string `json:"expectedFontBundleDigest"`
}
RuntimeValidationRequest is the profile-neutral request bound to a v2 descriptor. Deck owns the profile registry and derives the font digest; margo validates the wire shape and equality constraints.
func (RuntimeValidationRequest) Validate ¶ added in v0.0.7
func (request RuntimeValidationRequest) Validate() error
type SandboxToken ¶ added in v0.0.5
type SandboxToken string
const ( SandboxAllowPresentation SandboxToken = "allow-presentation" SandboxAllowScripts SandboxToken = "allow-scripts" )
type SchemaKind ¶ added in v0.0.5
type SchemaKind string
SchemaKind identifies one public, version-matched configuration or output schema. Output schemas describe the stable JSON envelopes emitted by the CLI and runtime integrations.
const ( SchemaPolicy SchemaKind = "policy" SchemaDocument SchemaKind = "document" SchemaSite SchemaKind = "site" SchemaDiagnostic SchemaKind = "diagnostic" SchemaDoctorReport SchemaKind = "doctor-report" SchemaCheckReport SchemaKind = "check-report" SchemaSiteReport SchemaKind = "site-report" SchemaSiteManifest SchemaKind = "site-manifest" SchemaRuntimeDescriptor SchemaKind = "runtime-descriptor" SchemaRuntimeReport SchemaKind = "runtime-report" SchemaDeckLayoutEvidence SchemaKind = "deck-layout-evidence" SchemaDeckPDFArtifactReport SchemaKind = "deck-pdf-artifact-report" )
type SourcePosition ¶
type SourcePosition struct {
Source string `json:"source"`
Line int `json:"line"`
Column int `json:"column"`
}
SourcePosition identifies a source location without exposing Goldmark segments as a public API.
type Spool ¶
type Spool struct {
// contains filtered or unexported fields
}
Spool accumulates one bounded artifact. It remains invisible to the caller's destination and spills to a mode-0600 private file after MemoryLimit.
func NewSpool ¶
func NewSpool(options SpoolOptions) *Spool
NewSpool creates a private bounded staging buffer. Zero limits select safe defaults; invalid negative limits are reported by the first write.
func (*Spool) Close ¶
Close removes private staging and makes the spool unusable. It is safe to call more than once.
func (*Spool) Digest ¶
func (s *Spool) Digest() ArtifactDigest
Digest returns the exact-byte digest accumulated so far.
func (*Spool) Reader ¶
func (s *Spool) Reader() (io.ReadCloser, error)
Reader returns a fresh replay reader positioned at byte zero.
func (*Spool) UsesPrivateFile ¶
UsesPrivateFile reports whether the memory threshold has been crossed.
type SpoolOptions ¶
SpoolOptions controls the private staging boundary used before publication.
type StandaloneOption ¶
type StandaloneOption func(*standaloneConfig) error
StandaloneOption configures the self-contained HTML shell.
func WithAssetOverride ¶
func WithAssetOverride(name string, asset AssetRef) StandaloneOption
WithAssetOverride supplies already-materialized bytes for one embedded asset.
func WithBrand ¶
func WithBrand(brand Brand) StandaloneOption
WithBrand applies trusted header/footer components and validated declarative brand values.
func WithPDFBrand ¶ added in v0.0.6
func WithPDFBrand(name string, logo AssetRef) StandaloneOption
WithPDFBrand applies PDFBrand after other standalone options. This keeps command-line title overrides visible in the generated footer.
func WithPageDescription ¶
func WithPageDescription(description string) StandaloneOption
WithPageDescription sets the optional escaped description.
func WithPageLanguage ¶ added in v0.0.4
func WithPageLanguage(language string) StandaloneOption
WithPageLanguage sets the document language using a BCP 47 language tag.
func WithPageTitle ¶
func WithPageTitle(title string) StandaloneOption
WithPageTitle sets the escaped document title.
func WithStandaloneColorMode ¶
func WithStandaloneColorMode(mode ColorMode) StandaloneOption
WithStandaloneColorMode selects the light or dark Goshtoso token family for both screen rendering and print/PDF projection.
func WithStandaloneTheme ¶
func WithStandaloneTheme(theme ThemeName) StandaloneOption
WithStandaloneTheme selects the closed theme set for standalone output.
func WithTableOfContents ¶
func WithTableOfContents() StandaloneOption
WithTableOfContents inserts one deterministic navigation landmark before the article. Entries cover heading levels two through four and reuse compiled IDs.
func WithThemeTokens ¶
func WithThemeTokens(tokens map[DocumentToken]string) StandaloneOption
WithThemeTokens applies only the supported, bounded token keys.
type StdoutSink ¶
StdoutSink copies only a completely validated spool to its writer. Unlike a filesystem sink, stdout cannot revoke bytes after a downstream short write.
func (StdoutSink) Commit ¶
func (s StdoutSink) Commit(ctx context.Context, r io.Reader, expected ArtifactDigest) (CommitResult, error)
type TableSortMode ¶
type TableSortMode string
TableSortMode is the bounded sorting vocabulary exposed by the root renderer. Server-side table behavior is deliberately not part of C5.
const (
TableSortClient TableSortMode = "client"
)
type TargetProjections ¶ added in v0.0.5
type TargetProjections struct {
HTML Projection `json:"html"`
Site Projection `json:"site"`
PDF Projection `json:"pdf"`
Deck Projection `json:"deck"`
}
TargetProjections keeps capability decisions independent per output target.
type TerminalReport ¶
type TerminalReport struct {
ProtocolVersion string
Document DocumentFingerprint
RenderInstanceID string
ExecutionID string
Kind string
Serializer string
Engine string
TerminalStatus string
TerminalDiagnostic string
PageConfiguration any
TaskInputHashes []string
TaskOutputHashes []string
FontChecks []string
BlockedRequests []string
Layout LayoutMetrics
}
TerminalReport is the immutable runtime projection consumed by artifact identity. ExecutionID routes a live execution and is deliberately excluded from the artifact preimage.
Source Files
¶
- artifact_sink.go
- assets.go
- atomic_file_sink.go
- atomic_unix.go
- brand.go
- check.go
- code_adapter.go
- compiler.go
- diagnostic.go
- doc.go
- document.go
- editorial.go
- editorial_fingerprint.go
- errors.go
- extension.go
- fingerprint.go
- frontmatter.go
- heading.go
- html_dependency.go
- html_page.go
- html_page_templ.go
- html_policy.go
- html_requirement.go
- iframe.go
- iframe_policy.go
- instance.go
- jsonschema.go
- manifest.go
- markdown.go
- mermaid.go
- metadata.go
- options.go
- output_mapper.go
- output_schema.go
- pdf_brand.go
- policy.go
- policy_json.go
- registry.go
- render.go
- render_nodes_templ.go
- render_plan.go
- resource_policy.go
- result.go
- runtime_descriptor.go
- runtime_projection.go
- runtime_report.go
- runtime_validation.go
- schema.go
- schema_generate.go
- source.go
- source_html.go
- source_media.go
- spool.go
- standalone.go
- standalone_templ.go
- stdout_sink.go
- table_adapter.go
- theme.go
- token_policy.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package charts provides optional chart integration for Margo.
|
Package charts provides optional chart integration for Margo. |
|
tools/optimistic-renderer
command
Command optimistic-renderer creates a deterministic standalone HTML review artifact with the optional Goshtoso Charts extension enabled.
|
Command optimistic-renderer creates a deterministic standalone HTML review artifact with the optional Goshtoso Charts extension enabled. |
|
cmd
|
|
|
margo
command
|
|
|
Package deck parses Margo Markdown and renders accessible HTML presentation decks.
|
Package deck parses Margo Markdown and renders accessible HTML presentation decks. |
|
examples
|
|
|
blog
command
|
|
|
blog/site
Package site builds the checked blog-style HTML example.
|
Package site builds the checked blog-style HTML example. |
|
internal
|
|
|
browserlaunch
Package browserlaunch centralizes host-browser process safeguards.
|
Package browserlaunch centralizes host-browser process safeguards. |
|
canonicaljson
Package canonicaljson provides the deterministic JSON byte routine used by Margo identity preimages.
|
Package canonicaljson provides the deterministic JSON byte routine used by Margo identity preimages. |
|
cmd/schema-docs
command
|
|
|
devserver
Package devserver implements Margo's development-only site server.
|
Package devserver implements Margo's development-only site server. |
|
htmlpolicy
Package htmlpolicy implements the closed margo-html-v1 fragment profile.
|
Package htmlpolicy implements the closed margo-html-v1 fragment profile. |
|
Package pdf defines renderer-neutral contracts for exporting Margo HTML to PDF.
|
Package pdf defines renderer-neutral contracts for exporting Margo HTML to PDF. |
|
chromium
Package chromium exports immutable Margo HTML through an explicitly selected installed Chromium-family executable.
|
Package chromium exports immutable Margo HTML through an explicitly selected installed Chromium-family executable. |
|
native
Package native defines the stable capability boundary for platform-native PDF engines.
|
Package native defines the stable capability boundary for platform-native PDF engines. |
|
platform
Package platform verifies the locked platform probe contract without selecting, downloading, or implementing a PDF engine.
|
Package platform verifies the locked platform probe contract without selecting, downloading, or implementing a PDF engine. |
|
Package site builds deterministic multi-page HTML sites from Markdown inputs.
|
Package site builds deterministic multi-page HTML sites from Markdown inputs. |
|
Package ssg contains the layout-neutral contract used by Margo static sites.
|
Package ssg contains the layout-neutral contract used by Margo static sites. |
|
tools
|
|
|
optimistic-renderer
command
Command optimistic-renderer creates a deterministic standalone HTML review artifact from one Markdown source file.
|
Command optimistic-renderer creates a deterministic standalone HTML review artifact from one Markdown source file. |