From 4b84cfdc9063c37723adacb14ffb207a7e3b69ff Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 4 Nov 2026 18:41:39 -0500 Subject: [PATCH 01/15] docs: add Markdown SDK reference generator Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/release.yml | 3 + alias.go | 2 + bin/docs_scripts/generate_markdown.py | 258 ++++++++++++++++++++++++++ capture.go | 2 + config.go | 2 + docs/getting-started.md | 28 +++ error_tracking.go | 2 + error_tracking_slog.go | 2 + group_identify.go | 2 + identify.go | 2 + message.go | 2 + posthog.go | 30 +++ request_context.go | 4 + 13 files changed, 339 insertions(+) create mode 100644 bin/docs_scripts/generate_markdown.py create mode 100644 docs/getting-started.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0eb6e3e3..8bd4cf18 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,6 +129,9 @@ jobs: (cd "$MODULE" && go mod edit "-require=github.com/posthog/posthog-go@v${NEW_VERSION}") done + - name: Regenerate SDK reference + run: python3 bin/docs_scripts/generate_markdown.py --latest + - name: Check for version bump changes id: check-changes run: | diff --git a/alias.go b/alias.go index ee1ea162..aa3fdb59 100644 --- a/alias.go +++ b/alias.go @@ -9,6 +9,8 @@ var _ Message = (*Alias)(nil) // Alias represents an alias call that links another distinct ID to an existing user. // Enqueue validates that DistinctId and Alias are both set, fills Type, Uuid, // Timestamp, and DisableGeoIP, then sends the message as a $create_alias event. +// +// posthog-capability: alias type Alias struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/bin/docs_scripts/generate_markdown.py b/bin/docs_scripts/generate_markdown.py new file mode 100644 index 00000000..ad79b7a4 --- /dev/null +++ b/bin/docs_scripts/generate_markdown.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Generate the Markdown SDK reference with gomarkdoc (pinned, never a module dependency). + +gomarkdoc renders every symbol. This script only groups the symbols by the +`posthog-capability: ` line in their doc comment, orders them, and writes +front matter. Usage: generate_markdown.py [--source DIR] [--out DIR] [--latest] [--experimental] +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile + +GOMARKDOC = "github.com/princjef/gomarkdoc/cmd/gomarkdoc@v1.1.0" +REFERENCE_ID = "posthog-go" +NAME = "PostHog Go SDK" +CLIENT_CLASSES = ["FeatureFlagEvaluations"] # public classes that get their own H2 + +# Capabilities this SDK implements, in sdk-specs README order (setup, capture, identify first). +CAPABILITIES = [ + ("setup", "Setup"), ("capture", "Capture"), ("identify", "Identify"), ("alias", "Alias"), + ("capture-exception", "Capture exception"), ("flush", "Flush"), + ("get-feature-flag", "Get feature flag"), ("get-feature-flag-payload", "Get feature flag payload"), + ("get-feature-flag-result", "Get feature flag result"), ("get-feature-flags", "Get feature flags"), + ("evaluate-flags", "Evaluate flags"), ("group-identify", "Group identify"), + ("is-feature-enabled", "Is feature enabled"), ("reload-feature-flags", "Reload feature flags"), + ("shutdown", "Shutdown"), ("before-send-hook", "Before send hook"), +] +TAG = re.compile(r"^posthog\\?-capability: (\S+)$") # gomarkdoc escapes the hyphen +HEAD = re.compile(r"^(##|###) (func|type) (?:\\\(\\?\*?(\w+)\\\) )?(?:\[(\w+)\]|(\w+))") + + +class Sym: + def __init__(self, kind, recv, name, level, body): + self.kind, self.recv, self.name, self.level, self.body = kind, recv, name, level, body + self.tag = None + self.children = [] + + @property + def title(self): + return f"{self.recv}.{self.name}" if self.recv else self.name + + +def run_gomarkdoc(source): + out = os.path.join(tempfile.mkdtemp(), "gomarkdoc.md") + subprocess.run(["go", "run", GOMARKDOC, "--output", out, "."], cwd=source, check=True) + return open(out).read() + + +def split_symbols(text): + """Split gomarkdoc output into extra blocks (constants, variables) and symbols.""" + chunks, cur = [], None + in_fence = False + for line in text.split("\n"): + if line.startswith("```"): + in_fence = not in_fence + if not in_fence and re.match(r"^#{1,3} ", line): + cur = [line] + chunks.append(cur) + elif cur is not None and not line.startswith("]*>\)", r"`\1`", text) # gomarkdoc in-page links have no target here + text = re.sub(r"\n{3,}", "\n\n", text) + # MDX 1 reads raw < and { in prose as JSX: escape them outside code + parts = re.split(r"(```.*?```|`[^`\n]*`)", text, flags=re.S) + return "".join(p if i % 2 else re.sub(r"<(?!https?://|/?(?:details|summary|p)>)", "<", p) + .replace("\\{", "{").replace("\\}", "}").replace("{", "{").replace("}", "}") + for i, p in enumerate(parts)) + + +def render(sym, level): + return f"{'#' * level} `{sym.title}`\n\n{clean(sym.body)}\n\n" + "".join(render(c, level + 1) for c in sym.children) + + +def slug(title): + return re.sub(r"[^\w\- ]", "", title.lower()).replace(" ", "-") + + +def build(text): + syms, blocks = split_symbols(text) + flat, parent = [], None + for s in syms: + if s.level == 2: + parent = s if s.kind == "type" else None + elif parent is not None: # method or constructor nested under its type + parent.children.append(s) + continue + flat.append(s) + for s in list(flat): + if s.kind == "type" and any("interface {" in l for l in s.body): + s.children = expand_interface(s) + s.children + everything = [] + for s in flat: + everything.append(s) + everything += s.children + for s in everything: + pull_tag(s) + # tagged nested symbols move out of their type + for s in flat: + s.children = [c for c in s.children if c.tag is None] + sections = {slug_: [] for slug_, _ in CAPABILITIES} + utils, classes, types = [], [], [] + for s in flat: + if s.tag: + sections[s.tag].append(s) + elif s.name in CLIENT_CLASSES: + classes.append(s) + elif s.kind == "func": + utils.append(s) + else: + types.append(s) + for s in everything: + if s.tag and s not in flat: + sections[s.tag].append(s) # tagged method/constructor + unknown = {s.tag for s in everything if s.tag} - set(sections) + if unknown: + sys.exit(f"unknown capability tag(s): {sorted(unknown)}") + return sections, utils, classes, types, blocks + + +def write_migration(source, out): + """Concatenate docs/migration-v.md guides, newest first, under one page.""" + import glob + files = sorted(glob.glob(os.path.join(source, "docs", "migration-v*.md")), reverse=True, + key=lambda f: int(re.search(r"v(\d+)", os.path.basename(f))[1])) + if not files: + return + guides, fence = [], False + for f in files: + for line in open(f).read().strip().split("\n"): + fence ^= line.startswith("```") + guides.append("#" + line if re.match(r"^#+ ", line) and not fence else line) + guides.append("") + fm = f'---\ntitle: "{NAME} migration guides"\nsidebar: Docs\nshowTitle: true\n---\n\n' + with open(os.path.join(out, f"{REFERENCE_ID}-migration.md"), "w") as f: + f.write(fm + clean(guides) + "\n") + print("wrote", os.path.join(out, f"{REFERENCE_ID}-migration.md")) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--source", default=".") + ap.add_argument("--out", default="references") + ap.add_argument("--latest", action="store_true", help="also write the latest page") + ap.add_argument("--experimental", action="store_true", help="mark the major as unreleased") + a = ap.parse_args() + source = os.path.abspath(a.source) + mod = re.search(r"^module \S+?(?:/v(\d+))?$", open(os.path.join(source, "go.mod")).read(), re.M) + major = mod[1] or "1" + sections, utils, classes, types, blocks = build(run_gomarkdoc(source)) + + key = lambda s: (s.kind == "type", s.title) + body, toc = [], [] + + def h2(title, content): + toc.append(title) + body.append(f"## {title}\n\n{content.strip()}\n") + + gs = open(os.path.join(source, "docs", "getting-started.md")).read().strip() + h2("Getting started", re.sub(r"^(#+) ", r"#\1 ", gs, flags=re.M).split("\n", 2)[-1] if gs.startswith("# ") else gs) + for slug_, title in CAPABILITIES: + if sections[slug_]: + h2(title, "".join(render(s, 3) for s in sorted(sections[slug_], key=key))) + util = "".join(render(s, 3) for s in sorted(utils, key=key)) + for name in ("Constants", "Variables"): + if name in blocks: + util += f"### {name}\n\n{clean(blocks[name])}\n\n" + h2("SDK utils", util) + for c in classes: + h2(f"`{c.name}`", clean(c.body) + "\n\n" + "".join(render(x, 3) for x in sorted(c.children, key=key))) + h2("Types", "".join(render(s, 3) for s in sorted(types, key=key))) + + suffix = " (experimental)" if a.experimental else "" + def page(title): + fm = ["---", f'title: "{title}"', "sidebar: Docs", "showTitle: true", "contentMaxWidthClass: max-w-full", + "platformLogo: go", "tableOfContents:"] + for t in toc: + fm += [f' - value: "{t.replace("`", "")}"', f" url: {slug(t)}", " depth: 0"] + return "\n".join(fm + ["---", ""]) + "\n" + "\n".join(body) + + os.makedirs(a.out, exist_ok=True) + pages = {f"{REFERENCE_ID}-{major}.md": f"{NAME} {major}.x{suffix}"} + if a.latest: + pages[f"{REFERENCE_ID}-reference.md"] = NAME + for fname, title in pages.items(): + with open(os.path.join(a.out, fname), "w") as f: + f.write(page(title)) + print("wrote", os.path.join(a.out, fname)) + write_migration(source, a.out) + + +if __name__ == "__main__": + main() diff --git a/capture.go b/capture.go index 3650b0ca..6a408690 100644 --- a/capture.go +++ b/capture.go @@ -82,6 +82,8 @@ var _ Message = (*Capture)(nil) // Enqueue validates Event and DistinctId (or obtains DistinctId from request context), // fills Type, Uuid, and Timestamp, merges Config.DefaultEventProperties, and queues // the event for a future batch upload. +// +// posthog-capability: capture type Capture struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: PostHog ignores the top-level type field on capture events. Use Event for diff --git a/config.go b/config.go index 7e534891..5a505287 100644 --- a/config.go +++ b/config.go @@ -64,6 +64,8 @@ const ( // // Each exported field's zero value is either meaningful or replaced by the // default documented on that field. +// +// posthog-capability: setup type Config struct { // Endpoint is the PostHog API host used for event ingestion and feature flag requests. diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 00000000..7206fea5 --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,28 @@ +# Getting started + +Install the module (Go 1.21 or later): + +```bash +go get github.com/posthog/posthog-go +``` + +Create a client with your project API key, send an event, and close the client to flush the queue: + +```go +package main + +import "github.com/posthog/posthog-go" + +func main() { + client, _ := posthog.NewWithConfig("", posthog.Config{ + Endpoint: "", + }) + defer client.Close() // flushes queued events + + client.Enqueue(posthog.Capture{ + DistinctId: "user_123", + Event: "button_clicked", + Properties: posthog.NewProperties().Set("plan", "pro"), + }) +} +``` diff --git a/error_tracking.go b/error_tracking.go index 3ad4566a..4f6ccc55 100644 --- a/error_tracking.go +++ b/error_tracking.go @@ -10,6 +10,8 @@ var _ Message = (*Exception)(nil) // Exception represents an error tracking exception event. // Enqueue validates DistinctId and ExceptionList (or obtains DistinctId from request context), // fills Type, Uuid, Timestamp, and DisableGeoIP, then sends the message as a $exception event. +// +// posthog-capability: capture-exception type Exception struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/error_tracking_slog.go b/error_tracking_slog.go index ec0210f1..d3c48498 100644 --- a/error_tracking_slog.go +++ b/error_tracking_slog.go @@ -31,6 +31,8 @@ type SlogCaptureHandler struct { // return "my-user-id" // or pull from ctx // }), // )) +// +// posthog-capability: capture-exception func NewSlogCaptureHandler(next slog.Handler, client EnqueueClient, opts ...SlogOption) *SlogCaptureHandler { cfg := defaultCaptureConfig() for _, opt := range opts { diff --git a/group_identify.go b/group_identify.go index b014f71e..796d8eeb 100644 --- a/group_identify.go +++ b/group_identify.go @@ -8,6 +8,8 @@ import ( // GroupIdentify represents a group analytics call that sets properties on a group. // Enqueue validates Type and Key, fills Uuid, Timestamp, and DisableGeoIP, then // sends the message as a $groupidentify event. +// +// posthog-capability: group-identify type GroupIdentify struct { // Type is the group type, such as "company" or "organization". Type string diff --git a/identify.go b/identify.go index b92a68ad..6d130b3c 100644 --- a/identify.go +++ b/identify.go @@ -9,6 +9,8 @@ var _ Message = (*Identify)(nil) // Identify represents an identify call that sets person properties for a user. // Enqueue validates that DistinctId is set, fills Type, Uuid, Timestamp, and // DisableGeoIP, then sends the message as a $identify event. +// +// posthog-capability: identify type Identify struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/message.go b/message.go index 69722da5..891bdecc 100644 --- a/message.go +++ b/message.go @@ -37,6 +37,8 @@ type Callback interface { // reference values stored inside Properties or Groups (for example, pointers or // custom mutable structs held as interface{} values) are not deep-cloned and can // still share state with the caller. +// +// posthog-capability: before-send-hook type BeforeSendFunc func(Message) Message // Message represents a PostHog object that can be queued with Client.Enqueue. diff --git a/posthog.go b/posthog.go index 0e1bef14..4dc226c5 100644 --- a/posthog.go +++ b/posthog.go @@ -57,6 +57,8 @@ type EnqueueClient interface { // Bulk or backfill workloads that can enqueue faster than the client uploads // should check the returned error for ErrQueueFull and throttle or retry (or // raise Config.MaxQueueSize); otherwise events are dropped, not delayed. + // + // posthog-capability: capture Enqueue(Message) error } @@ -73,17 +75,23 @@ type Client interface { // Callback.Failure; a nil result does not guarantee successful ingestion. // Use FlushWithContext to bound the wait. Do not call a blocking Flush from // a delivery callback, which is itself part of the delivery cycle. + // + // posthog-capability: flush Flush() error // FlushWithContext is Flush with a caller-controlled deadline. Cancellation // stops only this caller's wait, not delivery or future use of the client. // Messages accepted before the call are covered; concurrent Enqueue calls may // be included in this cycle or a later one. Calls after Close return ErrClosed. + // + // posthog-capability: flush FlushWithContext(context.Context) error // Close gracefully shuts down the client and flushes pending messages. // If Config.ShutdownTimeout is positive, Close uses it as the shutdown deadline; // otherwise it waits indefinitely. Repeated calls return ErrClosed. + // + // posthog-capability: shutdown Close() error // IsFeatureEnabled evaluates one feature flag for a user and returns the same @@ -91,12 +99,16 @@ type Client interface { // for boolean flags. The FeatureFlagPayload parameter supplies the flag key, // distinct ID, optional groups/properties, and evaluation options. // Deprecated: Prefer EvaluateFlags for new code. + // + // posthog-capability: is-feature-enabled IsFeatureEnabled(FeatureFlagPayload) (interface{}, error) // GetFeatureFlag evaluates one feature flag for a user. It returns a variant // string for multivariate flags, true or false for boolean flags, false with // nil error when the flag is missing/disabled, and an error for evaluation failures. // Deprecated: Prefer EvaluateFlags for new code. + // + // posthog-capability: get-feature-flag GetFeatureFlag(FeatureFlagPayload) (interface{}, error) // GetFeatureFlagResult evaluates one feature flag and returns its value and payload together. @@ -104,12 +116,16 @@ type Client interface { // It returns ErrFlagNotFound when the flag cannot be found or evaluated and // ErrNoSecretKey when OnlyEvaluateLocally is true without SecretKey or a // FlagDefinitionCacheProvider. + // + // posthog-capability: get-feature-flag-result GetFeatureFlagResult(FeatureFlagPayload) (*FeatureFlagResult, error) // GetFeatureFlagPayload returns the payload for the matching flag value, or an // empty string when no payload is configured or the flag is missing/disabled. // Deprecated: Use GetFeatureFlagResult instead, which returns both the flag value // and payload while properly tracking feature flag usage. + // + // posthog-capability: get-feature-flag-payload GetFeatureFlagPayload(FeatureFlagPayload) (string, error) // GetRemoteConfigPayload returns the decrypted payload for a remote config flag key. @@ -119,6 +135,8 @@ type Client interface { // GetAllFlags evaluates all flags for a user. Returned values are booleans for // boolean flags and strings for multivariate variants. It returns ErrNoSecretKey // when OnlyEvaluateLocally is true without SecretKey or a FlagDefinitionCacheProvider. + // + // posthog-capability: get-feature-flags GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error) // EvaluateFlags returns a snapshot of feature-flag evaluations for the @@ -137,15 +155,21 @@ type Client interface { // branch on what was resolved. // If OnlyEvaluateLocally is true and neither SecretKey nor a // FlagDefinitionCacheProvider is configured, returns ErrNoSecretKey. + // + // posthog-capability: evaluate-flags EvaluateFlags(EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) // ReloadFeatureFlags forces a reload of feature flags. // If neither SecretKey nor a FlagDefinitionCacheProvider is configured, // returns ErrNoSecretKey. + // + // posthog-capability: reload-feature-flags ReloadFeatureFlags() error // CloseWithContext gracefully shuts down the client with the provided context. // The context can be used to control the shutdown deadline. + // + // posthog-capability: shutdown CloseWithContext(context.Context) error } @@ -250,6 +274,8 @@ type flagUser struct { // // The apiKey parameter is trimmed before use. If it is empty, New returns a // no-op client whose methods return default values and ErrSDKDisabled where applicable. +// +// posthog-capability: setup func New(apiKey string) Client { // Here we can ignore the error because the default config is always valid. c, _ := NewWithConfig(apiKey, Config{}) @@ -262,6 +288,8 @@ func New(apiKey string) Client { // It returns a ConfigError when config contains invalid values such as negative // intervals or out-of-range retry settings; in that case the returned Client is nil. // If apiKey is empty after trimming, NewWithConfig returns a no-op client and nil error. +// +// posthog-capability: setup func NewWithConfig(apiKey string, config Config) (cli Client, err error) { if err = config.Validate(); err != nil { return @@ -1160,6 +1188,8 @@ func (c *client) getAllFlagsWithContext(ctx context.Context, flagConfig FeatureF } // EvaluateFlagsPayload is the input to Client.EvaluateFlags. +// +// posthog-capability: evaluate-flags type EvaluateFlagsPayload struct { // DistinctId is the user distinct ID to evaluate flags for. It is required // unless EvaluateFlagsWithContext can read one from RequestContext. diff --git a/request_context.go b/request_context.go index 386a96c6..69eb7d54 100644 --- a/request_context.go +++ b/request_context.go @@ -401,6 +401,8 @@ func remoteIP(r *http.Request) string { // EnqueueWithContext queues a message and applies any PostHog request context attached to ctx. // Use this from HTTP handlers with r.Context() when NewRequestContextMiddleware is installed. +// +// posthog-capability: capture func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error { return enqueueWithContext(ctx, client, msg) } @@ -408,6 +410,8 @@ func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) // EvaluateFlagsWithContext evaluates feature flags and uses the request-scoped distinct ID attached // to ctx when payload.DistinctId is empty. It does not generate personless IDs: feature flag // evaluation requires a stable distinct ID and returns ErrNoDistinctID if neither payload nor ctx has one. +// +// posthog-capability: evaluate-flags func EvaluateFlagsWithContext(ctx context.Context, client Client, payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) { if client == nil { return noopFeatureFlagEvaluations, fmt.Errorf("posthog: nil client") From d7a4d1b5989b5d8a49e2f8cc0e28ba96987f2ca2 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 12:07:04 -0500 Subject: [PATCH 02/15] docs: generate the reference with go/doc instead of gomarkdoc go/doc reads each exported symbol and go/doc/comment renders its doc comment as Markdown, so the generator needs no third-party tool and no regex. It only groups symbols by their posthog-capability tag in sdk-specs order and writes front matter. The release step checks out sdk-specs for the headings. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 10 +- .gitignore | 1 + bin/docs_scripts/generate_markdown.py | 258 -------------------- internal/cmd/reference/main.go | 323 ++++++++++++++++++++++++++ 4 files changed, 333 insertions(+), 259 deletions(-) delete mode 100644 bin/docs_scripts/generate_markdown.py create mode 100644 internal/cmd/reference/main.go diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8bd4cf18..f0f42c70 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -129,8 +129,16 @@ jobs: (cd "$MODULE" && go mod edit "-require=github.com/posthog/posthog-go@v${NEW_VERSION}") done + # The reference headings come from the sdk-specs capabilities. + - name: Check out sdk-specs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: PostHog/sdk-specs + path: .sdk-specs + persist-credentials: false + - name: Regenerate SDK reference - run: python3 bin/docs_scripts/generate_markdown.py --latest + run: go run ./internal/cmd/reference --sdk-specs .sdk-specs - name: Check for version bump changes id: check-changes diff --git a/.gitignore b/.gitignore index 172e3396..380e6e6e 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,4 @@ node_modules/ # built compliance adapter binary sdk_compliance_adapter/sdk_compliance_adapter +.sdk-specs/ diff --git a/bin/docs_scripts/generate_markdown.py b/bin/docs_scripts/generate_markdown.py deleted file mode 100644 index ad79b7a4..00000000 --- a/bin/docs_scripts/generate_markdown.py +++ /dev/null @@ -1,258 +0,0 @@ -#!/usr/bin/env python3 -"""Generate the Markdown SDK reference with gomarkdoc (pinned, never a module dependency). - -gomarkdoc renders every symbol. This script only groups the symbols by the -`posthog-capability: ` line in their doc comment, orders them, and writes -front matter. Usage: generate_markdown.py [--source DIR] [--out DIR] [--latest] [--experimental] -""" -import argparse -import os -import re -import subprocess -import sys -import tempfile - -GOMARKDOC = "github.com/princjef/gomarkdoc/cmd/gomarkdoc@v1.1.0" -REFERENCE_ID = "posthog-go" -NAME = "PostHog Go SDK" -CLIENT_CLASSES = ["FeatureFlagEvaluations"] # public classes that get their own H2 - -# Capabilities this SDK implements, in sdk-specs README order (setup, capture, identify first). -CAPABILITIES = [ - ("setup", "Setup"), ("capture", "Capture"), ("identify", "Identify"), ("alias", "Alias"), - ("capture-exception", "Capture exception"), ("flush", "Flush"), - ("get-feature-flag", "Get feature flag"), ("get-feature-flag-payload", "Get feature flag payload"), - ("get-feature-flag-result", "Get feature flag result"), ("get-feature-flags", "Get feature flags"), - ("evaluate-flags", "Evaluate flags"), ("group-identify", "Group identify"), - ("is-feature-enabled", "Is feature enabled"), ("reload-feature-flags", "Reload feature flags"), - ("shutdown", "Shutdown"), ("before-send-hook", "Before send hook"), -] -TAG = re.compile(r"^posthog\\?-capability: (\S+)$") # gomarkdoc escapes the hyphen -HEAD = re.compile(r"^(##|###) (func|type) (?:\\\(\\?\*?(\w+)\\\) )?(?:\[(\w+)\]|(\w+))") - - -class Sym: - def __init__(self, kind, recv, name, level, body): - self.kind, self.recv, self.name, self.level, self.body = kind, recv, name, level, body - self.tag = None - self.children = [] - - @property - def title(self): - return f"{self.recv}.{self.name}" if self.recv else self.name - - -def run_gomarkdoc(source): - out = os.path.join(tempfile.mkdtemp(), "gomarkdoc.md") - subprocess.run(["go", "run", GOMARKDOC, "--output", out, "."], cwd=source, check=True) - return open(out).read() - - -def split_symbols(text): - """Split gomarkdoc output into extra blocks (constants, variables) and symbols.""" - chunks, cur = [], None - in_fence = False - for line in text.split("\n"): - if line.startswith("```"): - in_fence = not in_fence - if not in_fence and re.match(r"^#{1,3} ", line): - cur = [line] - chunks.append(cur) - elif cur is not None and not line.startswith("]*>\)", r"`\1`", text) # gomarkdoc in-page links have no target here - text = re.sub(r"\n{3,}", "\n\n", text) - # MDX 1 reads raw < and { in prose as JSX: escape them outside code - parts = re.split(r"(```.*?```|`[^`\n]*`)", text, flags=re.S) - return "".join(p if i % 2 else re.sub(r"<(?!https?://|/?(?:details|summary|p)>)", "<", p) - .replace("\\{", "{").replace("\\}", "}").replace("{", "{").replace("}", "}") - for i, p in enumerate(parts)) - - -def render(sym, level): - return f"{'#' * level} `{sym.title}`\n\n{clean(sym.body)}\n\n" + "".join(render(c, level + 1) for c in sym.children) - - -def slug(title): - return re.sub(r"[^\w\- ]", "", title.lower()).replace(" ", "-") - - -def build(text): - syms, blocks = split_symbols(text) - flat, parent = [], None - for s in syms: - if s.level == 2: - parent = s if s.kind == "type" else None - elif parent is not None: # method or constructor nested under its type - parent.children.append(s) - continue - flat.append(s) - for s in list(flat): - if s.kind == "type" and any("interface {" in l for l in s.body): - s.children = expand_interface(s) + s.children - everything = [] - for s in flat: - everything.append(s) - everything += s.children - for s in everything: - pull_tag(s) - # tagged nested symbols move out of their type - for s in flat: - s.children = [c for c in s.children if c.tag is None] - sections = {slug_: [] for slug_, _ in CAPABILITIES} - utils, classes, types = [], [], [] - for s in flat: - if s.tag: - sections[s.tag].append(s) - elif s.name in CLIENT_CLASSES: - classes.append(s) - elif s.kind == "func": - utils.append(s) - else: - types.append(s) - for s in everything: - if s.tag and s not in flat: - sections[s.tag].append(s) # tagged method/constructor - unknown = {s.tag for s in everything if s.tag} - set(sections) - if unknown: - sys.exit(f"unknown capability tag(s): {sorted(unknown)}") - return sections, utils, classes, types, blocks - - -def write_migration(source, out): - """Concatenate docs/migration-v.md guides, newest first, under one page.""" - import glob - files = sorted(glob.glob(os.path.join(source, "docs", "migration-v*.md")), reverse=True, - key=lambda f: int(re.search(r"v(\d+)", os.path.basename(f))[1])) - if not files: - return - guides, fence = [], False - for f in files: - for line in open(f).read().strip().split("\n"): - fence ^= line.startswith("```") - guides.append("#" + line if re.match(r"^#+ ", line) and not fence else line) - guides.append("") - fm = f'---\ntitle: "{NAME} migration guides"\nsidebar: Docs\nshowTitle: true\n---\n\n' - with open(os.path.join(out, f"{REFERENCE_ID}-migration.md"), "w") as f: - f.write(fm + clean(guides) + "\n") - print("wrote", os.path.join(out, f"{REFERENCE_ID}-migration.md")) - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--source", default=".") - ap.add_argument("--out", default="references") - ap.add_argument("--latest", action="store_true", help="also write the latest page") - ap.add_argument("--experimental", action="store_true", help="mark the major as unreleased") - a = ap.parse_args() - source = os.path.abspath(a.source) - mod = re.search(r"^module \S+?(?:/v(\d+))?$", open(os.path.join(source, "go.mod")).read(), re.M) - major = mod[1] or "1" - sections, utils, classes, types, blocks = build(run_gomarkdoc(source)) - - key = lambda s: (s.kind == "type", s.title) - body, toc = [], [] - - def h2(title, content): - toc.append(title) - body.append(f"## {title}\n\n{content.strip()}\n") - - gs = open(os.path.join(source, "docs", "getting-started.md")).read().strip() - h2("Getting started", re.sub(r"^(#+) ", r"#\1 ", gs, flags=re.M).split("\n", 2)[-1] if gs.startswith("# ") else gs) - for slug_, title in CAPABILITIES: - if sections[slug_]: - h2(title, "".join(render(s, 3) for s in sorted(sections[slug_], key=key))) - util = "".join(render(s, 3) for s in sorted(utils, key=key)) - for name in ("Constants", "Variables"): - if name in blocks: - util += f"### {name}\n\n{clean(blocks[name])}\n\n" - h2("SDK utils", util) - for c in classes: - h2(f"`{c.name}`", clean(c.body) + "\n\n" + "".join(render(x, 3) for x in sorted(c.children, key=key))) - h2("Types", "".join(render(s, 3) for s in sorted(types, key=key))) - - suffix = " (experimental)" if a.experimental else "" - def page(title): - fm = ["---", f'title: "{title}"', "sidebar: Docs", "showTitle: true", "contentMaxWidthClass: max-w-full", - "platformLogo: go", "tableOfContents:"] - for t in toc: - fm += [f' - value: "{t.replace("`", "")}"', f" url: {slug(t)}", " depth: 0"] - return "\n".join(fm + ["---", ""]) + "\n" + "\n".join(body) - - os.makedirs(a.out, exist_ok=True) - pages = {f"{REFERENCE_ID}-{major}.md": f"{NAME} {major}.x{suffix}"} - if a.latest: - pages[f"{REFERENCE_ID}-reference.md"] = NAME - for fname, title in pages.items(): - with open(os.path.join(a.out, fname), "w") as f: - f.write(page(title)) - print("wrote", os.path.join(a.out, fname)) - write_migration(source, a.out) - - -if __name__ == "__main__": - main() diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go new file mode 100644 index 00000000..7448c9a0 --- /dev/null +++ b/internal/cmd/reference/main.go @@ -0,0 +1,323 @@ +// Command reference writes the Markdown SDK reference to references/. +// +// go/doc reads each exported symbol and its doc comment, and go/doc/comment renders +// the comment as Markdown. This command only groups symbols by the +// "posthog-capability: " line in their doc comment, orders them like the +// PostHog/sdk-specs README, and writes front matter. +// +// go run ./internal/cmd/reference --sdk-specs ../sdk-specs [--major 2] +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/doc" + "go/doc/comment" + "go/parser" + "go/printer" + "go/token" + "log" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "unicode" +) + +const name, id, tagPrefix = "PostHog Go SDK", "posthog-go", "posthog-capability:" + +var ( + first = []string{"setup", "capture", "identify"} + classes = []string{"FeatureFlagEvaluations"} // client types that get their own H2 + fset = token.NewFileSet() + notes []*ast.CommentGroup + pkg *doc.Package +) + +type entry struct { + title, code, doc, tag string + children []entry +} + +func main() { + specs := flag.String("sdk-specs", "", "PostHog/sdk-specs checkout") + major := flag.Int("major", 0, "target major, defaults to the declared one") + flag.Parse() + var files []*ast.File + paths, _ := filepath.Glob("*.go") + for _, p := range paths { + if !strings.HasSuffix(p, "_test.go") { + f, err := parser.ParseFile(fset, p, nil, parser.ParseComments) + check(err) + files, notes = append(files, f), append(notes, f.Comments...) + } + } + var err error + pkg, err = doc.NewFromFiles(fset, files, "github.com/posthog/posthog-go") + check(err) + declared, _ := strconv.Atoi(strings.Split(strings.Trim(constant("Version"), `"`), ".")[0]) + if *major == 0 { + *major = declared + } + body := append([]string{"## Getting started", nest(read("docs/getting-started.md"))}, reference(capabilities(*specs))...) + title := fmt.Sprintf("%s %d.x", name, *major) + if *major > declared { + title += " (experimental)" + } + write(fmt.Sprintf("%s-%d.md", id, *major), frontMatter(title, body), body) + if *major <= declared { + write(id+"-reference.md", frontMatter(name, body), body) + } + if guides, _ := filepath.Glob("docs/migration-*.md"); len(guides) > 0 { + slices.Reverse(guides) + for i, g := range guides { + guides[i] = strings.TrimSpace(read(g)) + } + write(id+"-migration.md", "---\ntitle: \""+name+" migration guides\"\nsidebar: Docs\nshowTitle: true\n---", guides) + } +} + +// capabilities returns each sdk-specs capability's slug and sentence-case title, in README order. +func capabilities(checkout string) (caps [][2]string) { + acronyms := map[string]string{"id": "ID", "ai": "AI", "http": "HTTP", "mcp": "MCP"} + for _, line := range strings.Split(read(filepath.Join(checkout, "README.md")), "\n") { + cells := strings.Split(line, "|") + if _, path, ok := strings.Cut(strings.Join(cells[min(2, len(cells)-1):], ""), "openspec/specs/"); ok && len(cells) > 2 { + words := strings.Fields(strings.ToLower(cells[1])) + for i, w := range words { + if a, ok := acronyms[w]; ok { + words[i] = a + } + } + title := strings.Join(words, " ") + caps = append(caps, [2]string{strings.Split(path, "/")[0], strings.ToUpper(title[:1]) + title[1:]}) + } + } + rank := func(slug string) int { return (slices.Index(first, slug) + len(first) + 1) % (len(first) + 1) } + sort.SliceStable(caps, func(i, j int) bool { return rank(caps[i][0]) < rank(caps[j][0]) }) + return caps +} + +func reference(caps [][2]string) []string { + var utils, types, own []entry + embedded := map[string]bool{} + for _, t := range pkg.Types { + switch { + case t.Name == "Client": + utils = append(utils, methods(t, embedded)...) + utils = append(utils, funcs(t.Funcs, "posthog.")...) + case slices.Contains(classes, t.Name): + own = append(own, typeEntry(t)) + default: + types = append(types, typeEntry(t)) + } + } + utils = append(utils, funcs(pkg.Funcs, "posthog.")...) + types = slices.DeleteFunc(types, func(e entry) bool { return embedded[e.title] }) + // A tagged symbol moves to its capability, from wherever go/doc listed it. + tagged := map[string][]entry{} + untagged := func(list []entry) []entry { + return slices.DeleteFunc(list, func(e entry) bool { + if e.tag != "" { + tagged[e.tag] = append(tagged[e.tag], e) + } + return e.tag != "" + }) + } + for _, list := range []*[]entry{&utils, &types, &own} { + for i := range *list { + (*list)[i].children = untagged((*list)[i].children) + } + *list = untagged(*list) + } + var out []string + for _, c := range caps { + if list := tagged[c[0]]; list != nil { + out = append(append(out, "## "+c[1]), render(list, 3)...) + delete(tagged, c[0]) + } + } + for tag := range tagged { + log.Fatalf("unknown capability tag %q", tag) + } + out = append(append(out, "## SDK utils"), render(utils, 3)...) + for _, v := range append(pkg.Consts, pkg.Vars...) { + out = append(out, block(v.Decl), markdown(v.Doc)) + } + for _, c := range own { + out = append(append(out, "## `"+c.title+"`", c.code, c.doc), render(c.children, 3)...) + } + return append(append(out, "## Types"), render(types, 3)...) +} + +// methods lists an interface's methods, including those of the interfaces it embeds. +func methods(t *doc.Type, embedded map[string]bool) (out []entry) { + for _, field := range t.Decl.Specs[0].(*ast.TypeSpec).Type.(*ast.InterfaceType).Methods.List { + if ident, ok := field.Type.(*ast.Ident); ok && len(field.Names) == 0 { + embedded[ident.Name] = true + for _, inner := range pkg.Types { + if inner.Name == ident.Name { + out = append(out, methods(inner, embedded)...) + } + } + } else if len(field.Names) > 0 { + text, tag := untag(field.Doc.Text()) + sig := field.Names[0].Name + strings.TrimPrefix(source(field.Type), "func") + out = append(out, entry{t.Name + "." + field.Names[0].Name, code(sig), markdown(text), tag, nil}) + } + } + return out +} + +func typeEntry(t *doc.Type) entry { + text, tag := untag(t.Doc) + children := append(funcs(t.Funcs, "posthog."), funcs(t.Methods, t.Name+".")...) + return entry{t.Name, block(t.Decl), markdown(text), tag, children} +} + +func funcs(list []*doc.Func, prefix string) (out []entry) { + for _, f := range list { + text, tag := untag(f.Doc) + decl := *f.Decl + decl.Doc, decl.Body = nil, nil + out = append(out, entry{prefix + f.Name, code(source(&decl)), markdown(text), tag, nil}) + } + return out +} + +func render(list []entry, level int) (out []string) { + sort.SliceStable(list, func(i, j int) bool { return list[i].title < list[j].title }) + for _, e := range list { + out = append(append(out, strings.Repeat("#", level)+" `"+e.title+"`", e.code, e.doc), render(e.children, level+1)...) + } + return out +} + +// untag drops the capability line from a doc comment and returns its slug. +func untag(text string) (string, string) { + var keep []string + tag := "" + for _, line := range strings.Split(text, "\n") { + if slug, ok := strings.CutPrefix(strings.TrimSpace(line), tagPrefix); ok { + tag = strings.TrimSpace(slug) + } else { + keep = append(keep, line) + } + } + return strings.TrimSpace(strings.Join(keep, "\n")), tag +} + +// markdown renders a doc comment. The site reads Markdown as MDX, so prose escapes < and braces. +func markdown(text string) string { + d := pkg.Parser().Parse(text) + escape(d.Content) + p := pkg.Printer() + p.HeadingLevel = 5 + p.DocLinkURL = func(l *comment.DocLink) string { return "#" + anchor(l.Recv+l.Name) } + return strings.TrimSpace(string(p.Markdown(d))) +} + +var mdx = strings.NewReplacer("<", "<", "{", "{", "}", "}") + +func escape(blocks []comment.Block) { + for _, b := range blocks { + switch b := b.(type) { + case *comment.Paragraph: + for i, t := range b.Text { + if s, ok := t.(comment.Plain); ok { + b.Text[i] = comment.Plain(mdx.Replace(string(s))) + } + } + case *comment.List: + for _, item := range b.Items { + escape(item.Content) + } + } + } +} + +func constant(want string) string { + for _, v := range pkg.Consts { + for _, s := range v.Decl.Specs { + if s := s.(*ast.ValueSpec); s.Names[0].Name == want { + return s.Values[0].(*ast.BasicLit).Value + } + } + } + log.Fatalf("no %s constant", want) + return "" +} + +func block(decl *ast.GenDecl) string { + d := *decl + d.Doc = nil + return code(source(&printer.CommentedNode{Node: &d, Comments: notes})) +} + +func source(node any) string { + var buf bytes.Buffer + check(printer.Fprint(&buf, fset, node)) + return buf.String() +} + +func code(s string) string { return "```go\n" + s + "\n```" } + +func frontMatter(title string, body []string) string { + head := []string{"---", "title: " + strconv.Quote(title), "sidebar: Docs", "showTitle: true", + "contentMaxWidthClass: max-w-full", "platformLogo: go", "tableOfContents:"} + for _, s := range body { + if h, ok := strings.CutPrefix(s, "## "); ok { + head = append(head, " - value: "+strconv.Quote(strings.ReplaceAll(h, "`", "")), " url: "+anchor(h), " depth: 0") + } + } + return strings.Join(append(head, "---"), "\n") +} + +// anchor is the github-slugger slug the docs site gives a heading. +func anchor(heading string) string { + return strings.Map(func(r rune) rune { + if r == ' ' { + return '-' + } + if r == '-' || r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) { + return r + } + return -1 + }, strings.ToLower(heading)) +} + +// nest moves each heading of a hand-written page down one level and drops its H1. +func nest(page string) string { + var out []string + fenced := false + for _, line := range strings.Split(strings.TrimSpace(page), "\n") { + fenced = fenced != strings.HasPrefix(strings.TrimSpace(line), "```") + if fenced || !strings.HasPrefix(line, "#") { + out = append(out, line) + } else if !strings.HasPrefix(line, "# ") { + out = append(out, "#"+line) + } + } + return strings.Join(out, "\n") +} + +func read(path string) string { + b, err := os.ReadFile(path) + check(err) + return string(b) +} + +func write(file, front string, body []string) { + check(os.WriteFile(filepath.Join("references", file), []byte(strings.Join(append([]string{front}, body...), "\n\n")+"\n"), 0o644)) + fmt.Println("wrote references/" + file) +} + +func check(err error) { + if err != nil { + log.Fatal(err) + } +} From 4adf9507eb6e7b87875a9f73ac056ad176645c66 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 13:09:15 -0500 Subject: [PATCH 03/15] chore: update the public API snapshot for the capability tags The snapshot includes doc comments, and the tags add a line to some of them. No signatures change. Co-Authored-By: Claude Opus 5.5 --- api/public-api.txt | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/api/public-api.txt b/api/public-api.txt index 7e1c41f7..c81c99c7 100644 --- a/api/public-api.txt +++ b/api/public-api.txt @@ -96,6 +96,7 @@ FUNCTIONS func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error + func NewRequestContextMiddleware(next http.Handler, opts ...RequestContextOption) http.Handler @@ -132,6 +133,7 @@ type Alias struct { IsServer bool } + func (msg Alias) APIfy() APIMessage func (msg Alias) Validate() error @@ -177,6 +179,7 @@ func (b *Backoff) Sleep(attempt int) type BeforeSendFunc func(Message) Message + type Callback interface { Success(APIMessage) @@ -201,6 +204,7 @@ type Capture struct { } + func (msg Capture) APIfy() APIMessage func (msg Capture) Validate() error @@ -277,9 +281,11 @@ type Client interface { func New(apiKey string) Client + func NewWithConfig(apiKey string, config Config) (cli Client, err error) + type CommonResponseFields struct { QuotaLimited []string `json:"quota_limited"` RequestId string `json:"requestId"` @@ -360,6 +366,7 @@ type Config struct { } + func (c Config) GetDisableGeoIP() bool func (c Config) GetIsServer() bool @@ -442,6 +449,7 @@ type EvaluateFlagsPayload struct { FlagKeys []string } + type Exception struct { Type string Uuid string @@ -458,6 +466,7 @@ type Exception struct { ExceptionFingerprint *string } + func NewDefaultException( timestamp time.Time, distinctID, title, description string, @@ -538,6 +547,7 @@ type FeatureFlagEvaluations struct { func EvaluateFlagsWithContext(ctx context.Context, client Client, payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) + func (e *FeatureFlagEvaluations) GetFlag(key string) interface{} func (e *FeatureFlagEvaluations) GetFlagPayload(key string) string @@ -731,6 +741,7 @@ type GroupIdentify struct { IsServer bool } + func (msg GroupIdentify) APIfy() APIMessage func (msg GroupIdentify) Validate() error @@ -768,6 +779,7 @@ type Identify struct { IsServer bool } + func (msg Identify) APIfy() APIMessage func (msg Identify) Validate() error @@ -899,6 +911,7 @@ func NewSlogCaptureHandler(next slog.Handler, client EnqueueClient, opts ...Slog + func (h *SlogCaptureHandler) Enabled(ctx context.Context, level slog.Level) bool func (h *SlogCaptureHandler) Handle(ctx context.Context, r slog.Record) error From bc87bb933c7fa86151e569404f1a7a772ba1772f Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:25:46 -0500 Subject: [PATCH 04/15] ci: stage generated reference pages before the release commit ghcommit-action passes an untracked folder to ghcommit as one path, which fails on the first release that writes references/. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f0f42c70..6b261d5d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -138,7 +138,10 @@ jobs: persist-credentials: false - name: Regenerate SDK reference - run: go run ./internal/cmd/reference --sdk-specs .sdk-specs + # Stage the pages, so a new page shows in git status as a file, not as an untracked folder. + run: | + go run ./internal/cmd/reference --sdk-specs .sdk-specs + git add references - name: Check for version bump changes id: check-changes From e3a1866c581e4478c9359bd2a454966be190de44 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:34:15 -0500 Subject: [PATCH 05/15] docs: read capability tags from docs/capabilities.json The posthog-capability lines showed up in IDE hover help for every SDK user. The generator now reads a label-to-slug map next to it, and fails on stale labels, unknown slugs, and unmapped SDK utils members. Co-Authored-By: Claude Opus 5.5 --- alias.go | 2 - api/public-api.txt | 13 ----- capture.go | 2 - config.go | 2 - docs/capabilities.json | 41 +++++++++++++++ error_tracking.go | 2 - error_tracking_slog.go | 2 - group_identify.go | 2 - identify.go | 2 - internal/cmd/reference/main.go | 92 +++++++++++++++++++++------------- message.go | 2 - posthog.go | 30 ----------- request_context.go | 4 -- 13 files changed, 98 insertions(+), 98 deletions(-) create mode 100644 docs/capabilities.json diff --git a/alias.go b/alias.go index aa3fdb59..ee1ea162 100644 --- a/alias.go +++ b/alias.go @@ -9,8 +9,6 @@ var _ Message = (*Alias)(nil) // Alias represents an alias call that links another distinct ID to an existing user. // Enqueue validates that DistinctId and Alias are both set, fills Type, Uuid, // Timestamp, and DisableGeoIP, then sends the message as a $create_alias event. -// -// posthog-capability: alias type Alias struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/api/public-api.txt b/api/public-api.txt index c81c99c7..7e1c41f7 100644 --- a/api/public-api.txt +++ b/api/public-api.txt @@ -96,7 +96,6 @@ FUNCTIONS func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error - func NewRequestContextMiddleware(next http.Handler, opts ...RequestContextOption) http.Handler @@ -133,7 +132,6 @@ type Alias struct { IsServer bool } - func (msg Alias) APIfy() APIMessage func (msg Alias) Validate() error @@ -179,7 +177,6 @@ func (b *Backoff) Sleep(attempt int) type BeforeSendFunc func(Message) Message - type Callback interface { Success(APIMessage) @@ -204,7 +201,6 @@ type Capture struct { } - func (msg Capture) APIfy() APIMessage func (msg Capture) Validate() error @@ -281,11 +277,9 @@ type Client interface { func New(apiKey string) Client - func NewWithConfig(apiKey string, config Config) (cli Client, err error) - type CommonResponseFields struct { QuotaLimited []string `json:"quota_limited"` RequestId string `json:"requestId"` @@ -366,7 +360,6 @@ type Config struct { } - func (c Config) GetDisableGeoIP() bool func (c Config) GetIsServer() bool @@ -449,7 +442,6 @@ type EvaluateFlagsPayload struct { FlagKeys []string } - type Exception struct { Type string Uuid string @@ -466,7 +458,6 @@ type Exception struct { ExceptionFingerprint *string } - func NewDefaultException( timestamp time.Time, distinctID, title, description string, @@ -547,7 +538,6 @@ type FeatureFlagEvaluations struct { func EvaluateFlagsWithContext(ctx context.Context, client Client, payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) - func (e *FeatureFlagEvaluations) GetFlag(key string) interface{} func (e *FeatureFlagEvaluations) GetFlagPayload(key string) string @@ -741,7 +731,6 @@ type GroupIdentify struct { IsServer bool } - func (msg GroupIdentify) APIfy() APIMessage func (msg GroupIdentify) Validate() error @@ -779,7 +768,6 @@ type Identify struct { IsServer bool } - func (msg Identify) APIfy() APIMessage func (msg Identify) Validate() error @@ -911,7 +899,6 @@ func NewSlogCaptureHandler(next slog.Handler, client EnqueueClient, opts ...Slog - func (h *SlogCaptureHandler) Enabled(ctx context.Context, level slog.Level) bool func (h *SlogCaptureHandler) Handle(ctx context.Context, r slog.Record) error diff --git a/capture.go b/capture.go index 6a408690..3650b0ca 100644 --- a/capture.go +++ b/capture.go @@ -82,8 +82,6 @@ var _ Message = (*Capture)(nil) // Enqueue validates Event and DistinctId (or obtains DistinctId from request context), // fills Type, Uuid, and Timestamp, merges Config.DefaultEventProperties, and queues // the event for a future batch upload. -// -// posthog-capability: capture type Capture struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: PostHog ignores the top-level type field on capture events. Use Event for diff --git a/config.go b/config.go index 5a505287..7e534891 100644 --- a/config.go +++ b/config.go @@ -64,8 +64,6 @@ const ( // // Each exported field's zero value is either meaningful or replaced by the // default documented on that field. -// -// posthog-capability: setup type Config struct { // Endpoint is the PostHog API host used for event ingestion and feature flag requests. diff --git a/docs/capabilities.json b/docs/capabilities.json new file mode 100644 index 00000000..60f34536 --- /dev/null +++ b/docs/capabilities.json @@ -0,0 +1,41 @@ +{ + "Alias": "alias", + "BeforeSendFunc": "before-send-hook", + "Capture": "capture", + "Client.Close": "shutdown", + "Client.CloseWithContext": "shutdown", + "Client.EvaluateFlags": "evaluate-flags", + "Client.Flush": "flush", + "Client.FlushWithContext": "flush", + "Client.GetAllFlags": "get-feature-flags", + "Client.GetFeatureFlag": "get-feature-flag", + "Client.GetFeatureFlagPayload": "get-feature-flag-payload", + "Client.GetFeatureFlagResult": "get-feature-flag-result", + "Client.IsFeatureEnabled": "is-feature-enabled", + "Client.ReloadFeatureFlags": "reload-feature-flags", + "Config": "setup", + "EnqueueClient.Enqueue": "capture", + "EvaluateFlagsPayload": "evaluate-flags", + "Exception": "capture-exception", + "GroupIdentify": "group-identify", + "Identify": "identify", + "next": { + "utils": [ + "Client.EnqueueAI", + "posthog.EnqueueAIWithContext" + ] + }, + "posthog.EnqueueWithContext": "capture", + "posthog.EvaluateFlagsWithContext": "evaluate-flags", + "posthog.New": "setup", + "posthog.NewSlogCaptureHandler": "capture-exception", + "posthog.NewWithConfig": "setup", + "utils": [ + "Client.GetRemoteConfigPayload", + "posthog.NewRequestContextMiddleware", + "posthog.Ptr", + "posthog.SimpleInAppDecider", + "posthog.WithFreshRequestContext", + "posthog.WithRequestContext" + ] +} diff --git a/error_tracking.go b/error_tracking.go index 4f6ccc55..3ad4566a 100644 --- a/error_tracking.go +++ b/error_tracking.go @@ -10,8 +10,6 @@ var _ Message = (*Exception)(nil) // Exception represents an error tracking exception event. // Enqueue validates DistinctId and ExceptionList (or obtains DistinctId from request context), // fills Type, Uuid, Timestamp, and DisableGeoIP, then sends the message as a $exception event. -// -// posthog-capability: capture-exception type Exception struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/error_tracking_slog.go b/error_tracking_slog.go index d3c48498..ec0210f1 100644 --- a/error_tracking_slog.go +++ b/error_tracking_slog.go @@ -31,8 +31,6 @@ type SlogCaptureHandler struct { // return "my-user-id" // or pull from ctx // }), // )) -// -// posthog-capability: capture-exception func NewSlogCaptureHandler(next slog.Handler, client EnqueueClient, opts ...SlogOption) *SlogCaptureHandler { cfg := defaultCaptureConfig() for _, opt := range opts { diff --git a/group_identify.go b/group_identify.go index 796d8eeb..b014f71e 100644 --- a/group_identify.go +++ b/group_identify.go @@ -8,8 +8,6 @@ import ( // GroupIdentify represents a group analytics call that sets properties on a group. // Enqueue validates Type and Key, fills Uuid, Timestamp, and DisableGeoIP, then // sends the message as a $groupidentify event. -// -// posthog-capability: group-identify type GroupIdentify struct { // Type is the group type, such as "company" or "organization". Type string diff --git a/identify.go b/identify.go index 6d130b3c..b92a68ad 100644 --- a/identify.go +++ b/identify.go @@ -9,8 +9,6 @@ var _ Message = (*Identify)(nil) // Identify represents an identify call that sets person properties for a user. // Enqueue validates that DistinctId is set, fills Type, Uuid, Timestamp, and // DisableGeoIP, then sends the message as a $identify event. -// -// posthog-capability: identify type Identify struct { // Type is reserved for SDK serialization and is overwritten by Enqueue. // Deprecated: this field is ignored by PostHog ingestion and is kept for backwards compatibility. diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go index 7448c9a0..6d71a0af 100644 --- a/internal/cmd/reference/main.go +++ b/internal/cmd/reference/main.go @@ -1,15 +1,16 @@ // Command reference writes the Markdown SDK reference to references/. // // go/doc reads each exported symbol and its doc comment, and go/doc/comment renders -// the comment as Markdown. This command only groups symbols by the -// "posthog-capability: " line in their doc comment, orders them like the -// PostHog/sdk-specs README, and writes front matter. +// the comment as Markdown. This command only groups symbols by capability, using the +// labels in docs/capabilities.json, orders them like the PostHog/sdk-specs README, +// and writes front matter. // // go run ./internal/cmd/reference --sdk-specs ../sdk-specs [--major 2] package main import ( "bytes" + "encoding/json" "flag" "fmt" "go/ast" @@ -28,7 +29,7 @@ import ( "unicode" ) -const name, id, tagPrefix = "PostHog Go SDK", "posthog-go", "posthog-capability:" +const name, id = "PostHog Go SDK", "posthog-go" var ( first = []string{"setup", "capture", "identify"} @@ -36,11 +37,17 @@ var ( fset = token.NewFileSet() notes []*ast.CommentGroup pkg *doc.Package + mapped = map[string]label{} // entry label to capability slug, "" for SDK utils ) type entry struct { - title, code, doc, tag string - children []entry + title, code, doc string + children []entry +} + +type label struct { + slug string + next bool // from "next": the label may exist only on the next major } func main() { @@ -56,6 +63,9 @@ func main() { files, notes = append(files, f), append(notes, f.Comments...) } } + var labels map[string]any + check(json.Unmarshal([]byte(read("docs/capabilities.json")), &labels)) + load(labels, false) var err error pkg, err = doc.NewFromFiles(fset, files, "github.com/posthog/posthog-go") check(err) @@ -63,7 +73,7 @@ func main() { if *major == 0 { *major = declared } - body := append([]string{"## Getting started", nest(read("docs/getting-started.md"))}, reference(capabilities(*specs))...) + body := append([]string{"## Getting started", nest(read("docs/getting-started.md"))}, reference(capabilities(*specs), *major <= declared)...) title := fmt.Sprintf("%s %d.x", name, *major) if *major > declared { title += " (experimental)" @@ -81,6 +91,22 @@ func main() { } } +// load reads docs/capabilities.json: slugs by label, a "utils" list, and a "next" object of the same shape. +func load(labels map[string]any, next bool) { + for k, v := range labels { + switch v := v.(type) { + case map[string]any: + load(v, true) + case []any: + for _, l := range v { + mapped[l.(string)] = label{"", next} + } + default: + mapped[k] = label{v.(string), next} + } + } +} + // capabilities returns each sdk-specs capability's slug and sentence-case title, in README order. func capabilities(checkout string) (caps [][2]string) { acronyms := map[string]string{"id": "ID", "ai": "AI", "http": "HTTP", "mcp": "MCP"} @@ -102,7 +128,8 @@ func capabilities(checkout string) (caps [][2]string) { return caps } -func reference(caps [][2]string) []string { +// reference lists every symbol. On a next-major run, current is false and labels that no longer exist are skipped. +func reference(caps [][2]string, current bool) []string { var utils, types, own []entry embedded := map[string]bool{} for _, t := range pkg.Types { @@ -118,14 +145,16 @@ func reference(caps [][2]string) []string { } utils = append(utils, funcs(pkg.Funcs, "posthog.")...) types = slices.DeleteFunc(types, func(e entry) bool { return embedded[e.title] }) - // A tagged symbol moves to its capability, from wherever go/doc listed it. - tagged := map[string][]entry{} + // A mapped symbol moves to its capability, from wherever go/doc listed it. + tagged, found := map[string][]entry{}, map[string]bool{} untagged := func(list []entry) []entry { return slices.DeleteFunc(list, func(e entry) bool { - if e.tag != "" { - tagged[e.tag] = append(tagged[e.tag], e) + found[e.title] = true + slug := mapped[e.title].slug + if slug != "" { + tagged[slug] = append(tagged[slug], e) } - return e.tag != "" + return slug != "" }) } for _, list := range []*[]entry{&utils, &types, &own} { @@ -134,6 +163,16 @@ func reference(caps [][2]string) []string { } *list = untagged(*list) } + for l, m := range mapped { + if !found[l] && !m.next && current { + log.Fatalf("docs/capabilities.json: %s names no symbol", l) + } + } + for _, e := range utils { + if _, ok := mapped[e.title]; !ok { + log.Fatalf("docs/capabilities.json: map %s to a capability or list it under utils", e.title) + } + } var out []string for _, c := range caps { if list := tagged[c[0]]; list != nil { @@ -141,8 +180,8 @@ func reference(caps [][2]string) []string { delete(tagged, c[0]) } } - for tag := range tagged { - log.Fatalf("unknown capability tag %q", tag) + for slug, list := range tagged { + log.Fatalf("docs/capabilities.json: %s maps to %q, which is not an sdk-specs capability", list[0].title, slug) } out = append(append(out, "## SDK utils"), render(utils, 3)...) for _, v := range append(pkg.Consts, pkg.Vars...) { @@ -165,26 +204,23 @@ func methods(t *doc.Type, embedded map[string]bool) (out []entry) { } } } else if len(field.Names) > 0 { - text, tag := untag(field.Doc.Text()) sig := field.Names[0].Name + strings.TrimPrefix(source(field.Type), "func") - out = append(out, entry{t.Name + "." + field.Names[0].Name, code(sig), markdown(text), tag, nil}) + out = append(out, entry{t.Name + "." + field.Names[0].Name, code(sig), markdown(field.Doc.Text()), nil}) } } return out } func typeEntry(t *doc.Type) entry { - text, tag := untag(t.Doc) children := append(funcs(t.Funcs, "posthog."), funcs(t.Methods, t.Name+".")...) - return entry{t.Name, block(t.Decl), markdown(text), tag, children} + return entry{t.Name, block(t.Decl), markdown(t.Doc), children} } func funcs(list []*doc.Func, prefix string) (out []entry) { for _, f := range list { - text, tag := untag(f.Doc) decl := *f.Decl decl.Doc, decl.Body = nil, nil - out = append(out, entry{prefix + f.Name, code(source(&decl)), markdown(text), tag, nil}) + out = append(out, entry{prefix + f.Name, code(source(&decl)), markdown(f.Doc), nil}) } return out } @@ -197,20 +233,6 @@ func render(list []entry, level int) (out []string) { return out } -// untag drops the capability line from a doc comment and returns its slug. -func untag(text string) (string, string) { - var keep []string - tag := "" - for _, line := range strings.Split(text, "\n") { - if slug, ok := strings.CutPrefix(strings.TrimSpace(line), tagPrefix); ok { - tag = strings.TrimSpace(slug) - } else { - keep = append(keep, line) - } - } - return strings.TrimSpace(strings.Join(keep, "\n")), tag -} - // markdown renders a doc comment. The site reads Markdown as MDX, so prose escapes < and braces. func markdown(text string) string { d := pkg.Parser().Parse(text) diff --git a/message.go b/message.go index 891bdecc..69722da5 100644 --- a/message.go +++ b/message.go @@ -37,8 +37,6 @@ type Callback interface { // reference values stored inside Properties or Groups (for example, pointers or // custom mutable structs held as interface{} values) are not deep-cloned and can // still share state with the caller. -// -// posthog-capability: before-send-hook type BeforeSendFunc func(Message) Message // Message represents a PostHog object that can be queued with Client.Enqueue. diff --git a/posthog.go b/posthog.go index 4dc226c5..0e1bef14 100644 --- a/posthog.go +++ b/posthog.go @@ -57,8 +57,6 @@ type EnqueueClient interface { // Bulk or backfill workloads that can enqueue faster than the client uploads // should check the returned error for ErrQueueFull and throttle or retry (or // raise Config.MaxQueueSize); otherwise events are dropped, not delayed. - // - // posthog-capability: capture Enqueue(Message) error } @@ -75,23 +73,17 @@ type Client interface { // Callback.Failure; a nil result does not guarantee successful ingestion. // Use FlushWithContext to bound the wait. Do not call a blocking Flush from // a delivery callback, which is itself part of the delivery cycle. - // - // posthog-capability: flush Flush() error // FlushWithContext is Flush with a caller-controlled deadline. Cancellation // stops only this caller's wait, not delivery or future use of the client. // Messages accepted before the call are covered; concurrent Enqueue calls may // be included in this cycle or a later one. Calls after Close return ErrClosed. - // - // posthog-capability: flush FlushWithContext(context.Context) error // Close gracefully shuts down the client and flushes pending messages. // If Config.ShutdownTimeout is positive, Close uses it as the shutdown deadline; // otherwise it waits indefinitely. Repeated calls return ErrClosed. - // - // posthog-capability: shutdown Close() error // IsFeatureEnabled evaluates one feature flag for a user and returns the same @@ -99,16 +91,12 @@ type Client interface { // for boolean flags. The FeatureFlagPayload parameter supplies the flag key, // distinct ID, optional groups/properties, and evaluation options. // Deprecated: Prefer EvaluateFlags for new code. - // - // posthog-capability: is-feature-enabled IsFeatureEnabled(FeatureFlagPayload) (interface{}, error) // GetFeatureFlag evaluates one feature flag for a user. It returns a variant // string for multivariate flags, true or false for boolean flags, false with // nil error when the flag is missing/disabled, and an error for evaluation failures. // Deprecated: Prefer EvaluateFlags for new code. - // - // posthog-capability: get-feature-flag GetFeatureFlag(FeatureFlagPayload) (interface{}, error) // GetFeatureFlagResult evaluates one feature flag and returns its value and payload together. @@ -116,16 +104,12 @@ type Client interface { // It returns ErrFlagNotFound when the flag cannot be found or evaluated and // ErrNoSecretKey when OnlyEvaluateLocally is true without SecretKey or a // FlagDefinitionCacheProvider. - // - // posthog-capability: get-feature-flag-result GetFeatureFlagResult(FeatureFlagPayload) (*FeatureFlagResult, error) // GetFeatureFlagPayload returns the payload for the matching flag value, or an // empty string when no payload is configured or the flag is missing/disabled. // Deprecated: Use GetFeatureFlagResult instead, which returns both the flag value // and payload while properly tracking feature flag usage. - // - // posthog-capability: get-feature-flag-payload GetFeatureFlagPayload(FeatureFlagPayload) (string, error) // GetRemoteConfigPayload returns the decrypted payload for a remote config flag key. @@ -135,8 +119,6 @@ type Client interface { // GetAllFlags evaluates all flags for a user. Returned values are booleans for // boolean flags and strings for multivariate variants. It returns ErrNoSecretKey // when OnlyEvaluateLocally is true without SecretKey or a FlagDefinitionCacheProvider. - // - // posthog-capability: get-feature-flags GetAllFlags(FeatureFlagPayloadNoKey) (map[string]interface{}, error) // EvaluateFlags returns a snapshot of feature-flag evaluations for the @@ -155,21 +137,15 @@ type Client interface { // branch on what was resolved. // If OnlyEvaluateLocally is true and neither SecretKey nor a // FlagDefinitionCacheProvider is configured, returns ErrNoSecretKey. - // - // posthog-capability: evaluate-flags EvaluateFlags(EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) // ReloadFeatureFlags forces a reload of feature flags. // If neither SecretKey nor a FlagDefinitionCacheProvider is configured, // returns ErrNoSecretKey. - // - // posthog-capability: reload-feature-flags ReloadFeatureFlags() error // CloseWithContext gracefully shuts down the client with the provided context. // The context can be used to control the shutdown deadline. - // - // posthog-capability: shutdown CloseWithContext(context.Context) error } @@ -274,8 +250,6 @@ type flagUser struct { // // The apiKey parameter is trimmed before use. If it is empty, New returns a // no-op client whose methods return default values and ErrSDKDisabled where applicable. -// -// posthog-capability: setup func New(apiKey string) Client { // Here we can ignore the error because the default config is always valid. c, _ := NewWithConfig(apiKey, Config{}) @@ -288,8 +262,6 @@ func New(apiKey string) Client { // It returns a ConfigError when config contains invalid values such as negative // intervals or out-of-range retry settings; in that case the returned Client is nil. // If apiKey is empty after trimming, NewWithConfig returns a no-op client and nil error. -// -// posthog-capability: setup func NewWithConfig(apiKey string, config Config) (cli Client, err error) { if err = config.Validate(); err != nil { return @@ -1188,8 +1160,6 @@ func (c *client) getAllFlagsWithContext(ctx context.Context, flagConfig FeatureF } // EvaluateFlagsPayload is the input to Client.EvaluateFlags. -// -// posthog-capability: evaluate-flags type EvaluateFlagsPayload struct { // DistinctId is the user distinct ID to evaluate flags for. It is required // unless EvaluateFlagsWithContext can read one from RequestContext. diff --git a/request_context.go b/request_context.go index 69eb7d54..386a96c6 100644 --- a/request_context.go +++ b/request_context.go @@ -401,8 +401,6 @@ func remoteIP(r *http.Request) string { // EnqueueWithContext queues a message and applies any PostHog request context attached to ctx. // Use this from HTTP handlers with r.Context() when NewRequestContextMiddleware is installed. -// -// posthog-capability: capture func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) error { return enqueueWithContext(ctx, client, msg) } @@ -410,8 +408,6 @@ func EnqueueWithContext(ctx context.Context, client EnqueueClient, msg Message) // EvaluateFlagsWithContext evaluates feature flags and uses the request-scoped distinct ID attached // to ctx when payload.DistinctId is empty. It does not generate personless IDs: feature flag // evaluation requires a stable distinct ID and returns ErrNoDistinctID if neither payload nor ctx has one. -// -// posthog-capability: evaluate-flags func EvaluateFlagsWithContext(ctx context.Context, client Client, payload EvaluateFlagsPayload) (*FeatureFlagEvaluations, error) { if client == nil { return noopFeatureFlagEvaluations, fmt.Errorf("posthog: nil client") From 3931c712db3590927777fe9b4035107810aa8419 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 14:37:55 -0500 Subject: [PATCH 06/15] docs: map EnqueueAI to capture-ai on 2.x Co-Authored-By: Claude Opus 5.5 --- docs/capabilities.json | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/capabilities.json b/docs/capabilities.json index 60f34536..6b81befe 100644 --- a/docs/capabilities.json +++ b/docs/capabilities.json @@ -20,10 +20,8 @@ "GroupIdentify": "group-identify", "Identify": "identify", "next": { - "utils": [ - "Client.EnqueueAI", - "posthog.EnqueueAIWithContext" - ] + "Client.EnqueueAI": "capture-ai", + "posthog.EnqueueAIWithContext": "capture-ai" }, "posthog.EnqueueWithContext": "capture", "posthog.EvaluateFlagsWithContext": "evaluate-flags", From 01c6ac9a419f1412ff67f29333246d66e73bae54 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 15:41:03 -0500 Subject: [PATCH 07/15] ci: add a workflow that regenerates the reference by hand The release's reference step is best-effort, so a failure never blocks a release. generate-references.yml reruns it from main on demand and commits references/ when anything changed. Same shape as posthog-js's generate-references.yml. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/generate-references.yml | 59 +++++++++++++++++++++++ .github/workflows/release.yml | 2 + 2 files changed, 61 insertions(+) create mode 100644 .github/workflows/generate-references.yml diff --git a/.github/workflows/generate-references.yml b/.github/workflows/generate-references.yml new file mode 100644 index 00000000..a36441b0 --- /dev/null +++ b/.github/workflows/generate-references.yml @@ -0,0 +1,59 @@ +name: Generate references + +# Regenerates references/ by hand, for when the release's best-effort reference step fails +# or the pages need a refresh. Same shape as posthog-js's generate-references.yml. +on: + workflow_dispatch: + +permissions: {} + +jobs: + generate-references: + name: Generate SDK reference + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Get GitHub App token + id: releaser + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.GH_APP_POSTHOG_GO_RELEASER_APP_ID }} + private-key: ${{ secrets.GH_APP_POSTHOG_GO_RELEASER_PRIVATE_KEY }} + + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + token: ${{ steps.releaser.outputs.token }} + + - name: Check out sdk-specs + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: PostHog/sdk-specs + path: .sdk-specs + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version: '1.x' + cache: false + + - name: Generate references + id: changes + run: | + go run ./internal/cmd/reference --sdk-specs .sdk-specs + git add references + git diff --cached --quiet || echo "changed=true" >> "$GITHUB_OUTPUT" + + - name: Commit generated references + if: steps.changes.outputs.changed == 'true' + uses: planetscale/ghcommit-action@a6b150b81dca5dd027baa898604418eec9e11465 # v0.2.22 + with: + commit_message: "docs: update the SDK reference [skip ci]" + repo: ${{ github.repository }} + branch: main + file_pattern: references/ + env: + GITHUB_TOKEN: ${{ steps.releaser.outputs.token }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6b261d5d..d5fdc2d5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -138,6 +138,8 @@ jobs: persist-credentials: false - name: Regenerate SDK reference + # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. + continue-on-error: true # Stage the pages, so a new page shows in git status as a file, not as an untracked folder. run: | go run ./internal/cmd/reference --sdk-specs .sdk-specs From 02c3a65af1c3de8eb751126a61a064cb915c36b6 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 16:12:45 -0500 Subject: [PATCH 08/15] ci: don't let the sdk-specs checkout block a release Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d5fdc2d5..3a7008a7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -131,6 +131,8 @@ jobs: # The reference headings come from the sdk-specs capabilities. - name: Check out sdk-specs + # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. + continue-on-error: true uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: PostHog/sdk-specs From 5e1bb9c1a12520ccd1424e8da4ee24e303dcecfa Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 5 Nov 2026 16:22:12 -0500 Subject: [PATCH 09/15] ci: warn when the SDK reference doesn't regenerate The reference step is best-effort, so a failure leaves the release green. A ::warning:: annotation now says so and points to generate-references.yml. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3a7008a7..0f561ad6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -140,6 +140,7 @@ jobs: persist-credentials: false - name: Regenerate SDK reference + id: reference # Best-effort: a failure never blocks the release. Run generate-references.yml to retry. continue-on-error: true # Stage the pages, so a new page shows in git status as a file, not as an untracked folder. @@ -147,6 +148,10 @@ jobs: go run ./internal/cmd/reference --sdk-specs .sdk-specs git add references + - name: Warn if the SDK reference didn't regenerate + if: steps.reference.outcome == 'failure' + run: echo "::warning::The SDK reference didn't regenerate. Run generate-references.yml to retry." + - name: Check for version bump changes id: check-changes run: | From b01313e25a357ccb07bf087eca121b5e1fd188cb Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Mon, 9 Nov 2026 13:30:34 -0500 Subject: [PATCH 10/15] docs: open the Go getting-started page with the steps to a first event Co-Authored-By: Claude Opus 5.5 --- docs/getting-started.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/getting-started.md b/docs/getting-started.md index 7206fea5..81540966 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,5 +1,11 @@ # Getting started +The Go SDK runs on your server, on Go 1.21 or later. + +To send your first event, create a client with your project token and host from your [project settings](https://app.posthog.com/project/settings), then call `Enqueue` with a `Capture`. + +The client queues events and sends them in batches, so call `Close` before your program exits, or the last events are lost. + Install the module (Go 1.21 or later): ```bash From 349ecb301fae7d682170c95684acb12e31c72fcd Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 11 Nov 2026 12:03:31 -0500 Subject: [PATCH 11/15] fix(reference): fence code examples, list typed constants, create references/ - Doc-comment examples printed as indented code, which MDX doesn't support, so braces in them parsed as JSX. Print them as fenced Go blocks. - go/doc groups typed constants and variables under their type, and the type entry left them out, so values like CompressionGzip and every UnresolvedFlagReason weren't documented. Render them under the type. - Create references/ before writing, so generation works from a clean checkout. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/reference/main.go | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go index 6d71a0af..0275dd66 100644 --- a/internal/cmd/reference/main.go +++ b/internal/cmd/reference/main.go @@ -211,9 +211,14 @@ func methods(t *doc.Type, embedded map[string]bool) (out []entry) { return out } +// typeEntry renders a type with the constants and variables go/doc groups under it, such as an enum's values. func typeEntry(t *doc.Type) entry { children := append(funcs(t.Funcs, "posthog."), funcs(t.Methods, t.Name+".")...) - return entry{t.Name, block(t.Decl), markdown(t.Doc), children} + text := []string{markdown(t.Doc)} + for _, v := range append(t.Consts, t.Vars...) { + text = append(text, block(v.Decl), markdown(v.Doc)) + } + return entry{t.Name, block(t.Decl), strings.TrimSpace(strings.Join(text, "\n\n")), children} } func funcs(list []*doc.Func, prefix string) (out []entry) { @@ -233,14 +238,32 @@ func render(list []entry, level int) (out []string) { return out } -// markdown renders a doc comment. The site reads Markdown as MDX, so prose escapes < and braces. +// markdown renders a doc comment. The site reads Markdown as MDX, so prose escapes < and braces, and +// code examples print as fenced Go blocks, which MDX keeps as code. It doesn't support indented code. func markdown(text string) string { d := pkg.Parser().Parse(text) escape(d.Content) p := pkg.Printer() p.HeadingLevel = 5 p.DocLinkURL = func(l *comment.DocLink) string { return "#" + anchor(l.Recv+l.Name) } - return strings.TrimSpace(string(p.Markdown(d))) + var out []string + var prose []comment.Block + flush := func() { + if len(prose) > 0 { + out = append(out, strings.TrimSpace(string(p.Markdown(&comment.Doc{Content: prose, Links: d.Links})))) + prose = nil + } + } + for _, b := range d.Content { + if c, ok := b.(*comment.Code); ok { + flush() + out = append(out, code(strings.TrimRight(c.Text, "\n"))) + } else { + prose = append(prose, b) + } + } + flush() + return strings.Join(out, "\n\n") } var mdx = strings.NewReplacer("<", "<", "{", "{", "}", "}") @@ -334,6 +357,8 @@ func read(path string) string { } func write(file, front string, body []string) { + // A fresh checkout has no references folder yet. + check(os.MkdirAll("references", 0o755)) check(os.WriteFile(filepath.Join("references", file), []byte(strings.Join(append([]string{front}, body...), "\n\n")+"\n"), 0o644)) fmt.Println("wrote references/" + file) } From bed93140bf589daafe24a48f25e40e5862ae8cd8 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 11 Nov 2026 12:16:25 -0500 Subject: [PATCH 12/15] fix(reference): clean up the generated Go reference - Print each declaration with only the comments of the fields and methods go/doc kept, so unexported fields' comments don't show, and drop the blank lines a filtered member leaves. - Put package constants and variables under Constants and Variables headings in SDK utils. - Keep the EnqueueClient type entry, which public signatures take. - Align columns with spaces, the way gofmt does. - Tag a code example go only when it looks like Go, and text otherwise. - Point [Name] doc links at the symbol's heading. - Drop empty parts, the brace escapes the site no longer needs, and the printer's escaped backticks. - Read the module path from go.mod, so the next major's page installs and imports .../posthog-go/v2. - Fix the Properties example, which put the dots at the start of lines. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/reference/main.go | 108 ++++++++++++++++++++++++++++----- properties.go | 6 +- 2 files changed, 96 insertions(+), 18 deletions(-) diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go index 0275dd66..0999ebde 100644 --- a/internal/cmd/reference/main.go +++ b/internal/cmd/reference/main.go @@ -35,7 +35,6 @@ var ( first = []string{"setup", "capture", "identify"} classes = []string{"FeatureFlagEvaluations"} // client types that get their own H2 fset = token.NewFileSet() - notes []*ast.CommentGroup pkg *doc.Package mapped = map[string]label{} // entry label to capability slug, "" for SDK utils ) @@ -60,20 +59,27 @@ func main() { if !strings.HasSuffix(p, "_test.go") { f, err := parser.ParseFile(fset, p, nil, parser.ParseComments) check(err) - files, notes = append(files, f), append(notes, f.Comments...) + files = append(files, f) } } var labels map[string]any check(json.Unmarshal([]byte(read("docs/capabilities.json")), &labels)) load(labels, false) var err error - pkg, err = doc.NewFromFiles(fset, files, "github.com/posthog/posthog-go") + module := strings.TrimSpace(strings.TrimPrefix(strings.SplitN(read("go.mod"), "\n", 2)[0], "module")) + pkg, err = doc.NewFromFiles(fset, files, module) check(err) declared, _ := strconv.Atoi(strings.Split(strings.Trim(constant("Version"), `"`), ".")[0]) if *major == 0 { *major = declared } - body := append([]string{"## Getting started", nest(read("docs/getting-started.md"))}, reference(capabilities(*specs), *major <= declared)...) + // The next major's code lives on its own branch with its own module path, such as .../posthog-go/v2, + // and reuses this getting-started page, so its install and import lines take that path. + start := read("docs/getting-started.md") + if module != "github.com/posthog/posthog-go" && !strings.Contains(start, module) { + start = strings.ReplaceAll(start, "github.com/posthog/posthog-go", module) + } + body := append([]string{"## Getting started", nest(start)}, reference(capabilities(*specs), *major <= declared)...) title := fmt.Sprintf("%s %d.x", name, *major) if *major > declared { title += " (experimental)" @@ -144,7 +150,8 @@ func reference(caps [][2]string, current bool) []string { } } utils = append(utils, funcs(pkg.Funcs, "posthog.")...) - types = slices.DeleteFunc(types, func(e entry) bool { return embedded[e.title] }) + // An interface Client embeds keeps its type entry, because public signatures such as + // NewSlogCaptureHandler take it. Its methods are listed with Client's. // A mapped symbol moves to its capability, from wherever go/doc listed it. tagged, found := map[string][]entry{}, map[string]bool{} untagged := func(list []entry) []entry { @@ -184,8 +191,16 @@ func reference(caps [][2]string, current bool) []string { log.Fatalf("docs/capabilities.json: %s maps to %q, which is not an sdk-specs capability", list[0].title, slug) } out = append(append(out, "## SDK utils"), render(utils, 3)...) - for _, v := range append(pkg.Consts, pkg.Vars...) { - out = append(out, block(v.Decl), markdown(v.Doc)) + for _, group := range []struct { + heading string + values []*doc.Value + }{{"### Constants", pkg.Consts}, {"### Variables", pkg.Vars}} { + if len(group.values) > 0 { + out = append(out, group.heading) + } + for _, v := range group.values { + out = append(out, block(v.Decl), markdown(v.Doc)) + } } for _, c := range own { out = append(append(out, "## `"+c.title+"`", c.code, c.doc), render(c.children, 3)...) @@ -238,26 +253,29 @@ func render(list []entry, level int) (out []string) { return out } -// markdown renders a doc comment. The site reads Markdown as MDX, so prose escapes < and braces, and -// code examples print as fenced Go blocks, which MDX keeps as code. It doesn't support indented code. +// markdown renders a doc comment as Markdown. Prose escapes <, because the site keeps raw HTML in a page +// and would read as a tag. Code examples print as fenced blocks, tagged go only when they look like Go. func markdown(text string) string { d := pkg.Parser().Parse(text) escape(d.Content) p := pkg.Printer() p.HeadingLevel = 5 - p.DocLinkURL = func(l *comment.DocLink) string { return "#" + anchor(l.Recv+l.Name) } + p.DocLinkURL = docLink var out []string var prose []comment.Block flush := func() { if len(prose) > 0 { - out = append(out, strings.TrimSpace(string(p.Markdown(&comment.Doc{Content: prose, Links: d.Links})))) + // The printer escapes backticks so prose can't open a code span; doc comments use them for code. + md := strings.ReplaceAll(string(p.Markdown(&comment.Doc{Content: prose, Links: d.Links})), "\\`", "`") + out = append(out, strings.TrimSpace(md)) prose = nil } } for _, b := range d.Content { if c, ok := b.(*comment.Code); ok { flush() - out = append(out, code(strings.TrimRight(c.Text, "\n"))) + src := strings.TrimRight(c.Text, "\n") + out = append(out, "```"+language(src)+"\n"+src+"\n```") } else { prose = append(prose, b) } @@ -266,7 +284,38 @@ func markdown(text string) string { return strings.Join(out, "\n\n") } -var mdx = strings.NewReplacer("<", "<", "{", "{", "}", "}") +// language tags a code example go when it parses as Go, or looks like Go with placeholders such as +// NewWithConfig(...). Other examples, such as a list of default values, are text. +func language(src string) string { + if _, err := parser.ParseExpr(src); err == nil { + return "go" + } + for _, wrap := range []string{"package p\n%s", "package p\nfunc _() {\n%s\n}"} { + if _, err := parser.ParseFile(token.NewFileSet(), "", fmt.Sprintf(wrap, src), 0); err == nil { + return "go" + } + } + if strings.ContainsAny(src, "({") || strings.Contains(src, ":=") { + return "go" + } + return "text" +} + +// docLink points a [Name] doc link at the heading the reference gives that symbol: Type.Method for a +// method, the type's name for a type, and posthog.Name for a function. +func docLink(l *comment.DocLink) string { + if l.Recv != "" { + return "#" + anchor(l.Recv+"."+l.Name) + } + for _, t := range pkg.Types { + if t.Name == l.Name { + return "#" + anchor(l.Name) + } + } + return "#" + anchor("posthog."+l.Name) +} + +var mdx = strings.NewReplacer("<", "<") func escape(blocks []comment.Block) { for _, b := range blocks { @@ -297,15 +346,42 @@ func constant(want string) string { return "" } +// block prints a declaration with the comments of the fields and values go/doc kept, so the comments of +// unexported fields it filtered out don't show. func block(decl *ast.GenDecl) string { d := *decl d.Doc = nil - return code(source(&printer.CommentedNode{Node: &d, Comments: notes})) + var kept []*ast.CommentGroup + ast.Inspect(&d, func(n ast.Node) bool { + switch n := n.(type) { + case *ast.Field: + kept = append(kept, n.Doc, n.Comment) + case *ast.ValueSpec: + kept = append(kept, n.Doc, n.Comment) + case *ast.TypeSpec: + kept = append(kept, n.Comment) + } + return true + }) + kept = slices.DeleteFunc(kept, func(c *ast.CommentGroup) bool { return c == nil }) + // A filtered-out member leaves blank lines where it was, such as right after an interface's brace. + lines := strings.Split(source(&printer.CommentedNode{Node: &d, Comments: kept}), "\n") + var out []string + for i, line := range lines { + blank := strings.TrimSpace(line) == "" + afterOpen := len(out) > 0 && strings.HasSuffix(out[len(out)-1], "{") + beforeClose := i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), "}") + if !blank || (!afterOpen && !beforeClose) { + out = append(out, line) + } + } + return code(strings.Join(out, "\n")) } +// source prints a node the way gofmt does: tabs indent, spaces align columns. func source(node any) string { var buf bytes.Buffer - check(printer.Fprint(&buf, fset, node)) + check((&printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}).Fprint(&buf, fset, node)) return buf.String() } @@ -359,6 +435,8 @@ func read(path string) string { func write(file, front string, body []string) { // A fresh checkout has no references folder yet. check(os.MkdirAll("references", 0o755)) + // A symbol with no doc comment leaves an empty part, which would print as a run of blank lines. + body = slices.DeleteFunc(slices.Clone(body), func(s string) bool { return strings.TrimSpace(s) == "" }) check(os.WriteFile(filepath.Join("references", file), []byte(strings.Join(append([]string{front}, body...), "\n\n")+"\n"), 0o644)) fmt.Println("wrote references/" + file) } diff --git a/properties.go b/properties.go index 37ea734c..4fda2371 100644 --- a/properties.go +++ b/properties.go @@ -9,9 +9,9 @@ package posthog // posthog.Capture{ // DistinctId: "0123456789", // Event: "order completed", -// Properties: posthog.NewProperties() -// .Set("revenue", 10.0) -// .Set("currency", "USD"), +// Properties: posthog.NewProperties(). +// Set("revenue", 10.0). +// Set("currency", "USD"), // } type Properties map[string]interface{} From e61729965bc3dc9e88973fe3e99f80200e30dbd7 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 11 Nov 2026 12:17:07 -0500 Subject: [PATCH 13/15] fix(reference): drop the blank line nest leaves after the dropped H1 Co-Authored-By: Claude Opus 5.5 --- internal/cmd/reference/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go index 0999ebde..f1609066 100644 --- a/internal/cmd/reference/main.go +++ b/internal/cmd/reference/main.go @@ -423,7 +423,7 @@ func nest(page string) string { out = append(out, "#"+line) } } - return strings.Join(out, "\n") + return strings.TrimSpace(strings.Join(out, "\n")) } func read(path string) string { From 3cc634a97a17b810d559d46fca3844c39db6649f Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 11 Nov 2026 12:20:55 -0500 Subject: [PATCH 14/15] fix(reference): tag an example go only when it parses, and trim blanks inside parentheses A ... placeholder is read as an argument, so examples such as NewWithConfig(...) still parse as Go, and prose with a parenthesis no longer passes as code. A const block no longer opens with a blank line. Co-Authored-By: Claude Opus 5.5 --- internal/cmd/reference/main.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/internal/cmd/reference/main.go b/internal/cmd/reference/main.go index f1609066..5fba6309 100644 --- a/internal/cmd/reference/main.go +++ b/internal/cmd/reference/main.go @@ -284,9 +284,10 @@ func markdown(text string) string { return strings.Join(out, "\n\n") } -// language tags a code example go when it parses as Go, or looks like Go with placeholders such as -// NewWithConfig(...). Other examples, such as a list of default values, are text. +// language tags a code example go when it parses as Go, reading a ... placeholder such as +// NewWithConfig(...) as an argument. Other examples, such as a list of default values, are text. func language(src string) string { + src = strings.ReplaceAll(src, "...", "_") if _, err := parser.ParseExpr(src); err == nil { return "go" } @@ -295,9 +296,6 @@ func language(src string) string { return "go" } } - if strings.ContainsAny(src, "({") || strings.Contains(src, ":=") { - return "go" - } return "text" } @@ -364,13 +362,17 @@ func block(decl *ast.GenDecl) string { return true }) kept = slices.DeleteFunc(kept, func(c *ast.CommentGroup) bool { return c == nil }) - // A filtered-out member leaves blank lines where it was, such as right after an interface's brace. + // A filtered-out member leaves blank lines where it was, such as right after a brace or parenthesis. lines := strings.Split(source(&printer.CommentedNode{Node: &d, Comments: kept}), "\n") var out []string for i, line := range lines { blank := strings.TrimSpace(line) == "" - afterOpen := len(out) > 0 && strings.HasSuffix(out[len(out)-1], "{") - beforeClose := i+1 < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i+1]), "}") + afterOpen := len(out) > 0 && strings.HasSuffix(out[len(out)-1], "{") || len(out) > 0 && strings.HasSuffix(out[len(out)-1], "(") + next := "" + if i+1 < len(lines) { + next = strings.TrimSpace(lines[i+1]) + } + beforeClose := strings.HasPrefix(next, "}") || strings.HasPrefix(next, ")") if !blank || (!afterOpen && !beforeClose) { out = append(out, line) } From 8274f608f8db5866ade1fbad92471d28879512f0 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Wed, 11 Nov 2026 12:38:57 -0500 Subject: [PATCH 15/15] docs: map Client.Emails to the emails capability Main added Client.Emails, and the generator stops on a member with no capability, so the release step would skip the pages. Co-Authored-By: Claude Opus 5.5 --- docs/capabilities.json | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/capabilities.json b/docs/capabilities.json index 6b81befe..c5c5de20 100644 --- a/docs/capabilities.json +++ b/docs/capabilities.json @@ -4,6 +4,7 @@ "Capture": "capture", "Client.Close": "shutdown", "Client.CloseWithContext": "shutdown", + "Client.Emails": "emails", "Client.EvaluateFlags": "evaluate-flags", "Client.Flush": "flush", "Client.FlushWithContext": "flush",