defineContentPlugin()

Author a plugin that adds typed methods to the Content instance.

defineContentPlugin(factory)

Defines a plugin. The factory receives the plugin's options and returns a { setup } object; setup receives the ContentPluginContext and returns the methods to merge onto the Content instance.

Parameters:

  • factory: (options?: TOptions) => { setup: (content: ContentPluginContext) => TMethods | void | Promise<TMethods | void> }.

Returns: a plugin factory (...args) => ContentPlugin<TMethods> to pass to comarkContent({ plugins }). The returned methods are typed onto the instance.

plugin.ts
import { defineContentPlugin } from 'comark-content'

export default defineContentPlugin<{ suffix?: string }>((options) => ({
  setup(content) {
    content.hooks.hook('file:upsert', (source, key) => {
      console.log('indexed', source, key)
    })
    return {
      hello: () => `hello${options?.suffix ?? ''}`,
    }
  },
}))

ContentPluginContext

The content handle passed to a plugin's setup. It exposes the manifest, cache, hooks, and registration helpers.

MemberTypeDescription
optionsContentOptionsThe resolved options the Content instance was created with.
hooksHookable<ContentHooks>Subscribe to content-change events.
cacheCacheThe resolved cache.
manifestManifestThe in-memory index.
init(opts?) => Promise<void>Trigger initialization.
stat(key) => ContentListFile | undefinedLook up one manifest entry.
getSource(name) => Source | undefinedGet a configured source.
loadSnapshot(source) => Promise<void>Hydrate a source's bodies from a snapshot.
addParser(extensions, parse) => voidRegister a Parser for new extensions.
addListingFields(extensions, fields) => voidTrim which data fields listings keep.
addServeHandler(section, handler) => voidAdd a custom section to handler().
update(source, file) => Promise<void>Upsert an entry.
remove(source, key) => Promise<void>Drop an entry.

Usage

Adding a data endpoint plus the client method that reads it is the canonical pattern, so the client/server contract lives in one place. Use addServeHandler to register a custom section on handler():

search-sections.ts
import { defineContentPlugin } from 'comark-content'

export default defineContentPlugin(() => ({
  setup(content) {
    content.addServeHandler('search-sections', () => jsonResponse(buildSearchSections(content)))
  },
}))

Register it with comarkContent({ plugins }), then read it from the browser with a matching defineContentClientPlugin.