Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ core/event/ the change event of patch-it's contract: types, fingerpri
core/diff/ core/normalize/ core/hint/ the OpenAPI diff engine and its helpers
plugins/<kind>/ one package per kind, with its providers: openapi (+ adapter/, one spec adapter
per provider), notices (+ retire/, feed/, eol/), migrationguide (+ sdkguide/,
members/), changelog (Markdown, RST or JSON), catalog, apisurface (+ pysurface/);
members/), changelog (Markdown, RST or JSON), catalog, apisurface (+ pysurface/, dtsurface/);
plugins/all imports every one
cmd/list-plugins/ prints the list from the registry (make plugins); internal/pluginlist/ is its logic
cmd/new-plugin/ scaffolds a provider's source on a kind (make new-plugin ARGS=...; go run ./cmd/new-plugin --help)
Expand Down
79 changes: 78 additions & 1 deletion cmd/new-plugin/formats.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ var defaultReaders = map[string]string{
"notices": "deprecations",
"migrationguide": "sdk",
"changelog": "markdown",
"apisurface": "pypi", // npm when a --package is npm:
}

var formats = map[string]formatSpec{
Expand Down Expand Up @@ -541,7 +542,7 @@ func {{.Lower}}Ingest(t *testing.T, file string) []event.Event {
imports: []string{"context", "fmt", "os", "github.com/patch-it-dev/patch-it-plugins/plugins/openapi/adapter", "github.com/patch-it-dev/patch-it-plugins/core/event", "github.com/patch-it-dev/patch-it-plugins/core/plugin"},
next: "Write LatestTag, Fetch and Versions in plugins/openapi/adapter/{{.File}}.go (fetch.Get only); add Diff/Keep to the Register line if the spec needs them (see vercel.go).",
},
"apisurface": {
"apisurface/pypi": {
kind: "apisurface",
layer: "sdk",
defDir: "plugins/apisurface",
Expand Down Expand Up @@ -611,6 +612,82 @@ func {{.Lower}}Ingest(t *testing.T, file string) []event.Event {
imports: []string{"archive/zip", "bytes", "context", "fmt", "github.com/patch-it-dev/patch-it-plugins/core/event"},
next: "Save two real wheels of the package and serve them in {{.Lower}}Ingest; the kind reads their .py files, never runs them.",
},
"apisurface/npm": {
kind: "apisurface",
layer: "sdk",
defDir: "plugins/apisurface",
def: `package apisurface

// {{.Ident}} is {{.Provider}}'s package on npm, its public API read from each
// release's TypeScript declarations.
//
// ` + todo + `: check the name on npm, and that its tarball has .d.ts
// files (package.json's "types" or "exports"). Say what you checked, with
// the date.
var {{.Ident}} = npmPackage("{{.ID}}", "{{.NPM}}")
`,
register: `plugin.Register(Plugin{Package: {{.Ident}}})`,
pluginOf: `Plugin{Package: {{.Ident}}}`,
fixtures: map[string]string{
"{{.File}}-old.d.ts": "// ` + todo + `: a placeholder for the older release's declarations. Save the real release's tarball instead (see npm_test.go).\nexport declare function placeholder(a: string, b?: number): void;\n",
"{{.File}}-new.d.ts": "// ` + todo + `: a placeholder for the newer release's declarations: b is no longer optional, one event.\nexport declare function placeholder(a: string, b: number): void;\n",
},
// The drop test's newer release: the older one again, a name added.
dropFile: "// ` + todo + `: a placeholder: a release that only adds.\nexport declare function placeholder(a: string, b?: number): void;\nexport declare function added(): void;\n",
source: "{{.File}}-new.d.ts",
ingest: `// {{.Lower}}Ingest compares two releases: 1.0.0, a tarball holding
// testdata/{{.File}}-old.d.ts as index.d.ts, and 1.1.0, one holding file.
// The tarballs are built here so the placeholders are text.
// ` + todo + `: save the two real tarballs (trimmed if they're large, as
// npm_test.go's are) and serve them instead.
func {{.Lower}}Ingest(t *testing.T, file string) []event.Event {
t.Helper()
tarball := func(src string) []byte {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
for name, body := range map[string][]byte{
"package/package.json": []byte(` + "`" + `{"name": "{{.NPM}}", "types": "index.d.ts"}` + "`" + `),
"package/index.d.ts": kittest.Read(t, src),
} {
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil {
t.Fatal(err)
}
tw.Write(body)
}
if err := tw.Close(); err != nil {
t.Fatal(err)
}
gz.Close()
return buf.Bytes()
}
reg := "https://registry.npmjs.org/" + strings.ReplaceAll("{{.NPM}}", "/", "%2F")
files := map[string][]byte{
reg: []byte(` + "`" + `{"versions": {"1.0.0": {}, "1.1.0": {}}, "time": {"1.0.0": "2026-01-01T00:00:00Z", "1.1.0": "2026-02-01T00:00:00Z"}}` + "`" + `),
reg + "/1.0.0": []byte(` + "`" + `{"dist": {"tarball": "https://example.com/{{.File}}-1.0.0.tgz"}}` + "`" + `),
reg + "/1.1.0": []byte(` + "`" + `{"dist": {"tarball": "https://example.com/{{.File}}-1.1.0.tgz"}}` + "`" + `),
"https://example.com/{{.File}}-1.0.0.tgz": tarball("testdata/{{.File}}-old.d.ts"),
"https://example.com/{{.File}}-1.1.0.tgz": tarball(file),
}
env := kittest.Env(t, nil)
env.Get = func(_ context.Context, url string) ([]byte, error) {
if b, ok := files[url]; ok {
return b, nil
}
t.Errorf("fetched %s, which the test didn't save", url)
return nil, fmt.Errorf("no saved copy of %s", url)
}
ctx, p := context.Background(), Plugin{Package: {{.Ident}}}
vs, err := p.ListVersions(ctx, env)
if err != nil || len(vs) != 2 {
t.Fatalf("versions %v: %v", vs, err)
}
return kittest.Versions(t, env, p, vs[0], vs[1])
}
`,
imports: []string{"archive/tar", "bytes", "compress/gzip", "context", "fmt", "strings", "github.com/patch-it-dev/patch-it-plugins/core/event"},
next: "Save two real tarballs of the package and serve them in {{.Lower}}Ingest; the kind reads their .d.ts files, never runs them.",
},
}

// testFile is the generated test, the same for every format.
Expand Down
20 changes: 15 additions & 5 deletions cmd/new-plugin/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,9 @@ func (o Options) template() (string, error) {
return o.Kind, nil
}
r := cmp(o.Reader, defaultReaders[o.Kind])
if o.Kind == "apisurface" && o.Reader == "" && slices.ContainsFunc(o.Packages, func(p string) bool { return strings.HasPrefix(p, "npm:") }) {
r = "npm" // the package's ecosystem picks the reader
}
if _, ok := formats[o.Kind+"/"+r]; !ok {
return "", fmt.Errorf("--reader %q: kind %s's readers are %s", o.Reader, o.Kind, readerHelp())
}
Expand All @@ -192,10 +195,10 @@ var (

// data is what the templates fill in.
type data struct {
ID, Name, Ident, Lower, ProviderID, Provider, Source, File, Format, Kind, Module, PyPI string
Slug string // the provider, lowercase: a model subject's provider
SourceFile, DropFile, PluginOf, Ingest, Drop string
Imports []string
ID, Name, Ident, Lower, ProviderID, Provider, Source, File, Format, Kind, Module, PyPI, NPM string
Slug string // the provider, lowercase: a model subject's provider
SourceFile, DropFile, PluginOf, Ingest, Drop string
Imports []string
}

// Run scaffolds the source, or changes nothing and says why.
Expand Down Expand Up @@ -233,7 +236,7 @@ func Run(o Options, out io.Writer) error {
}
}
if len(o.Packages) == 0 && f.kind == "apisurface" {
o.Packages = []string{"pypi:" + o.ProviderID}
o.Packages = []string{strings.TrimPrefix(o.tmpl, "apisurface/") + ":" + o.ProviderID}
}
for _, p := range o.Packages {
eco, name, ok := strings.Cut(p, ":")
Expand Down Expand Up @@ -268,6 +271,13 @@ func Run(o Options, out io.Writer) error {
break
}
}
d.NPM = o.ProviderID
for _, p := range o.Packages {
if name, ok := strings.CutPrefix(p, "npm:"); ok {
d.NPM = name
break
}
}
d.Module = strings.ReplaceAll(strings.ToLower(d.PyPI), "-", "_")
d.Ident = ident(o.name)
d.Lower = string(unicode.ToLower(rune(d.Ident[0]))) + d.Ident[1:]
Expand Down
2 changes: 1 addition & 1 deletion cmd/new-plugin/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func hash(b []byte) string {
// name, category and homepage not asked again.
func TestAsksWhatIsMissing(t *testing.T) {
o := Options{ProviderID: "stripe"}
in := bufio.NewReader(strings.NewReader("python-sdk\napisurface\nsdk\nhttps://pypi.org/project/stripe/\npypi:stripe\nRemoved names\n"))
in := bufio.NewReader(strings.NewReader("python-sdk\napisurface\npypi\nsdk\nhttps://pypi.org/project/stripe/\npypi:stripe\nRemoved names\n"))
var out bytes.Buffer
if err := ask(&o, in, &out); err != nil {
t.Fatal(err)
Expand Down
2 changes: 1 addition & 1 deletion docs/which-kind.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Every kind is one of two shapes ([writing-a-plugin.md, step 4](writing-a-plugin.
| Is there a **changelog**: a file per release (`CHANGELOG.md`, `CHANGES.rst`, `HISTORY.rst`), or a machine-readable JSON changelog? | `changelog` | The release's section at its tag (reader `markdown`), or the life-cycle entries a JSON changelog adds commit by commit (reader `json`) | Keep a Changelog files; reStructuredText release notes; an API changelog JSON in a repo; a Terraform provider's changelog |
| Is there a **live page of dated notices**: a deprecations or shutdown table, an end-of-life table, or an **RSS/Atom feed** of announcements? | `notices` | The page as it is now, cited through a Web Archive snapshot, against the snapshot kept from the read before: a living page, with no versions of its own (reader `deprecations`, `feed`, or an end-of-life table) | A model deprecations page; an API end-of-life policy table; a changelog feed with a "deprecation" label; a Kubernetes API removals page |
| Is there a **flat catalog**, one JSON entry per name (a command, an endpoint), with no release tags? | `catalog` | Two snapshots, compared for names that disappeared entirely | A list of commands a server accepts, kept in a repo |
| Is it a **published package** with no changelog worth reading? | `apisurface` | Each release's files from the registry (PyPI first), compared: removed or renamed classes, functions, methods, and parameters removed or newly required | An SDK generated from a spec, released often, whose changelog says "chore: update types" |
| Is it a **published package** with no changelog worth reading? | `apisurface` | Each release's files from the registry (PyPI wheels, npm TypeScript declarations), compared: removed or renamed classes, functions, methods, and parameters removed or newly required | An SDK generated from a spec, released often, whose changelog says "chore: update types" |

Still no "yes"? Open a [discussion](https://github.com/patch-it-dev/patch-it-plugins/discussions) with the source's link: a new kind is a new package under `plugins/`, and the questions above get one more row.

Expand Down
6 changes: 4 additions & 2 deletions docs/writing-a-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Write the numbers on the provider page, as `providers/vercel.md` does for its sp
| `plugins/migrationguide` | A guide that lists what a release removed, at the release's tag: an SDK's migration guide per new major (removed request parameters), or a package's table of removed members (an RST simple table or a Markdown pipe table) | A `sdkguide.Guide` in `plugins/migrationguide/sdkguide/`, or a `members.Guide` in `plugins/migrationguide/members/` |
| `plugins/changelog` | A changelog: a `CHANGELOG.md` / `CHANGES.rst` / `HISTORY.rst`, each release's section at its tag (releases from PyPI or npm), or a vendor's machine-readable API changelog in JSON (per day, endpoint and API version, oasdiff change codes), commit by commit | A `changelog.File` with its `TagPrefix`, or a `changelog.Log` |
| `plugins/catalog` | A flat JSON catalog, one entry per name, with no release tags to pin — a commit SHA stands in | A `catalog.Catalog`, diffed between two snapshots for names that disappeared entirely |
| `plugins/apisurface` | A published package's public API, compared between two releases: the classes, functions, methods and parameters in each release's files (Python first: the wheel or sdist from PyPI) | A `apisurface.Package` (registry name, ecosystem, top-level module) and its `plugin.RegisterProvider` block |
| `plugins/apisurface` | A published package's public API, compared between two releases: the classes, functions, methods and parameters in each release's files (the wheel or sdist from PyPI, the TypeScript declarations in an npm tarball) | An `apisurface.Package` (registry name, ecosystem, top-level module; `npmPackage` for npm) and its `plugin.RegisterProvider` block |

## 4. The interface

Expand Down Expand Up @@ -149,7 +149,9 @@ A living page (a deprecations page, a feed: a `notices` source) only shows its l

### The `apisurface` kind: reading a package's API without running it

`plugins/apisurface` downloads a release's wheel (or sdist) through `env.Get`, opens it in memory (`archive/zip`, `archive/tar`: nothing is written to disk) and hands the `.py` and `.pyi` files to `plugins/apisurface/pysurface`, which reads them as text: logical lines, indentation, and the headers of `def`, `class`, `__all__` and `from … import`. Nothing in the package is imported, compiled or run. That's the safest way to read code someone else publishes, and it needs no dependency: a Python interpreter (the `ast` module) would mean running a second runtime next to the plugins, and the pure-Go Python parsers available follow old grammars and pull in a large module for what is a few hundred lines here. The cost is that only signatures are read, never what a body does, and anything the reader can't be sure of is left out (see `providers/openai-python-sdk.md`). Archive and file sizes are capped (`MaxFileBytes`, `MaxSourceBytes`), so a crafted release can't exhaust the runner.
`plugins/apisurface` downloads a release's wheel (or sdist) through `env.Get`, opens it in memory (`archive/zip`, `archive/tar`: nothing is written to disk) and hands the `.py` and `.pyi` files to `plugins/apisurface/pysurface`, which reads them as text: logical lines, indentation, and the headers of `def`, `class`, `__all__` and `from … import`. Nothing in the package is imported, compiled or run. That's the safest way to read code someone else publishes, and it needs no dependency: a Python interpreter (the `ast` module) would mean running a second runtime next to the plugins, and the pure-Go Python parsers available follow old grammars and pull in a large module for what is a few hundred lines here. The cost is that only signatures are read, never what a body does, and anything the reader can't be sure of is left out (see `providers/openai-python-surface.md`). Archive and file sizes are capped (`MaxFileBytes`, `MaxSourceBytes`), so a crafted release can't exhaust the runner.

An npm release is read the same way: its tarball (the version document's `dist.tarball`) is opened in memory and only `package.json` and the `.d.ts`, `.d.mts` and `.d.cts` files are kept, for `plugins/apisurface/dtsurface`. Declaration files hold declarations only, never statements, so a tokenizer and a parser of declarations, which skips each type expression by its brackets, read every name, member and parameter a caller can see, in about a thousand lines of standard-library Go. The alternatives would each be worse here: the TypeScript compiler is JavaScript, so it would mean running Node and code from npm next to the plugins; the Go ports of TypeScript's parser are internal to their projects or need cgo (tree-sitter); and a full type checker is far more than a public-API diff needs. No package code runs, no install script runs, no dependency is added (the `make imports` allowlist is unchanged). What it doesn't do, on purpose: resolve types (a property's type isn't followed), or read interface members (see `providers/openai-node-surface.md`).

An event cites the newer release's file, and its excerpt quotes the definition's path and line in both releases. npm packages (`.d.ts` files) are next.

Expand Down
12 changes: 8 additions & 4 deletions internal/pluginlist/pluginlist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package pluginlist

import (
"encoding/json"
"slices"
"strings"
"testing"

Expand Down Expand Up @@ -42,8 +43,9 @@ func TestBuildListsEveryRegisteredSource(t *testing.T) {
}
}

// One provider, several sources: Algolia's three APIs.
func TestAlgoliaIsOneProviderWithThreeSources(t *testing.T) {
// One provider, several sources: Algolia's three APIs (and its other
// sources), merged across kinds into one provider.
func TestAlgoliaIsOneProviderWithItsSources(t *testing.T) {
b, err := Marshal(Build("v1.2.3"))
if err != nil {
t.Fatal(err)
Expand All @@ -63,8 +65,10 @@ func TestAlgoliaIsOneProviderWithThreeSources(t *testing.T) {
t.Errorf("%s: page %s isn't at the release", s.ID, s.Page)
}
}
if got := strings.Join(ids, " "); got != "algolia/ingestion-api algolia/recommend-api algolia/search-api" {
t.Errorf("algolia's sources: %s", got)
for _, want := range []string{"algolia/ingestion-api", "algolia/recommend-api", "algolia/search-api"} {
if !slices.Contains(ids, want) {
t.Errorf("algolia's sources %v lack %s", ids, want)
}
}
return
}
Expand Down
Loading
Loading