@theholocron/holocron-plugin-postman 5.0.0-alpha.46 → 5.0.0-alpha.460

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ <!-- alex disable postman-postwoman -->
2
+
1
3
  # `@theholocron/holocron-plugin-postman`
2
4
 
3
5
  Postman plugin for [Holocron](../cli). Implements the **multi-cardinality**
@@ -17,17 +19,18 @@ Postman ships a CLI (`postman`, the newer + more capable successor to
17
19
  `newman`), but for our `tooling` surface — collection / spec / environment
18
20
  **management** — REST is the canonical interface and avoids a system-binary
19
21
  dependency. The CLI is best suited for running collections (the newman use
20
- case); we sync, we don't run.
22
+ case); we sync, we don't run. The one thing it uses the CLI for is `export`
23
+ (below), which has no REST equivalent.
21
24
 
22
25
  ## Auth
23
26
 
24
27
  Token resolution order:
25
28
 
26
29
  1. `--token <KEY>` flag on the holocron invocation
27
- 2. `HOLOCRON_POSTMAN_API_KEY` env var
30
+ 2. `HOLOCRON_POSTMAN_TOKEN` env var
28
31
  3. `POSTMAN_API_KEY` env var (Postman's own standard)
29
32
  4. Keyring `postman.<org>` — tried first when an org is active via `--org`, `HOLOCRON_ORG`, or `org` in `holocron.config.ts`
30
- 5. Keyring `postman` — unnamespaced fallback; set via `holocron auth set postman <key>`
33
+ 5. Keyring `postman` — unnamespaced fallback; set via `holocron new token postman <key>`
31
34
 
32
35
  Generate the key at <https://web.postman.co/settings/me/api-keys>.
33
36
 
@@ -55,31 +58,36 @@ Generate the key at <https://web.postman.co/settings/me/api-keys>.
55
58
 
56
59
  ```
57
60
 
58
- - `workspaceId` (required) — Postman workspace id. Find via `holocron tooling postman workspaces`.
61
+ - `workspace` / `workspaceId` (one is required) — the workspace by name (`sync` finds it, or makes it) or by id (wins over the name). Find an id via `holocron tooling postman workspaces`.
62
+ - `workspaceType` (optional) — `personal` (default) or `team`: the type of a workspace `sync` makes.
63
+ - `collectionFiles` (optional) — hand-written Postman collection JSON files. Each is matched to a collection in the workspace by `info.name` and replaced in place, or created.
59
64
  - `specFile` (optional) — relative path to the local OpenAPI JSON. `sync` reads + uploads this.
60
65
  - `specName` (optional) — display name in Postman's Spec Hub. Defaults to repo name.
61
66
  - `collectionName` (optional) — name for the imported collection. Defaults to `specName`.
62
- - `envFiles` (optional) — local Postman environment JSON files to push.
67
+ - `envFiles` (optional) — local Postman environment JSON files to push. A secret the file leaves empty keeps the value the environment already holds.
68
+
69
+ `sync` needs at least one of `specFile`, `collectionFiles` and `envFiles`.
63
70
 
64
71
  ## What's implemented
65
72
 
66
- | Method | What it does |
67
- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
68
- | **Tooling interface** | |
69
- | `sync()` | Reads `specFile`, upserts the Spec Hub spec, delete-then-imports the collection, find-or-creates each env in `envFiles`. |
70
- | `doctor()` | Probes `/me` + `/workspaces`; returns `{ ok, message }`. |
71
- | **Postman-specific methods** (on `PostmanTooling`, not on the `Tooling` interface) | |
72
- | `getMyself` | `GET /me` — authed user identity. |
73
- | `listWorkspaces` | `GET /workspaces`. |
74
- | `findCollectionByName` | `GET /collections?workspace=…` + name filter. |
75
- | `deleteCollection` | `DELETE /collections/{uid}`. |
76
- | `importOpenApi` | `POST /import/openapi?workspace=…` with the spec stringified into `{ type: "string", input }`. |
77
- | `findEnvironmentByName` | `GET /environments?workspace=…` + name filter. |
78
- | `createEnvironment` | `POST /environments?workspace=…`. |
79
- | `updateEnvironment` | `PUT /environments/{uid}`. |
80
- | `findSpecByName` | `GET /specs?workspaceId=…` + name filter. |
81
- | `createSpec` | `POST /specs?workspaceId=…` (flat body — name/type are NOT wrapped under `spec`). |
82
- | `upsertSpecFile` | `PATCH /specs/{id}/files/{path}` (PUT returns 404 here). |
73
+ | Method | What it does |
74
+ | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | **Tooling interface** | |
76
+ | `sync()` | Finds or makes the workspace; with `specFile`, upserts the Spec Hub spec and delete-then-imports the collection; replaces or creates each `collectionFiles` collection; find-or-creates each env in `envFiles`. |
77
+ | `export(input)` | Optional. Runs `postman collection migrate <file> --output <dir>` for each collection file (the Postman CLI, `brew install --cask postman-cli`, or `./.humans/setup.sh` in this repo) and lists the files it wrote, one folder per collection: Postman's schema 3.0 YAML. An environment file is reported as not exported. No API key, no workspace. A dry run migrates into a temporary folder and removes it. Not verified against the real CLI. |
78
+ | `doctor()` | Probes `/me` + `/workspaces`; returns `{ ok, message }`. |
79
+ | **Postman-specific methods** (on `PostmanTooling`, not on the `Tooling` interface) | |
80
+ | `getMyself` | `GET /me` — authed user identity. |
81
+ | `listWorkspaces` | `GET /workspaces`. |
82
+ | `findCollectionByName` | `GET /collections?workspace=…` + name filter. |
83
+ | `deleteCollection` | `DELETE /collections/{uid}`. |
84
+ | `importOpenApi` | `POST /import/openapi?workspace=…` with the spec stringified into `{ type: "string", input }`. |
85
+ | `findEnvironmentByName` | `GET /environments?workspace=…` + name filter. |
86
+ | `createEnvironment` | `POST /environments?workspace=…`. |
87
+ | `updateEnvironment` | `PUT /environments/{uid}`. |
88
+ | `findSpecByName` | `GET /specs?workspaceId=…` + name filter. |
89
+ | `createSpec` | `POST /specs?workspaceId=…` (flat body — name/type are NOT wrapped under `spec`). |
90
+ | `upsertSpecFile` | `PATCH /specs/{id}/files/{path}` (PUT returns 404 here). |
83
91
 
84
92
  ## Status
85
93
 
package/dist/index.d.mts CHANGED
@@ -1,11 +1,25 @@
1
- import { AuthError, ResolveTokenInput, Tooling, ToolingDoctorReport } from "@theholocron/cli";
1
+ /**
2
+ * `@theholocron/holocron-plugin-postman` — entrypoint.
3
+ *
4
+ * Implements the `tooling` capability against Postman's REST API.
5
+ * See README for auth + config docs.
6
+ */
7
+ import { AuthError, PluginToken, ResolveTokenInput, Tooling, ToolingDoctorReport, ToolingExportInput, ToolingExportResult, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess } from "@theholocron/cli";
8
+ import { spawnSync } from "node:child_process";
2
9
  import { PostmanClient, PostmanClient as PostmanClient$1, PostmanClientOptions, PostmanCollection, PostmanEnvironment, PostmanPlanLimitError, PostmanSpec, PostmanUser, PostmanWorkspace, createPostmanClient, detectPlanLimit } from "@theholocron/postman-client";
3
- //#region src/auth.d.ts
4
- declare const resolveToken: (input?: ResolveTokenInput) => string;
5
- //#endregion
6
- //#region src/capabilities/tooling.d.ts
10
+ /** Resolves the Postman API key from `--token`, `HOLOCRON_POSTMAN_TOKEN`, `POSTMAN_API_KEY` or the keyring, and throws an `AuthError` when none is set. */
11
+ export declare const resolveToken: import("@theholocron/cli").TokenResolver;
12
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`. */
13
+ export declare const tokens: PluginToken[];
7
14
  interface PostmanToolingOptions {
8
- workspaceId: string;
15
+ /** Postman workspace id. Wins over `workspace`. */
16
+ workspaceId?: string;
17
+ /** Workspace name; found, or made on `sync()` when no workspace has it. */
18
+ workspace?: string;
19
+ /** Type of a workspace `sync()` makes. Defaults to `personal`. */
20
+ workspaceType?: "personal" | "team";
21
+ /** Local Postman collection JSON files to push (relative to repoRoot), matched to Postman's by `info.name`. */
22
+ collectionFiles?: string[];
9
23
  /** Local OpenAPI JSON path (relative to repoRoot). */
10
24
  specFile?: string;
11
25
  /** Display name in Postman. Defaults to the OpenAPI spec's `info.title`. */
@@ -16,46 +30,87 @@ interface PostmanToolingOptions {
16
30
  envFiles?: string[];
17
31
  /** Working repo root. Defaults to process.cwd(). */
18
32
  repoRoot?: string;
33
+ /** Override the spawn function the Postman CLI is run with, in tests. */
34
+ spawn?: typeof spawnSync;
19
35
  }
20
- declare class PostmanTooling implements Tooling {
36
+ /** The Postman implementation of the `tooling` capability: syncs an OpenAPI spec, collection and environments into a workspace. */
37
+ export declare class PostmanTooling implements Tooling {
21
38
  private readonly client;
39
+ /** The capability this class provides, always `"tooling"`. */
22
40
  readonly key: "tooling";
41
+ /** The provider name, `"postman"`. */
23
42
  readonly providerName = "postman";
24
43
  private readonly opts;
25
44
  private readonly repoRoot;
45
+ private workspaceIdPromise;
26
46
  constructor(client: () => PostmanClient$1, opts: PostmanToolingOptions);
27
47
  sync(): Promise<void>;
48
+ private syncSpec;
49
+ private syncCollectionFile;
50
+ private syncEnvironmentFile;
51
+ /** The workspace id: `workspaceId`, else the workspace named `workspace`, which is made when absent. Memoized. */
52
+ private resolveWorkspaceId;
53
+ /**
54
+ * Writes each collection file in Postman's schema 3.0 YAML layout under `input.outDir` by running the Postman CLI
55
+ * (`postman collection migrate`), one folder per collection. Environment files are reported as issues, not exported.
56
+ * Needs the CLI on the PATH and no API key: it never touches the workspace.
57
+ */
58
+ export(input: ToolingExportInput): Promise<ToolingExportResult>;
59
+ /** Checks the key and the configured workspace; reports the authenticated user and the workspace, or why either failed. */
28
60
  doctor(): Promise<ToolingDoctorReport>;
61
+ /** Returns the authenticated Postman user. */
29
62
  getMyself(): Promise<PostmanUser>;
63
+ /** Lists the workspaces the key can see. */
30
64
  listWorkspaces(): Promise<PostmanWorkspace[]>;
65
+ /** Finds a collection in the workspace by exact name, or `null` when there is none. */
31
66
  findCollectionByName(input: {
32
67
  workspaceId: string;
33
68
  name: string;
34
69
  }): Promise<PostmanCollection | null>;
70
+ /** Creates a collection in the workspace from a Postman collection document. */
71
+ createCollection(input: {
72
+ workspaceId: string;
73
+ collection: unknown;
74
+ }): Promise<PostmanCollection>;
75
+ /** Replaces the collection with this uid. */
76
+ updateCollection(input: {
77
+ uid: string;
78
+ collection: unknown;
79
+ }): Promise<PostmanCollection>;
80
+ /** Deletes the collection with this uid. */
35
81
  deleteCollection(uid: string): Promise<void>;
82
+ /** Imports an OpenAPI document into the workspace as a collection; throws when Postman returns none. */
36
83
  importOpenApi(input: {
37
84
  workspaceId: string;
38
85
  spec: unknown;
39
86
  }): Promise<PostmanCollection>;
87
+ /** Lists the workspace's environments. */
40
88
  listEnvironments(input: {
41
89
  workspaceId: string;
42
90
  }): Promise<PostmanEnvironment[]>;
91
+ /** Finds an environment in the workspace by exact name, or `null` when there is none. */
43
92
  findEnvironmentByName(input: {
44
93
  workspaceId: string;
45
94
  name: string;
46
95
  }): Promise<PostmanEnvironment | null>;
96
+ /** Reads one environment with its variables. */
97
+ getEnvironment(uid: string): Promise<PostmanEnvironment>;
98
+ /** Creates an environment in the workspace. */
47
99
  createEnvironment(input: {
48
100
  workspaceId: string;
49
101
  environment: unknown;
50
102
  }): Promise<PostmanEnvironment>;
103
+ /** Replaces the environment with this uid. */
51
104
  updateEnvironment(input: {
52
105
  uid: string;
53
106
  environment: unknown;
54
107
  }): Promise<PostmanEnvironment>;
108
+ /** Finds an API spec in the workspace by exact name, or `null` when there is none. */
55
109
  findSpecByName(input: {
56
110
  workspaceId: string;
57
111
  name: string;
58
112
  }): Promise<PostmanSpec | null>;
113
+ /** Creates an API spec in the workspace from the given file content. */
59
114
  createSpec(input: {
60
115
  workspaceId: string;
61
116
  name: string;
@@ -63,36 +118,21 @@ declare class PostmanTooling implements Tooling {
63
118
  filePath?: string;
64
119
  fileContent: string;
65
120
  }): Promise<PostmanSpec>;
121
+ /** Writes new content to a file of an existing spec. */
66
122
  upsertSpecFile(input: {
67
123
  specId: string;
68
124
  filePath: string;
69
125
  content: string;
70
126
  }): Promise<void>;
71
127
  }
72
- //#endregion
73
- //#region src/verify-token.d.ts
74
- /**
75
- * `verifyToken` — plugin-level export used by `holocron auth set` +
76
- * `holocron auth check`. Hits Postman's `/me` endpoint (returns the
77
- * authenticated user).
78
- */
79
- interface VerifyTokenSuccess {
80
- ok: true;
81
- subject: string;
82
- }
83
- interface VerifyTokenFailure {
84
- ok: false;
85
- message: string;
86
- }
87
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
88
128
  interface VerifyTokenOptions {
89
129
  baseUrl?: string;
90
130
  fetch?: typeof fetch;
91
131
  }
92
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
93
- //#endregion
94
- //#region src/index.d.ts
95
- interface PostmanPluginOptions extends ResolveTokenInput, PostmanToolingOptions {
132
+ /** Checks a Postman API key by fetching the authenticated user; resolves to the user's email, username or name, or the failure message. */
133
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
134
+ /** Options for the Postman plugin: how the API key is resolved, the tooling settings, and test overrides. */
135
+ export interface PostmanPluginOptions extends ResolveTokenInput, PostmanToolingOptions {
96
136
  /** Working repo root. Used to resolve relative paths in specFile/envFiles. Defaults to process.cwd(). */
97
137
  repoRoot?: string;
98
138
  /** Override base URL for tests. */
@@ -100,22 +140,30 @@ interface PostmanPluginOptions extends ResolveTokenInput, PostmanToolingOptions
100
140
  /** Override `fetch` for tests. */
101
141
  fetch?: typeof fetch;
102
142
  }
103
- interface PluginContext {
143
+ /** The shared state the Postman plugin's capability and probes are built from. */
144
+ export interface PluginContext {
145
+ /** The options the plugin was created with. */
104
146
  options: PostmanPluginOptions;
147
+ /** Memoized client factory; the API key is resolved on first use. */
105
148
  client: () => PostmanClient;
106
149
  }
107
- declare function createContext(options: PostmanPluginOptions): PluginContext;
108
- declare function tooling(ctx: PluginContext): Tooling;
109
- declare function createPlugin(options: PostmanPluginOptions): {
150
+ /** Builds the plugin context from its options; throws when `workspaceId` is missing. */
151
+ export declare function createContext(options: PostmanPluginOptions): PluginContext;
152
+ /** Builds the `tooling` capability for a context, passing only the options that are set. */
153
+ export declare function tooling(ctx: PluginContext): Tooling;
154
+ /** Creates the Postman plugin: its `tooling` capability and its `connection` probe. */
155
+ export declare function createPlugin(options: PostmanPluginOptions): {
110
156
  name: string;
157
+ probes: {
158
+ connection: import("@theholocron/cli").Probe;
159
+ };
111
160
  capabilities: {
112
161
  tooling: () => Tooling;
113
162
  };
114
163
  };
115
164
  /**
116
- * One-line hint printed by `holocron auth set postman` when no
165
+ * One-line hint printed by `holocron new token postman` when no
117
166
  * token is supplied or the supplied token is rejected.
118
167
  */
119
- declare const AUTH_HINT: string;
120
- //#endregion
121
- export { AUTH_HINT, AuthError, PluginContext, type PostmanClient, type PostmanClientOptions, PostmanPlanLimitError, PostmanPluginOptions, PostmanTooling, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createContext, createPlugin, createPostmanClient, detectPlanLimit, resolveToken, tooling, verifyToken };
168
+ export declare const AUTH_HINT: string;
169
+ export { AuthError, type PostmanClient, type PostmanClientOptions, PostmanPlanLimitError, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createPostmanClient, detectPlanLimit };
package/dist/index.mjs CHANGED
@@ -1,60 +1,166 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
2
- import { readFile } from "node:fs/promises";
3
- import { basename, resolve } from "node:path";
1
+ import { AuthError, ProviderApiError, connectionProbe, createResolveToken } from "@theholocron/cli";
2
+ import { mkdir, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
3
+ import { basename, extname, join, relative, resolve } from "node:path";
4
+ import { errorMessage } from "@theholocron/misc-utils";
5
+ import { tmpdir } from "node:os";
6
+ import { spawnSync } from "node:child_process";
4
7
  import { PostmanPlanLimitError, createPostmanClient, detectPlanLimit } from "@theholocron/postman-client";
5
- //#region src/auth.ts
8
+ // src/auth.ts
9
+ /** Resolves the Postman API key from `--token`, `HOLOCRON_POSTMAN_TOKEN`, `POSTMAN_API_KEY` or the keyring, and throws an `AuthError` when none is set. */
6
10
  const resolveToken = createResolveToken({
7
- envName: "HOLOCRON_POSTMAN_API_KEY",
11
+ envName: "HOLOCRON_POSTMAN_TOKEN",
8
12
  vendorEnvName: "POSTMAN_API_KEY",
9
13
  keyringService: "postman",
10
- errorMessage: "no Postman API key found. Pass --token <KEY>, set HOLOCRON_POSTMAN_API_KEY / POSTMAN_API_KEY, or run: holocron auth set postman <KEY>"
14
+ errorMessage: "no Postman API key found. Pass --token <KEY>, set HOLOCRON_POSTMAN_TOKEN / POSTMAN_API_KEY, or run: holocron new token postman <KEY>"
11
15
  });
12
- //#endregion
13
- //#region src/capabilities/tooling.ts
16
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`. */
17
+ const tokens = [resolveToken.token];
18
+ // src/export-collections.ts
14
19
  /**
15
- * `tooling` capability for Postman.
16
- *
17
- * Ported from rando-id/rando.id `adapters/postman.ts`. The holocron
18
- * `Tooling` interface stays narrow (`sync` + `doctor`); the
19
- * Postman-specific surface (workspaces, collections, environments,
20
- * Spec Hub) lives as additional methods on this class for callers
21
- * that need direct access.
20
+ * The folder each collection is written to, in order: its own file name without the extension (`collection.json`
21
+ * is `collection`). Two files with the same name would write into one folder, so those use the whole path instead,
22
+ * its folders joined with `-` (`apps-a-collection`).
23
+ */
24
+ function exportDirNames(files) {
25
+ const stem = (file) => basename(file, extname(file));
26
+ const counts = /* @__PURE__ */ new Map();
27
+ for (const file of files) counts.set(stem(file), (counts.get(stem(file)) ?? 0) + 1);
28
+ return files.map((file) => {
29
+ if (counts.get(stem(file)) === 1) return stem(file);
30
+ return file.slice(0, file.length - extname(file).length).split("/").filter(Boolean).join("-");
31
+ });
32
+ }
33
+ /** Every file below `dir`, relative to it and sorted; a folder that is not there holds none. */
34
+ async function listFiles(dir) {
35
+ return (await readdir(dir, {
36
+ recursive: true,
37
+ withFileTypes: true
38
+ }).catch(() => [])).filter((entry) => entry.isFile()).map((entry) => relative(dir, join(entry.parentPath, entry.name))).sort();
39
+ }
40
+ /**
41
+ * Writes each collection in Postman's schema 3.0 YAML layout by running `postman collection migrate` on it, one folder
42
+ * per collection under `outDir`. The CLI only migrates collections, so an environment file is reported as an issue and
43
+ * not exported. On a dry run the CLI writes into a temporary folder, which is listed and then removed, so `outDir` is
44
+ * never touched. A collection the CLI cannot migrate throws, naming the file.
45
+ */
46
+ async function exportCollections(input, cli) {
47
+ const { collectionFiles, envFiles, outDir, repoRoot } = input;
48
+ const names = exportDirNames(collectionFiles);
49
+ const base = input.dryRun ? await mkdtemp(join(tmpdir(), "holocron-export-")) : outDir;
50
+ const files = [];
51
+ const issues = [];
52
+ try {
53
+ if (!input.dryRun) await mkdir(outDir, { recursive: true });
54
+ for (const [index, file] of collectionFiles.entries()) {
55
+ const name = names[index];
56
+ cli.migrate(resolve(repoRoot, file), join(base, name));
57
+ const written = await listFiles(join(base, name));
58
+ if (written.length === 0) issues.push({
59
+ file,
60
+ message: "`postman collection migrate` wrote no files"
61
+ });
62
+ files.push(...written.map((path) => join(name, path)));
63
+ }
64
+ } finally {
65
+ if (input.dryRun) await rm(base, {
66
+ recursive: true,
67
+ force: true
68
+ });
69
+ }
70
+ for (const file of envFiles) issues.push({
71
+ file,
72
+ message: "not exported: `postman collection migrate` converts collections only, so there is no 3.0 environment"
73
+ });
74
+ return {
75
+ files,
76
+ issues
77
+ };
78
+ }
79
+ // src/shell.ts
80
+ /**
81
+ * Thin wrapper around `spawnSync` for the Postman CLI (`postman`), the CLI-transport counterpart of `rest.ts`.
22
82
  *
23
- * `sync()` flow:
24
- * 1. Read the local OpenAPI spec from `options.specFile`
25
- * 2. Find or create the Spec Hub spec by name in the workspace;
26
- * upsert the spec file content
27
- * 3. Find any existing collection with the same name and delete it
28
- * (Postman's import-from-OpenAPI path is create-only — no stable
29
- * update path for collections produced from a spec)
30
- * 4. Import the spec as a fresh collection
31
- * 5. For each `envFiles[i]`, find-or-create the environment
83
+ * The only thing it runs is `postman collection migrate <file> --output <dir>`, which writes a collection in
84
+ * Postman's schema 3.0 YAML layout. The stdio shape is the usual one for a vendor CLI, `['inherit', 'pipe', 'pipe']`:
85
+ * stdin stays attached so a CLI that wants a terminal can ask for one, and the output is read here.
32
86
  *
33
- * `doctor()` probes `/me` for auth + `/workspaces` for workspace
34
- * reachability and returns a `ToolingDoctorReport`.
87
+ * Not verified against the real CLI: it was not installed where this was written, so the arguments and the layout it
88
+ * writes follow Postman's documentation and are exercised only through an injected `spawn`.
35
89
  */
90
+ /** Where to install the CLI, said when it is missing. */
91
+ const INSTALL_HINT = "install it from https://learning.postman.com/docs/postman-cli/postman-cli-installation/ (macOS: brew install --cask postman-cli)";
92
+ /** The Postman CLI, run as a child process. */
93
+ var PostmanCli = class {
94
+ spawnImpl;
95
+ /** The binary this wrapper runs; defaults to `"postman"`. */
96
+ binary;
97
+ constructor(opts = {}) {
98
+ this.spawnImpl = opts.spawn ?? spawnSync;
99
+ this.binary = opts.binary ?? "postman";
100
+ }
101
+ /**
102
+ * Runs `postman collection migrate <file> --output <outDir>` and throws when it cannot: the CLI is not installed,
103
+ * or it exits non-zero (its own message, trimmed, is the error).
104
+ */
105
+ migrate(file, outDir) {
106
+ const out = this.spawnImpl(this.binary, [
107
+ "collection",
108
+ "migrate",
109
+ file,
110
+ "--output",
111
+ outDir
112
+ ], {
113
+ encoding: "utf-8",
114
+ stdio: [
115
+ "inherit",
116
+ "pipe",
117
+ "pipe"
118
+ ]
119
+ });
120
+ if (out.error) {
121
+ const missing = out.error.code === "ENOENT";
122
+ throw new Error(missing ? `the Postman CLI (\`${this.binary}\`) is not installed: ${INSTALL_HINT}` : `could not run \`${this.binary}\`: ${out.error.message}`, { cause: out.error });
123
+ }
124
+ if (out.status !== 0) {
125
+ const said = `${out.stderr ?? ""}`.trim() || `${out.stdout ?? ""}`.trim() || `exit status ${out.status}`;
126
+ throw new Error(`\`${this.binary} collection migrate\` failed for ${file}: ${said}`);
127
+ }
128
+ }
129
+ };
130
+ // src/capabilities/tooling.ts
131
+ /** The Postman implementation of the `tooling` capability: syncs an OpenAPI spec, collection and environments into a workspace. */
36
132
  var PostmanTooling = class {
37
133
  client;
134
+ /** The capability this class provides, always `"tooling"`. */
38
135
  key = "tooling";
136
+ /** The provider name, `"postman"`. */
39
137
  providerName = "postman";
40
138
  opts;
41
139
  repoRoot;
140
+ workspaceIdPromise;
42
141
  constructor(client, opts) {
43
142
  this.client = client;
44
- if (!opts.workspaceId) throw new Error("PostmanTooling requires `workspaceId` in options");
143
+ if (!opts.workspaceId && !opts.workspace) throw new Error("PostmanTooling requires `workspaceId` or `workspace` in options");
45
144
  this.opts = opts;
46
145
  this.repoRoot = opts.repoRoot ?? process.cwd();
47
146
  }
48
147
  async sync() {
49
- if (!this.opts.specFile) throw new Error("PostmanTooling.sync() requires `specFile` in options (local OpenAPI JSON path)");
50
- const specPath = resolve(this.repoRoot, this.opts.specFile);
148
+ const { specFile, collectionFiles = [], envFiles = [] } = this.opts;
149
+ if (!specFile && collectionFiles.length === 0 && envFiles.length === 0) throw new Error("PostmanTooling.sync() requires `specFile` (local OpenAPI JSON path), `collectionFiles` or `envFiles` in options");
150
+ const workspaceId = await this.resolveWorkspaceId();
151
+ if (specFile) await this.syncSpec(workspaceId, specFile);
152
+ for (const file of collectionFiles) await this.syncCollectionFile(workspaceId, file);
153
+ for (const file of envFiles) await this.syncEnvironmentFile(workspaceId, file);
154
+ }
155
+ async syncSpec(workspaceId, specFile) {
156
+ const specPath = resolve(this.repoRoot, specFile);
51
157
  const specText = await readFile(specPath, "utf8");
52
158
  const specObj = JSON.parse(specText);
53
159
  const inferredName = specObj.info?.title ?? basename(specPath);
54
160
  const specName = this.opts.specName ?? inferredName;
55
161
  const collectionName = this.opts.collectionName ?? specName;
56
162
  const existingSpec = await this.findSpecByName({
57
- workspaceId: this.opts.workspaceId,
163
+ workspaceId,
58
164
  name: specName
59
165
  });
60
166
  if (existingSpec) await this.upsertSpecFile({
@@ -63,44 +169,99 @@ var PostmanTooling = class {
63
169
  content: specText
64
170
  });
65
171
  else await this.createSpec({
66
- workspaceId: this.opts.workspaceId,
172
+ workspaceId,
67
173
  name: specName,
68
174
  fileContent: specText
69
175
  });
70
176
  const existingCollection = await this.findCollectionByName({
71
- workspaceId: this.opts.workspaceId,
177
+ workspaceId,
72
178
  name: collectionName
73
179
  });
74
180
  if (existingCollection) await this.deleteCollection(existingCollection.uid);
75
181
  await this.importOpenApi({
76
- workspaceId: this.opts.workspaceId,
182
+ workspaceId,
77
183
  spec: specObj
78
184
  });
79
- for (const file of this.opts.envFiles ?? []) {
80
- const envText = await readFile(resolve(this.repoRoot, file), "utf8");
81
- const envObj = JSON.parse(envText);
82
- if (!envObj.name) throw new Error(`Postman environment file ${file} is missing a "name" field`);
83
- const existing = await this.findEnvironmentByName({
84
- workspaceId: this.opts.workspaceId,
85
- name: envObj.name
86
- });
87
- if (existing) await this.updateEnvironment({
88
- uid: existing.uid,
89
- environment: envObj
90
- });
91
- else await this.createEnvironment({
92
- workspaceId: this.opts.workspaceId,
185
+ }
186
+ async syncCollectionFile(workspaceId, file) {
187
+ const collection = JSON.parse(await readFile(resolve(this.repoRoot, file), "utf8"));
188
+ const name = collection.info?.name;
189
+ if (!name) throw new Error(`Postman collection file ${file} is missing \`info.name\``);
190
+ const existing = await this.findCollectionByName({
191
+ workspaceId,
192
+ name
193
+ });
194
+ if (existing) await this.updateCollection({
195
+ uid: existing.uid,
196
+ collection
197
+ });
198
+ else await this.createCollection({
199
+ workspaceId,
200
+ collection
201
+ });
202
+ }
203
+ async syncEnvironmentFile(workspaceId, file) {
204
+ const envText = await readFile(resolve(this.repoRoot, file), "utf8");
205
+ const envObj = JSON.parse(envText);
206
+ if (!envObj.name) throw new Error(`Postman environment file ${file} is missing a "name" field`);
207
+ const existing = await this.findEnvironmentByName({
208
+ workspaceId,
209
+ name: envObj.name
210
+ });
211
+ if (!existing) {
212
+ await this.createEnvironment({
213
+ workspaceId,
93
214
  environment: envObj
94
215
  });
216
+ return;
95
217
  }
218
+ const values = envObj.values ?? [];
219
+ const environment = values.some((v) => v.type === "secret" && !v.value) ? {
220
+ ...envObj,
221
+ values: keepSecrets(values, (await this.getEnvironment(existing.uid)).values ?? [])
222
+ } : envObj;
223
+ await this.updateEnvironment({
224
+ uid: existing.uid,
225
+ environment
226
+ });
96
227
  }
228
+ /** The workspace id: `workspaceId`, else the workspace named `workspace`, which is made when absent. Memoized. */
229
+ resolveWorkspaceId() {
230
+ const { workspaceId, workspace, workspaceType } = this.opts;
231
+ if (workspaceId) return Promise.resolve(workspaceId);
232
+ return this.workspaceIdPromise ??= (async () => {
233
+ const name = workspace;
234
+ const found = (await this.listWorkspaces()).find((w) => w.name === name);
235
+ if (found) return found.id;
236
+ const { workspace: made } = await this.client().workspaces.create({
237
+ name,
238
+ type: workspaceType ?? "personal"
239
+ });
240
+ return made.id;
241
+ })();
242
+ }
243
+ /**
244
+ * Writes each collection file in Postman's schema 3.0 YAML layout under `input.outDir` by running the Postman CLI
245
+ * (`postman collection migrate`), one folder per collection. Environment files are reported as issues, not exported.
246
+ * Needs the CLI on the PATH and no API key: it never touches the workspace.
247
+ */
248
+ async export(input) {
249
+ return exportCollections(input, new PostmanCli(this.opts.spawn ? { spawn: this.opts.spawn } : {}));
250
+ }
251
+ /** Checks the key and the configured workspace; reports the authenticated user and the workspace, or why either failed. */
97
252
  async doctor() {
98
253
  try {
99
254
  const me = await this.getMyself();
100
- const found = (await this.listWorkspaces()).find((w) => w.id === this.opts.workspaceId);
255
+ const workspaces = await this.listWorkspaces();
256
+ const wanted = this.opts.workspaceId ?? this.opts.workspace;
257
+ const found = workspaces.find((w) => this.opts.workspaceId ? w.id === wanted : w.name === wanted);
258
+ if (!found && !this.opts.workspaceId) return {
259
+ ok: true,
260
+ message: `authed as ${me.username}; workspace ${wanted} does not exist yet, \`sync\` makes it`
261
+ };
101
262
  if (!found) return {
102
263
  ok: false,
103
- message: `authed as ${me.username}, but workspace ${this.opts.workspaceId} not visible`
264
+ message: `authed as ${me.username}, but workspace ${wanted} not visible`
104
265
  };
105
266
  return {
106
267
  ok: true,
@@ -109,49 +270,75 @@ var PostmanTooling = class {
109
270
  } catch (err) {
110
271
  return {
111
272
  ok: false,
112
- message: err instanceof Error ? err.message : String(err)
273
+ message: errorMessage(err)
113
274
  };
114
275
  }
115
276
  }
277
+ /** Returns the authenticated Postman user. */
116
278
  async getMyself() {
117
279
  return (await this.client().me.get()).user ?? {};
118
280
  }
281
+ /** Lists the workspaces the key can see. */
119
282
  async listWorkspaces() {
120
283
  const { workspaces } = await this.client().workspaces.list();
121
284
  return workspaces;
122
285
  }
286
+ /** Finds a collection in the workspace by exact name, or `null` when there is none. */
123
287
  async findCollectionByName(input) {
124
288
  const { collections } = await this.client().collections.list(input.workspaceId);
125
289
  return collections.find((c) => c.name === input.name) ?? null;
126
290
  }
291
+ /** Creates a collection in the workspace from a Postman collection document. */
292
+ async createCollection(input) {
293
+ const { collection } = await this.client().collections.create(input.workspaceId, input.collection);
294
+ return collection;
295
+ }
296
+ /** Replaces the collection with this uid. */
297
+ async updateCollection(input) {
298
+ const { collection } = await this.client().collections.update(input.uid, input.collection);
299
+ return collection;
300
+ }
301
+ /** Deletes the collection with this uid. */
127
302
  async deleteCollection(uid) {
128
303
  await this.client().collections.delete(uid);
129
304
  }
305
+ /** Imports an OpenAPI document into the workspace as a collection; throws when Postman returns none. */
130
306
  async importOpenApi(input) {
131
307
  const { collections } = await this.client().import.openapi(input.workspaceId, input.spec);
132
308
  const created = collections[0];
133
309
  if (!created) throw new ProviderApiError("Postman returned no collection on import — check the OpenAPI spec is well-formed", 500, void 0);
134
310
  return created;
135
311
  }
312
+ /** Lists the workspace's environments. */
136
313
  async listEnvironments(input) {
137
314
  const { environments } = await this.client().environments.list(input.workspaceId);
138
315
  return environments;
139
316
  }
317
+ /** Finds an environment in the workspace by exact name, or `null` when there is none. */
140
318
  async findEnvironmentByName(input) {
141
319
  return (await this.listEnvironments(input)).find((e) => e.name === input.name) ?? null;
142
320
  }
321
+ /** Reads one environment with its variables. */
322
+ async getEnvironment(uid) {
323
+ const { environment } = await this.client().environments.get(uid);
324
+ return environment;
325
+ }
326
+ /** Creates an environment in the workspace. */
143
327
  async createEnvironment(input) {
144
328
  const { environment } = await this.client().environments.create(input.workspaceId, input.environment);
145
329
  return environment;
146
330
  }
331
+ /** Replaces the environment with this uid. */
147
332
  async updateEnvironment(input) {
148
333
  const { environment } = await this.client().environments.update(input.uid, input.environment);
149
334
  return environment;
150
335
  }
336
+ /** Finds an API spec in the workspace by exact name, or `null` when there is none. */
151
337
  async findSpecByName(input) {
152
338
  const { specs } = await this.client().specs.list(input.workspaceId);
153
339
  return specs.find((s) => s.name === input.name) ?? null;
154
340
  }
341
+ /** Creates an API spec in the workspace from the given file content. */
155
342
  async createSpec(input) {
156
343
  return this.client().specs.create(input.workspaceId, {
157
344
  name: input.name,
@@ -160,17 +347,27 @@ var PostmanTooling = class {
160
347
  fileContent: input.fileContent
161
348
  });
162
349
  }
350
+ /** Writes new content to a file of an existing spec. */
163
351
  async upsertSpecFile(input) {
164
352
  await this.client().specs.updateFile(input.specId, input.filePath, input.content);
165
353
  }
166
354
  };
167
- //#endregion
168
- //#region src/verify-token.ts
169
355
  /**
170
- * `verifyToken` — plugin-level export used by `holocron auth set` +
171
- * `holocron auth check`. Hits Postman's `/me` endpoint (returns the
172
- * authenticated user).
356
+ * The file's variables, where a secret the file leaves empty takes the value the environment holds under the same
357
+ * key, so syncing never blanks a secret someone set in Postman.
173
358
  */
359
+ function keepSecrets(local, existing) {
360
+ return local.map((v) => {
361
+ if (v.type !== "secret" || v.value) return v;
362
+ const held = existing.find((e) => e.key === v.key);
363
+ return held?.value ? {
364
+ ...v,
365
+ value: held.value
366
+ } : v;
367
+ });
368
+ }
369
+ // src/verify-token.ts
370
+ /** Checks a Postman API key by fetching the authenticated user; resolves to the user's email, username or name, or the failure message. */
174
371
  async function verifyToken(token, opts = {}) {
175
372
  const client = createPostmanClient({
176
373
  token,
@@ -186,14 +383,14 @@ async function verifyToken(token, opts = {}) {
186
383
  } catch (err) {
187
384
  return {
188
385
  ok: false,
189
- message: err instanceof Error ? err.message : String(err)
386
+ message: errorMessage(err)
190
387
  };
191
388
  }
192
389
  }
193
- //#endregion
194
- //#region src/index.ts
390
+ // src/index.ts
391
+ /** Builds the plugin context from its options; throws when `workspaceId` is missing. */
195
392
  function createContext(options) {
196
- if (!options.workspaceId) throw new Error("@theholocron/holocron-plugin-postman requires `workspaceId` in options");
393
+ if (!options.workspaceId && !options.workspace) throw new Error("@theholocron/holocron-plugin-postman requires `workspaceId` or `workspace` in options");
197
394
  let client;
198
395
  return {
199
396
  options,
@@ -204,26 +401,42 @@ function createContext(options) {
204
401
  })
205
402
  };
206
403
  }
404
+ /** Builds the `tooling` capability for a context, passing only the options that are set. */
207
405
  function tooling(ctx) {
208
- const opts = { workspaceId: ctx.options.workspaceId };
406
+ const opts = {};
407
+ if (ctx.options.workspaceId !== void 0) opts.workspaceId = ctx.options.workspaceId;
408
+ if (ctx.options.workspace !== void 0) opts.workspace = ctx.options.workspace;
409
+ if (ctx.options.workspaceType !== void 0) opts.workspaceType = ctx.options.workspaceType;
410
+ if (ctx.options.collectionFiles !== void 0) opts.collectionFiles = ctx.options.collectionFiles;
209
411
  if (ctx.options.specFile !== void 0) opts.specFile = ctx.options.specFile;
210
412
  if (ctx.options.specName !== void 0) opts.specName = ctx.options.specName;
211
413
  if (ctx.options.collectionName !== void 0) opts.collectionName = ctx.options.collectionName;
212
414
  if (ctx.options.envFiles !== void 0) opts.envFiles = ctx.options.envFiles;
213
415
  if (ctx.options.repoRoot !== void 0) opts.repoRoot = ctx.options.repoRoot;
416
+ if (ctx.options.spawn !== void 0) opts.spawn = ctx.options.spawn;
214
417
  return new PostmanTooling(ctx.client, opts);
215
418
  }
419
+ /** Creates the Postman plugin: its `tooling` capability and its `connection` probe. */
216
420
  function createPlugin(options) {
217
421
  const ctx = createContext(options);
218
422
  return {
219
423
  name: "@theholocron/holocron-plugin-postman",
424
+ probes: { connection: connectionProbe({
425
+ provider: "Postman",
426
+ url: options.baseUrl ?? "https://api.getpostman.com",
427
+ fetch: options.fetch,
428
+ token: () => resolveToken(options),
429
+ verify: (token) => verifyToken(token, {
430
+ baseUrl: options.baseUrl,
431
+ fetch: options.fetch
432
+ })
433
+ }) },
220
434
  capabilities: { tooling: () => tooling(ctx) }
221
435
  };
222
436
  }
223
437
  /**
224
- * One-line hint printed by `holocron auth set postman` when no
438
+ * One-line hint printed by `holocron new token postman` when no
225
439
  * token is supplied or the supplied token is rejected.
226
440
  */
227
- const AUTH_HINT = "generate a Postman API key at https://postman.co/settings/me/api-keys, then run: holocron auth set postman <KEY>";
228
- //#endregion
229
- export { AUTH_HINT, AuthError, PostmanPlanLimitError, PostmanTooling, createContext, createPlugin, createPostmanClient, detectPlanLimit, resolveToken, tooling, verifyToken };
441
+ const AUTH_HINT = "generate a Postman API key at https://postman.co/settings/me/api-keys, then run: holocron new token postman <KEY>";
442
+ export { AUTH_HINT, AuthError, PostmanPlanLimitError, PostmanTooling, createContext, createPlugin, createPostmanClient, detectPlanLimit, resolveToken, tokens, tooling, verifyToken };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-postman",
3
- "version": "5.0.0-alpha.46",
3
+ "version": "5.0.0-alpha.460",
4
4
  "description": "Holocron plugin for Postman. Implements the tooling capability against Postman's REST API — workspace + collection + spec + environment sync.",
5
5
  "keywords": [
6
6
  "holocron",
@@ -8,12 +8,12 @@
8
8
  "postman",
9
9
  "tooling"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-postman#readme",
11
+ "homepage": "https://docs.theholocron.dev/holocron/plugins/postman/",
12
12
  "bugs": "https://github.com/theholocron/holocron/issues",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "git+https://github.com/theholocron/holocron.git",
16
- "directory": "packages/holocron-plugin-postman"
16
+ "directory": "plugins/holocron-plugin-postman"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -30,27 +30,29 @@
30
30
  "dist"
31
31
  ],
32
32
  "devDependencies": {
33
- "@theholocron/eslint-config": "^8.4.5",
34
- "@theholocron/http-client": "^1.25.0",
35
- "@theholocron/postman-client": "^1.25.0",
36
- "@theholocron/tsconfig": "^8.4.5",
37
- "@theholocron/tsdown-config": "^8.4.5",
38
- "@theholocron/vitest-config": "^8.4.5",
39
33
  "@types/node": "^26",
40
- "@vitest/coverage-v8": "^4.1.11",
41
- "@vitest/eslint-plugin": "^1.6.27",
42
- "eslint": "^10.8.1",
43
- "eslint-plugin-n": "^18.3.0",
44
- "globals": "^17.11.0",
45
- "tsdown": "^0.22.14",
46
- "tsx": "4.23.12",
34
+ "@vitest/coverage-v8": "^5.1.0",
35
+ "@vitest/eslint-plugin": "^1.6.28",
36
+ "eslint": "^10.14.0",
37
+ "eslint-plugin-n": "^18.5.0",
38
+ "globals": "^17.14.0",
39
+ "tsdown": "^0.23.7",
40
+ "tsx": "4.23.15",
47
41
  "typescript": "^5.9.3",
48
- "vitest": "^4.1.11",
49
- "@theholocron/cli": "5.0.0-alpha.46"
42
+ "vitest": "^5.1.0",
43
+ "@theholocron/cli": "5.0.0-alpha.460",
44
+ "@theholocron/postman-client": "^1.58.0-alpha.37",
45
+ "@theholocron/http-client": "^1.58.0-alpha.37",
46
+ "@theholocron/eslint-config": "^8.9.0-alpha.18",
47
+ "@theholocron/misc-utils": "^1.17.0-alpha.4",
48
+ "@theholocron/tsconfig": "^8.9.0-alpha.18",
49
+ "@theholocron/tsdown-config": "^8.9.0-alpha.18",
50
+ "@theholocron/vitest-config": "^8.9.0-alpha.18"
50
51
  },
51
52
  "peerDependencies": {
52
- "@theholocron/postman-client": "^1.25.0",
53
- "@theholocron/cli": "5.0.0-alpha.46"
53
+ "@theholocron/misc-utils": "^1.16.0",
54
+ "@theholocron/postman-client": "^1.43.1",
55
+ "@theholocron/cli": "5.0.0-alpha.460"
54
56
  },
55
57
  "peerDependenciesMeta": {
56
58
  "@theholocron/postman-client": {}
@@ -62,11 +64,11 @@
62
64
  "access": "public"
63
65
  },
64
66
  "scripts": {
65
- "delivery.build": "tsdown",
66
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
67
+ "build": "tsdown",
68
+ "lint:code": "eslint .",
69
+ "test:unit": "vitest run --coverage",
67
70
  "test:watch": "vitest",
68
- "validate": "tsx scripts/validate.mjs",
69
- "verification.typeSafety": "holocron run verification.typeSafety --",
70
- "verification.unitTests": "holocron run verification.unitTests --"
71
+ "typecheck": "tsc --noEmit",
72
+ "validate:plugin": "tsx scripts/validate.mjs"
71
73
  }
72
74
  }