Documentation
¶
Overview ¶
Package plug is the public SDK for writing Krate plugins in Go. A plugin is a standalone main package that calls plug.Serve with the hooks it implements; the Krate compiler launches it as a subprocess over HashiCorp go-plugin (net/rpc). The plugin author ships per-platform binaries, typically inside an npm package whose config points Krate at the right binary for the host.
Hook contracts mirror the JavaScript plugin surface: the compiler hands each hook a JSON context and expects the concrete Go types described below. Hook contexts are mutable - edit fields (or the *ast.Program for AfterParse) and return nil. Dispatch marshals the changed state back for the host to apply.
Index ¶
- Constants
- Variables
- func Log(args ...interface{})
- func ReadFile(projectRoot, spec string) (string, error)
- func ResolveFile(projectRoot, spec string) (string, error)
- func Serve(name string, hooks Hooks)
- func Warn(args ...interface{})
- func WriteFileToRoot(projectRoot, rel string, content []byte) error
- type Bridge
- type BuildArgs
- type BuildResultArgs
- type DispatchRequest
- type File
- type GeneratedPage
- type Hooks
- type KrateInfo
- type MarkdownArgs
- type PageArgs
- type PageResult
- type ParseArgs
- type PluginServer
- type RPCClient
- type RenderArgs
- type Result
- type Route
- type ServeRequestArgs
- type ServeResponseArgs
Constants ¶
const ( // ProtocolVersion identifies the wire contract between host and plugin. ProtocolVersion = 1 // MagicCookieKey and MagicCookieValue distinguish a Krate plugin process // from any other executable the host may be pointed at. MagicCookieKey = "KRATE_PLUGIN_MAGIC_COOKIE" MagicCookieValue = "f58a3d1f-9c86-4b2a-9e7f-8b3c2a1d4e5f" // PluginName is the go-plugin plugin type name in the plugin map. PluginName = "krate" )
Handshake constants shared by the plugin binary and the Krate host.
Variables ¶
var HandshakeConfig = plugin.HandshakeConfig{ ProtocolVersion: ProtocolVersion, MagicCookieKey: MagicCookieKey, MagicCookieValue: MagicCookieValue, }
HandshakeConfig is the go-plugin handshake both sides must agree on.
Functions ¶
func Log ¶ added in v0.4.0
func Log(args ...interface{})
Log writes a diagnostic line to stderr, prefixed with the plugin name. It is the Go counterpart of the JS `krate.log`.
func ReadFile ¶ added in v0.4.0
ReadFile resolves spec (see ResolveFile) and returns its contents as a string.
func ResolveFile ¶ added in v0.4.0
ResolveFile resolves a plugin file specifier to an absolute path without hand-rolling a node_modules walk. Absolute/relative paths are anchored to projectRoot and must stay inside it; bare specifiers resolve through node_modules first. Traversal outside projectRoot is rejected.
func Serve ¶
Serve launches the plugin subprocess protocol. Call it from main and do not return after invoking it; the plugin exits when the host shuts it down.
func Warn ¶ added in v0.4.0
func Warn(args ...interface{})
Warn writes a warning line to stderr, prefixed with the plugin name. It is the Go counterpart of the JS `krate.warn`.
func WriteFileToRoot ¶ added in v0.4.0
WriteFileToRoot writes content to rel, interpreted relative to projectRoot (e.g. "public/logo.svg"), creating parent directories as needed. A path that escapes projectRoot is rejected. It is the Go counterpart of the JS `krate.writeFileToRoot`.
Types ¶
type Bridge ¶
type Bridge struct {
Impl PluginServer
}
Bridge adapts the plugin binary and the Krate host to go-plugin. On the server side Server returns the Dispatch service; on the client side Client returns an RPCClient bound to the running subprocess.
type BuildArgs ¶
type BuildArgs struct {
Result
Root string `json:"root"`
ProjectRoot string `json:"projectRoot,omitempty"`
OutDir string `json:"outDir"`
PagesDir string `json:"pagesDir,omitempty"`
Version string `json:"version,omitempty"`
Config interface{} `json:"config,omitempty"`
Pages []string `json:"pages"`
GeneratedPages *[]GeneratedPage `json:"generatedPages,omitempty"`
DevMode bool `json:"devMode"`
}
BuildArgs is passed to BeforeBuild and GenerateRoutes.
type BuildResultArgs ¶
type BuildResultArgs struct {
Result
Root string `json:"root"`
ProjectRoot string `json:"projectRoot,omitempty"`
OutDir string `json:"outDir"`
PagesDir string `json:"pagesDir,omitempty"`
Version string `json:"version,omitempty"`
Config interface{} `json:"config,omitempty"`
Pages []PageResult `json:"pages"`
CSS string `json:"css"`
}
BuildResultArgs is passed to AfterBuild with every page's results.
type DispatchRequest ¶
type DispatchRequest struct {
Kind string `json:"kind"`
Hook string `json:"hook"`
Args json.RawMessage `json:"args"`
}
DispatchRequest is the gob-encoded unit of RPC. Kind distinguishes build hooks from serve-time hooks; the plugin returns a uniform result envelope.
type GeneratedPage ¶
GeneratedPage is a page file produced by a plugin that should enter the normal page pipeline.
type Hooks ¶
type Hooks struct {
// BeforeBuild runs before pages are compiled. Files/GeneratedPages set on
// the context are applied by the host.
BeforeBuild func(ctx *BuildArgs) error
// AfterParse runs after a page's source parses. ctx.Program carries the
// parsed program; edit it in place and the host renders the edited tree.
AfterParse func(ctx *ParseArgs) error
// AfterMarkdownParse runs after markdown pages render to HTML. ctx.HTML is
// the rendered markup before layout wrapping.
AfterMarkdownParse func(ctx *MarkdownArgs) error
// AfterRender runs after a page renders but before layout wrapping.
AfterRender func(ctx *RenderArgs) error
// GenerateRoutes runs after BeforeBuild. Set ctx.Routes to synthesize
// virtual pages alongside real source pages.
GenerateRoutes func(ctx *BuildArgs) error
// AfterPage runs after a page is fully built including layout wrapping.
AfterPage func(ctx *PageArgs) error
// AfterBuild runs once after every page is built.
AfterBuild func(ctx *BuildResultArgs) error
// ServeRequest runs at request time before a page is served. Set ctx.Action
// to "rewrite" (with ctx.NewURL) to rewrite the path or "respond" (with
// Status/Headers/Body) to short-circuit.
ServeRequest func(ctx *ServeRequestArgs) error
// ServeResponse runs at request time after a non-streaming response has
// been buffered. Edit Status/Headers/Body on the context to rewrite it.
ServeResponse func(ctx *ServeResponseArgs) error
}
Hooks groups the optional hook implementations a plugin provides. Only non-nil hooks are invoked. Every hook receives a mutable context pointer; return an error to abort the build/serve operation.
type KrateInfo ¶ added in v0.4.0
type KrateInfo struct {
// ProjectRoot is the absolute path to the project root.
ProjectRoot string `json:"projectRoot,omitempty"`
// OutDir is the absolute path to the output directory.
OutDir string `json:"outDir,omitempty"`
// PagesDir is the absolute path to the configured pages directory.
PagesDir string `json:"pagesDir,omitempty"`
// Version is the running Krate compiler version.
Version string `json:"version,omitempty"`
// DevMode is true during `krate dev`.
DevMode bool `json:"devMode,omitempty"`
// Pages is the current page list (paths).
Pages []string `json:"pages,omitempty"`
// Config is the resolved krate config object.
Config interface{} `json:"config,omitempty"`
}
KrateInfo carries build-wide metadata on hook contexts that do not already declare their own root/outDir fields. It mirrors the fields of the JS `krate` object so plugins get the same context in both runtimes.
type MarkdownArgs ¶
type MarkdownArgs struct {
Result
KrateInfo
Page string `json:"page"`
HTML string `json:"html"`
Title string `json:"title"`
Route string `json:"route"`
}
MarkdownArgs is passed to AfterMarkdownParse.
type PageArgs ¶
type PageArgs struct {
Result
KrateInfo
Page string `json:"page"`
OutName string `json:"outName"`
HTML string `json:"html"`
HeadHTML string `json:"headHTML"`
HasJS bool `json:"hasJS"`
}
PageArgs is passed to AfterPage with the final page output.
type PageResult ¶
type PageResult struct {
Page string `json:"page"`
OutName string `json:"outName"`
HTML string `json:"html"`
HeadHTML string `json:"headHTML"`
HasJS bool `json:"hasJS"`
}
PageResult describes one built page in AfterBuild.
type ParseArgs ¶
type ParseArgs struct {
Result
KrateInfo
Page string `json:"page"`
Program *ast.Program `json:"-"`
}
ParseArgs is passed to AfterParse. Program is reconstructed from the kind-tagged document the host sends; editing it and returning modifies the build.
func (*ParseArgs) UnmarshalJSON ¶
UnmarshalJSON hydrates the context, decoding the "program" document via the astjson codec into a live *ast.Program for the hook to edit.
type PluginServer ¶
type PluginServer interface {
Dispatch(req DispatchRequest, out *json.RawMessage) error
}
PluginServer is the net/rpc service object a plugin binary serves.
type RPCClient ¶
type RPCClient struct {
// contains filtered or unexported fields
}
RPCClient is the host-side handle to a running plugin.
func (*RPCClient) Dispatch ¶
func (c *RPCClient) Dispatch(kind, hook string, args json.RawMessage) (json.RawMessage, error)
Dispatch sends one hook invocation to the plugin and returns the raw output envelope JSON. Kind must be "build" or "serve".
type RenderArgs ¶
type RenderArgs struct {
Result
KrateInfo
Page string `json:"page"`
HTML string `json:"html"`
HeadHTML string `json:"headHTML"`
HasJS bool `json:"hasJS"`
RawCSS string `json:"rawCSS"`
}
RenderArgs is passed to AfterRender. HTML, HeadHTML and RawCSS are filled from the host and are mutable; their final values are applied by the host.
type Result ¶
type Result struct {
Files []File `json:"files,omitempty"`
Routes []Route `json:"routes,omitempty"`
GeneratedPages []GeneratedPage `json:"generatedPages,omitempty"`
HTML *string `json:"html,omitempty"`
HeadHTML *string `json:"headHTML,omitempty"`
RawCSS *string `json:"rawCSS,omitempty"`
Scripts []string `json:"scripts,omitempty"`
MetaTags []string `json:"metaTags,omitempty"`
// Ast is the edited program document for AfterParse. Set by Dispatch from
// ParseArgs.Program; plugins do not construct it directly.
Ast json.RawMessage `json:"ast,omitempty"`
}
Result is embedded in every hook context. Dispatch collects whatever the hook set and returns it to the host in the unified output envelope.
func (*Result) EmitFile ¶ added in v0.4.0
EmitFile appends a file to the hook's output. The host writes `files` into the output directory (outDir-relative paths, traversal-guarded). It is the Go counterpart of the JS `krate.emitFile`.
func (*Result) InjectCSS ¶ added in v0.4.0
InjectCSS appends raw CSS. It takes effect for the AfterRender hook. It is the Go counterpart of `krate.injectCSS`.
func (*Result) InjectHead ¶ added in v0.4.0
InjectHead appends markup to the page <head>. It takes effect for the AfterRender and AfterPage hooks; the host folds it into the context's own HeadHTML before applying. It is the Go counterpart of `krate.injectHead`.
type Route ¶
type Route struct {
Path string `json:"path"`
Content string `json:"content"`
Title string `json:"title"`
Layout string `json:"layout,omitempty"`
Data map[string]string `json:"data,omitempty"`
}
Route is a virtual page synthesized by a plugin.
type ServeRequestArgs ¶
type ServeRequestArgs struct {
Result
URL string `json:"url"`
Method string `json:"method"`
Path string `json:"path"`
Headers map[string]string `json:"headers"`
// Action is "continue", "rewrite", or "respond".
Action string `json:"action,omitempty"`
Status int `json:"status,omitempty"`
NewURL string `json:"newURL,omitempty"`
Body string `json:"body,omitempty"`
}
ServeRequestArgs is the request-time context for the ServeRequest hook.
type ServeResponseArgs ¶
type ServeResponseArgs struct {
Result
URL string `json:"url"`
Method string `json:"method"`
Path string `json:"path"`
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
ServeResponseArgs is the request-time context for the ServeResponse hook. It wraps a buffered non-streaming response.