@assemblyline/al-orc 0.0.0-stage → 0.1.1

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.
Files changed (66) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +5 -0
  4. package/README.md +98 -2
  5. package/bin/cli.js +5 -0
  6. package/package.json +59 -4
  7. package/src/cli/_helpers.js +67 -0
  8. package/src/cli/config/add.js +10 -0
  9. package/src/cli/config/current.js +20 -0
  10. package/src/cli/config/index.js +63 -0
  11. package/src/cli/config/list.js +22 -0
  12. package/src/cli/config/remove.js +6 -0
  13. package/src/cli/config/use.js +6 -0
  14. package/src/cli/config-store.js +127 -0
  15. package/src/cli/factory-sessions/index.js +35 -0
  16. package/src/cli/factory-sessions/list.js +93 -0
  17. package/src/cli/factory-sessions/show.js +83 -0
  18. package/src/cli/index.js +61 -0
  19. package/src/cli/lines/index.js +53 -0
  20. package/src/cli/lines/list.js +36 -0
  21. package/src/cli/lines/pull.js +46 -0
  22. package/src/cli/lines/push.js +82 -0
  23. package/src/cli/lines/show.js +36 -0
  24. package/src/cli/shared/edit-tags.js +43 -0
  25. package/src/cli/stations/archive.js +24 -0
  26. package/src/cli/stations/delete.js +8 -0
  27. package/src/cli/stations/edit.js +30 -0
  28. package/src/cli/stations/index.js +104 -0
  29. package/src/cli/stations/list.js +34 -0
  30. package/src/cli/stations/pull.js +73 -0
  31. package/src/cli/stations/push.js +212 -0
  32. package/src/cli/stations/run.js +87 -0
  33. package/src/cli/stations/show.js +74 -0
  34. package/src/cli/status.js +23 -0
  35. package/src/cli/supporting-docs/index.js +21 -0
  36. package/src/cli/supporting-docs/show.js +49 -0
  37. package/src/cli/tags/create.js +21 -0
  38. package/src/cli/tags/delete.js +8 -0
  39. package/src/cli/tags/edit.js +27 -0
  40. package/src/cli/tags/index.js +49 -0
  41. package/src/cli/tags/list.js +24 -0
  42. package/src/cli/utils/format.js +206 -0
  43. package/src/cli/utils/line-files.js +84 -0
  44. package/src/cli/utils/station-files.js +151 -0
  45. package/src/cli/utils/station-labels.js +48 -0
  46. package/src/cli/work-records/cancel.js +24 -0
  47. package/src/cli/work-records/edit.js +22 -0
  48. package/src/cli/work-records/index.js +59 -0
  49. package/src/cli/work-records/list.js +48 -0
  50. package/src/cli/work-records/show.js +103 -0
  51. package/src/http.js +255 -0
  52. package/src/index.js +104 -0
  53. package/src/resources/factory-sessions.js +86 -0
  54. package/src/resources/lines.js +57 -0
  55. package/src/resources/stations.js +90 -0
  56. package/src/resources/supporting-docs.js +37 -0
  57. package/src/resources/tags.js +68 -0
  58. package/src/resources/work-records.js +77 -0
  59. package/src/types/api/Line.types.js +22 -0
  60. package/src/types/api/Station.types.js +34 -0
  61. package/src/types/api/SupportingDoc.types.js +14 -0
  62. package/src/types/api/Tag.types.js +10 -0
  63. package/src/types/api/WorkRecord.types.js +27 -0
  64. package/src/types/general/Credentials.types.js +18 -0
  65. package/src/types/general/Transport.types.js +21 -0
  66. package/src/types/general/index.js +8 -0
package/src/http.js ADDED
@@ -0,0 +1,255 @@
1
+ // @ts-check
2
+ /**
3
+ * Orchestrator API transport.
4
+ *
5
+ * PURE: credentials come from the `credentials` argument only — this module
6
+ * never reads `process.env` or the CLI config file. Callers resolve creds their
7
+ * own way (the CLI from its config profiles, factories from their own env) and
8
+ * inject them.
9
+ *
10
+ * Base URL is origin-only (e.g. https://orchestrator.assemblyline.sh/); the
11
+ * /api/v1 prefix is carried in the paths passed by the resource layer.
12
+ */
13
+
14
+ /**
15
+ * @typedef {import('./types/general/index.js').Credentials} Credentials
16
+ * @typedef {import('./types/general/index.js').RequestOptions} RequestOptions
17
+ * @typedef {import('./types/general/index.js').Transport} Transport
18
+ */
19
+
20
+ /**
21
+ * Row ceiling for auto-paginated fetches (`apiGetAll` / `ctx.getAll`). Exported
22
+ * so the CLI can flag a truncated bulk result — `getAll` returns a plain array,
23
+ * so `rows.length >= MAX_ALL_ROWS` is the signal that the cap was hit.
24
+ */
25
+ export const MAX_ALL_ROWS = 15000;
26
+
27
+ export class ApiError extends Error {
28
+ /**
29
+ * @param {string} message
30
+ * @param {{ code?: string, status?: number }} [opts]
31
+ */
32
+ constructor(message, { code, status } = {}) {
33
+ super(message);
34
+ this.name = 'ApiError';
35
+ this.code = code;
36
+ this.status = status;
37
+ }
38
+ }
39
+
40
+ /** Origin the client talks to when the caller doesn't supply `api_url`. */
41
+ export const DEFAULT_API_URL = 'https://orchestrator.assemblyline.sh';
42
+
43
+ /**
44
+ * Resolve credentials from the explicit argument only — this module never reads
45
+ * `process.env`. Callers
46
+ * pass `{ api_key, api_secret }` (required) and optionally `api_url` (defaults to
47
+ * the hosted origin) and `location` (sent as `X-Location`).
48
+ * @param {Credentials} credentials
49
+ * @returns {{ api_url: string, api_key: string, api_secret: string, location?: string }}
50
+ */
51
+ function resolveCreds(credentials) {
52
+ const api_url = credentials?.api_url ?? DEFAULT_API_URL;
53
+ const api_key = credentials?.api_key;
54
+ const api_secret = credentials?.api_secret;
55
+ if (!api_key || !api_secret) {
56
+ throw new ApiError(
57
+ 'Missing orchestrator credentials: pass { api_key, api_secret } to alOrc() ' +
58
+ `(api_url optional, defaults to ${DEFAULT_API_URL}).`,
59
+ { code: 'NO_CREDENTIALS' },
60
+ );
61
+ }
62
+ return { api_url, api_key, api_secret, location: credentials?.location };
63
+ }
64
+
65
+ /** @param {{ api_key: string, api_secret: string, location?: string }} creds */
66
+ function authHeaders(creds) {
67
+ /** @type {Record<string, string>} */
68
+ const headers = {
69
+ 'api-key': creds.api_key,
70
+ 'api-secret': creds.api_secret,
71
+ accept: 'application/json',
72
+ };
73
+ if (creds.location) headers['X-Location'] = creds.location;
74
+ return headers;
75
+ }
76
+
77
+ function buildUrl(baseUrl, path, searchParams) {
78
+ const base = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
79
+ const url = new URL(path.replace(/^\//, ''), base);
80
+ if (searchParams) {
81
+ for (const [key, value] of Object.entries(searchParams)) {
82
+ if (value !== undefined && value !== null && value !== '') {
83
+ url.searchParams.set(key, String(value));
84
+ }
85
+ }
86
+ }
87
+ return url;
88
+ }
89
+
90
+ /**
91
+ * @param {string} method
92
+ * @param {string} path
93
+ * @param {any} [body]
94
+ * @param {RequestOptions} [options]
95
+ */
96
+ async function apiRequest(method, path, body, { credentials, searchParams } = {}) {
97
+ const creds = resolveCreds(credentials);
98
+ const url = buildUrl(creds.api_url, path, searchParams);
99
+
100
+ const headers = authHeaders(creds);
101
+ const init = { method, headers };
102
+ if (body !== undefined) {
103
+ headers['content-type'] = 'application/json';
104
+ init.body = JSON.stringify(body);
105
+ }
106
+
107
+ const response = await fetch(url, init);
108
+ const text = await response.text();
109
+
110
+ let respBody = null;
111
+ if (text) {
112
+ try {
113
+ respBody = JSON.parse(text);
114
+ } catch {
115
+ // Non-JSON body. On error responses surface the raw text; on success it's a protocol violation.
116
+ if (!response.ok) {
117
+ throw new ApiError(`${response.status} ${response.statusText}: ${text.slice(0, 200)}`, {
118
+ code: 'HTTP_ERROR',
119
+ status: response.status,
120
+ });
121
+ }
122
+ throw new ApiError(
123
+ `Invalid JSON response (status ${response.status}): ${text.slice(0, 200)}`,
124
+ { code: 'INVALID_RESPONSE', status: response.status },
125
+ );
126
+ }
127
+ }
128
+
129
+ if (!response.ok) {
130
+ const code = respBody?.error?.code || 'HTTP_ERROR';
131
+ const message = respBody?.error?.message || respBody?.message || `${response.status} ${response.statusText}`;
132
+ throw new ApiError(message, { code, status: response.status });
133
+ }
134
+
135
+ return respBody;
136
+ }
137
+
138
+ export function apiGet(path, options) {
139
+ return apiRequest('GET', path, undefined, options);
140
+ }
141
+
142
+ export function apiPost(path, body, options) {
143
+ return apiRequest('POST', path, body ?? {}, options);
144
+ }
145
+
146
+ export function apiPut(path, body, options) {
147
+ return apiRequest('PUT', path, body ?? {}, options);
148
+ }
149
+
150
+ export function apiPatch(path, body, options) {
151
+ return apiRequest('PATCH', path, body ?? {}, options);
152
+ }
153
+
154
+ export function apiDelete(path, options) {
155
+ return apiRequest('DELETE', path, undefined, options);
156
+ }
157
+
158
+ /**
159
+ * Build the fully-resolved request URL (no credentials embedded). For commands
160
+ * that show or hand off the URL the CLI would hit.
161
+ * @param {string} path
162
+ * @param {RequestOptions} [options]
163
+ */
164
+ export function buildAuthedUrl(path, { credentials, searchParams } = {}) {
165
+ const creds = resolveCreds(credentials);
166
+ return buildUrl(creds.api_url, path, searchParams);
167
+ }
168
+
169
+ /**
170
+ * GET a binary response with auth headers. Returns the raw Response + resolved
171
+ * URL so the caller can stream the body (e.g. supporting-doc downloads). Throws
172
+ * ApiError on non-2xx (parsing a JSON error envelope if present).
173
+ * @param {string} path
174
+ * @param {{ credentials?: Credentials }} [options]
175
+ * @returns {Promise<{ response: Response, url: URL }>}
176
+ */
177
+ export async function apiGetStream(path, { credentials } = {}) {
178
+ const creds = resolveCreds(credentials);
179
+ const url = buildUrl(creds.api_url, path);
180
+
181
+ const response = await fetch(url, { method: 'GET', headers: authHeaders(creds) });
182
+
183
+ if (!response.ok) {
184
+ const text = await response.text();
185
+ let respBody = null;
186
+ if (text) {
187
+ try { respBody = JSON.parse(text); } catch { /* non-JSON error body */ }
188
+ }
189
+ const code = respBody?.error?.code || 'HTTP_ERROR';
190
+ const message = respBody?.error?.message || respBody?.message || `${response.status} ${response.statusText}`;
191
+ throw new ApiError(message, { code, status: response.status });
192
+ }
193
+ return { response, url };
194
+ }
195
+
196
+ /**
197
+ * Auto-paginating GET. Walks `page_context.has_more`, concatenating each page's
198
+ * `data` array. Endpoints that return everything in one shot (no `has_more`)
199
+ * simply stop after the first page. Caps at `maxRows` and reports `truncated`.
200
+ *
201
+ * @returns {Promise<{ data: any[], page_context: object|null, truncated: boolean }>}
202
+ */
203
+ export async function apiGetAll(path, options = {}, { maxRows = MAX_ALL_ROWS, pageSize = 500 } = {}) {
204
+ const baseParams = { ...(options.searchParams ?? {}) };
205
+ delete baseParams.page;
206
+ delete baseParams.limit;
207
+
208
+ const all = [];
209
+ let page = 1;
210
+ let pageContext = null;
211
+ let truncated = false;
212
+
213
+ while (true) {
214
+ const result = await apiGet(path, {
215
+ ...options,
216
+ searchParams: { ...baseParams, page, limit: pageSize },
217
+ });
218
+ const rows = result?.data ?? [];
219
+ pageContext = result?.page_context ?? null;
220
+
221
+ if (all.length + rows.length > maxRows) {
222
+ all.push(...rows.slice(0, maxRows - all.length));
223
+ truncated = true;
224
+ break;
225
+ }
226
+ all.push(...rows);
227
+
228
+ if (!pageContext?.has_more) break;
229
+ page++;
230
+ }
231
+
232
+ return { data: all, page_context: pageContext, truncated };
233
+ }
234
+
235
+ /**
236
+ * Bind credentials once and return a transport whose methods no longer take a
237
+ * `credentials` argument. This is the seam the resource layer builds on: the
238
+ * `alOrc(credentials)` factory calls this, then hands the resulting `ctx` to
239
+ * each `buildX(ctx)` so action files stay credential-free and pure.
240
+ *
241
+ * @param {Credentials} [credentials]
242
+ * @returns {Transport}
243
+ */
244
+ export function createTransport(credentials) {
245
+ return {
246
+ get: (path, options) => apiGet(path, { ...options, credentials }),
247
+ post: (path, body, options) => apiPost(path, body, { ...options, credentials }),
248
+ put: (path, body, options) => apiPut(path, body, { ...options, credentials }),
249
+ patch: (path, body, options) => apiPatch(path, body, { ...options, credentials }),
250
+ delete: (path, options) => apiDelete(path, { ...options, credentials }),
251
+ getAll: (path, options, pageOpts) => apiGetAll(path, { ...options, credentials }, pageOpts),
252
+ getStream: (path) => apiGetStream(path, { credentials }),
253
+ buildUrl: (path, options) => buildAuthedUrl(path, { ...options, credentials }),
254
+ };
255
+ }
package/src/index.js ADDED
@@ -0,0 +1,104 @@
1
+ // @ts-check
2
+ /**
3
+ * @assemblyline/al-orc — the importable orchestrator client.
4
+ *
5
+ * Construct a client with credentials bound once, then call resource namespaces:
6
+ *
7
+ * import { alOrc } from '@assemblyline/al-orc';
8
+ * const orc = alOrc({ api_key, api_secret }); // api_url optional (defaults to the hosted origin)
9
+ * const { data } = await orc.stations.list();
10
+ * const lines = await orc.lines.getAll();
11
+ * const wr = await orc.stations.run(id, { overrides: { dry_run: true } });
12
+ *
13
+ * The `al-orc` CLI builds the same client and calls these same namespaces — so
14
+ * the CLI and the library can never drift: every endpoint is defined once, in
15
+ * src/resources/.
16
+ *
17
+ * Code serving several orgs constructs one client per org: `alOrc(orgACreds)`,
18
+ * `alOrc(orgBCreds)`.
19
+ */
20
+
21
+ import { createTransport, apiGet } from './http.js';
22
+ import { buildLines } from './resources/lines.js';
23
+ import { buildStations } from './resources/stations.js';
24
+ import { buildWorkRecords } from './resources/work-records.js';
25
+ import { buildTags } from './resources/tags.js';
26
+ import { buildSupportingDocs } from './resources/supporting-docs.js';
27
+ import { buildFactorySessions } from './resources/factory-sessions.js';
28
+
29
+ /**
30
+ * @typedef {import('./types/general/index.js').Credentials} Credentials
31
+ * @typedef {import('./resources/lines.js').LinesApi} LinesApi
32
+ * @typedef {import('./resources/stations.js').StationsApi} StationsApi
33
+ * @typedef {import('./resources/work-records.js').WorkRecordsApi} WorkRecordsApi
34
+ * @typedef {import('./resources/tags.js').TagsApi} TagsApi
35
+ * @typedef {import('./resources/supporting-docs.js').SupportingDocsApi} SupportingDocsApi
36
+ * @typedef {import('./resources/factory-sessions.js').FactorySessionsApi} FactorySessionsApi
37
+ */
38
+
39
+ /**
40
+ * Who the credentials belong to, from `GET /api/v1/me`.
41
+ * @typedef {Object} Me
42
+ * @property {{ id: string, name: string }} org
43
+ * @property {{ id: string, name: string, key: string }} api_key
44
+ */
45
+
46
+ /**
47
+ * The orchestrator client. Explicit (not inferred) so callers — CLI handlers and
48
+ * factories alike — get a checked, autocompleted surface.
49
+ * @typedef {Object} OrcClient
50
+ * @property {LinesApi} lines
51
+ * @property {StationsApi} stations
52
+ * @property {WorkRecordsApi} workRecords
53
+ * @property {TagsApi} tags
54
+ * @property {SupportingDocsApi} supportingDocs
55
+ * @property {FactorySessionsApi} factorySessions
56
+ * @property {() => Promise<Me|null>} me
57
+ * @property {() => Promise<{ connected: boolean, org?: Me['org'], api_key?: Me['api_key'], status?: number, error?: string }>} checkConnection
58
+ */
59
+
60
+ /**
61
+ * @param {Credentials} credentials Required: `{ api_key, api_secret }`. Optional
62
+ * `api_url` (origin-only) overrides the default hosted endpoint; optional
63
+ * `location` is sent as `X-Location`. The library never reads these from the
64
+ * environment — inject them explicitly.
65
+ * @returns {OrcClient}
66
+ */
67
+ export function alOrc(credentials) {
68
+ const ctx = createTransport(credentials);
69
+ return {
70
+ lines: buildLines(ctx),
71
+ stations: buildStations(ctx),
72
+ workRecords: buildWorkRecords(ctx),
73
+ tags: buildTags(ctx),
74
+ supportingDocs: buildSupportingDocs(ctx),
75
+ factorySessions: buildFactorySessions(ctx),
76
+ /** The org and API key these credentials belong to. */
77
+ me: () => ctx.get('/api/v1/me').then((r) => r?.data ?? null),
78
+ /** Check the credentials against the orchestrator; never throws and never claims work. */
79
+ checkConnection: async () => {
80
+ try {
81
+ const { data } = await apiGet('/api/v1/me', { credentials });
82
+ return { connected: true, org: data?.org, api_key: data?.api_key };
83
+ } catch (/** @type {any} */ error) {
84
+ return { connected: false, status: error?.status, error: error?.message };
85
+ }
86
+ },
87
+ };
88
+ }
89
+
90
+ // Transport primitives — an escape hatch for one-off calls the namespaces don't cover.
91
+ export {
92
+ ApiError,
93
+ apiGet,
94
+ apiPost,
95
+ apiPut,
96
+ apiPatch,
97
+ apiDelete,
98
+ apiGetAll,
99
+ apiGetStream,
100
+ buildAuthedUrl,
101
+ createTransport,
102
+ MAX_ALL_ROWS,
103
+ DEFAULT_API_URL,
104
+ } from './http.js';
@@ -0,0 +1,86 @@
1
+ // @ts-check
2
+ /**
3
+ * The `factory-sessions` resource — one row per factory session start.
4
+ *
5
+ * A session is the unit of factory debugging: `factory_name` is only
6
+ * `{location}/{hostname}` and repeats across restarts, so the session id is
7
+ * the sole stable handle on a particular running process.
8
+ *
9
+ * Return shapes follow the house convention: `list` returns the raw
10
+ * `{ data, page_context }` envelope, `getAll` a flat array, `get` the
11
+ * unwrapped record.
12
+ */
13
+
14
+ /**
15
+ * @typedef {import('../types/general/index.js').Transport} Transport
16
+ */
17
+
18
+ /**
19
+ * @typedef {Object} FactorySession
20
+ * @property {string} id
21
+ * @property {string} factory_name
22
+ * @property {string} location
23
+ * @property {'active'|'expired'|'disconnected'} status
24
+ * @property {string|null} hostname
25
+ * @property {number|null} pid
26
+ * @property {string|null} cwd
27
+ * @property {string|null} factory_version
28
+ * @property {string} started_at
29
+ * @property {string} last_seen_at
30
+ * @property {string|null} ended_at
31
+ * @property {number} tasks_completed
32
+ * @property {number} tasks_failed
33
+ */
34
+
35
+ /**
36
+ * @typedef {Object} SlugOutcome
37
+ * @property {string} step_slug
38
+ * @property {number} completed
39
+ * @property {number} failed
40
+ * @property {number} other
41
+ */
42
+
43
+ /**
44
+ * @typedef {FactorySession & {
45
+ * slug_breakdown: SlugOutcome[],
46
+ * recent_tasks: Array<{ id: string, work_record: string, step_slug: string, status: string,
47
+ * retry_count: number, error: string|null,
48
+ * claimed_at: string|null, completed_at: string|null }>
49
+ * }} FactorySessionDetail
50
+ */
51
+
52
+ /**
53
+ * The factory-sessions client surface. Explicit (not inferred) so callers get
54
+ * real checking; `buildFactorySessions`'s `@returns` binds it, so `tsc`
55
+ * verifies the impl.
56
+ * @typedef {Object} FactorySessionsApi
57
+ * @property {(params?: { status?: string, location?: string, factory_name?: string, limit?: number }) => Promise<{ data: FactorySession[], page_context: object|null }>} list
58
+ * @property {(params?: { status?: string, location?: string, factory_name?: string }) => Promise<FactorySession[]>} getAll
59
+ * @property {(id: string) => Promise<FactorySessionDetail|null>} get
60
+ */
61
+
62
+ /** Unwrap a single-record response body; null if there's no data.
63
+ * @param {any} r
64
+ * @returns {any} */
65
+ const unwrap = (r) => r?.data ?? null;
66
+
67
+ /** @param {string} s */
68
+ const enc = (s) => encodeURIComponent(s);
69
+
70
+ /**
71
+ * @param {Transport} ctx
72
+ * @returns {FactorySessionsApi}
73
+ */
74
+ export function buildFactorySessions(ctx) {
75
+ return {
76
+ /** One page of sessions, newest-seen first. Returns the `{ data, page_context }` envelope. */
77
+ list: (params = {}) => ctx.get('/api/v1/factory-sessions', { searchParams: params }),
78
+
79
+ /** Every session, walking pagination. Returns a flat array (capped at MAX_ALL_ROWS). */
80
+ getAll: async (params = {}) =>
81
+ (await ctx.getAll('/api/v1/factory-sessions', { searchParams: params })).data,
82
+
83
+ /** One session by id, with its per-slug outcome breakdown and recent tasks. Null if absent. */
84
+ get: (id) => ctx.get(`/api/v1/factory-sessions/${enc(id)}`).then(unwrap),
85
+ };
86
+ }
@@ -0,0 +1,57 @@
1
+ // @ts-check
2
+ /**
3
+ * The `lines` resource — every line endpoint, defined once.
4
+ *
5
+ * Lines live at the canonical `/api/v1/lines` surface (there was never a
6
+ * "process"-era path for them). `id` in every signature accepts a line id or
7
+ * its code — the orchestrator resolves either.
8
+ *
9
+ * Return shapes: single-record ops return the unwrapped record; `list` returns
10
+ * the raw `{ data, page_context }` envelope; `getAll` returns a flat array.
11
+ */
12
+
13
+ /**
14
+ * @typedef {import('../types/general/index.js').Transport} Transport
15
+ * @typedef {import('../types/api/Line.types.js').Line} Line
16
+ */
17
+
18
+ /**
19
+ * @typedef {Object} LinesApi
20
+ * @property {(params?: { location?: string, include_archived?: boolean }) => Promise<{ data: Line[], page_context: object|null }>} list
21
+ * @property {(params?: { location?: string, include_archived?: boolean }) => Promise<Line[]>} getAll
22
+ * @property {(id: string) => Promise<Line|null>} get
23
+ * @property {(data: object) => Promise<Line|null>} create
24
+ * @property {(id: string, data: object) => Promise<Line|null>} update
25
+ * @property {(id: string) => Promise<any>} delete
26
+ */
27
+
28
+ /** @param {any} r @returns {any} */
29
+ const unwrap = (r) => r?.data ?? null;
30
+ /** @param {string} s */
31
+ const enc = (s) => encodeURIComponent(s);
32
+
33
+ /**
34
+ * @param {Transport} ctx
35
+ * @returns {LinesApi}
36
+ */
37
+ export function buildLines(ctx) {
38
+ return {
39
+ /** One page of lines. Returns the `{ data, page_context }` envelope. */
40
+ list: (params = {}) => ctx.get('/api/v1/lines', { searchParams: params }),
41
+
42
+ /** Every line, walking pagination. Returns a flat array. */
43
+ getAll: async (params = {}) => (await ctx.getAll('/api/v1/lines', { searchParams: params })).data,
44
+
45
+ /** One line by id or code, or null if absent. */
46
+ get: (id) => ctx.get(`/api/v1/lines/${enc(id)}`).then(unwrap),
47
+
48
+ /** Create a line (`{ code, location, name?, description? }`). Returns the created record. */
49
+ create: (data) => ctx.post('/api/v1/lines', data).then(unwrap),
50
+
51
+ /** Update line fields (PUT). Returns the updated record. */
52
+ update: (id, data) => ctx.put(`/api/v1/lines/${enc(id)}`, data).then(unwrap),
53
+
54
+ /** Delete a line. Refused by the server while stations are still on it. */
55
+ delete: (id) => ctx.delete(`/api/v1/lines/${enc(id)}`).then(unwrap),
56
+ };
57
+ }
@@ -0,0 +1,90 @@
1
+ // @ts-check
2
+ /**
3
+ * The `stations` resource — every station endpoint, defined once.
4
+ *
5
+ * Every route lives under `/api/v1/stations/*`.
6
+ *
7
+ * Return shapes: single-record ops return the unwrapped record; `list` returns
8
+ * the raw `{ data, page_context }` envelope; `getAll` returns a flat array.
9
+ */
10
+
11
+ /**
12
+ * @typedef {import('../types/general/index.js').Transport} Transport
13
+ * @typedef {import('../types/api/Station.types.js').Station} Station
14
+ * @typedef {import('../types/api/Station.types.js').StationRunResult} StationRunResult
15
+ * @typedef {import('../types/api/Tag.types.js').Tag} Tag
16
+ */
17
+
18
+ /**
19
+ * The station client surface. Explicit (not inferred) so callers get real
20
+ * checking; `buildStations`'s `@returns` binds it, so `tsc` verifies the impl.
21
+ * @typedef {Object} StationsApi
22
+ * @property {(params?: { tag?: string, line?: string, include_archived?: boolean }) => Promise<{ data: Station[], page_context: object|null }>} list
23
+ * @property {(params?: { tag?: string, line?: string, include_archived?: boolean }) => Promise<Station[]>} getAll
24
+ * @property {(id: string) => Promise<Station|null>} get
25
+ * @property {(data: object) => Promise<Station|null>} create
26
+ * @property {(id: string, data: object) => Promise<Station|null>} update
27
+ * @property {(id: string, opts?: { cascade?: boolean }) => Promise<any>} delete
28
+ * @property {(id: string) => Promise<Station|null>} archive
29
+ * @property {(id: string) => Promise<Station|null>} unarchive
30
+ * @property {(id: string, opts?: { overrides?: Record<string, any> }) => Promise<StationRunResult|null>} run
31
+ * @property {(id: string) => Promise<Tag[]>} getTags
32
+ * @property {(id: string, tagIds: string[]) => Promise<any>} setTags
33
+ */
34
+
35
+ /** Unwrap a single-record response body; null if there's no data.
36
+ * @param {any} r
37
+ * @returns {any} */
38
+ const unwrap = (r) => r?.data ?? null;
39
+
40
+ /** @param {string} s */
41
+ const enc = (s) => encodeURIComponent(s);
42
+
43
+ /**
44
+ * @param {Transport} ctx
45
+ * @returns {StationsApi}
46
+ */
47
+ export function buildStations(ctx) {
48
+ return {
49
+ /** One page of stations. Returns the `{ data, page_context }` envelope. */
50
+ list: (params = {}) => ctx.get('/api/v1/stations', { searchParams: params }),
51
+
52
+ /** Every station, walking pagination. Returns a flat array (capped at MAX_ALL_ROWS). */
53
+ getAll: async (params = {}) => (await ctx.getAll('/api/v1/stations', { searchParams: params })).data,
54
+
55
+ /** One station by id, or null if absent. */
56
+ get: (id) => ctx.get(`/api/v1/stations/${enc(id)}`).then(unwrap),
57
+
58
+ /** Create a station (`data` uses API field names). Returns the created record. */
59
+ create: (data) => ctx.post('/api/v1/stations', data).then(unwrap),
60
+
61
+ /** Update station fields (PUT). Returns the updated record. */
62
+ update: (id, data) => ctx.put(`/api/v1/stations/${enc(id)}`, data).then(unwrap),
63
+
64
+ /** Delete a station. `cascade` also removes linked work records (server support pending). */
65
+ delete: (id, { cascade } = {}) =>
66
+ ctx.delete(`/api/v1/stations/${enc(id)}`, cascade ? { searchParams: { cascade: true } } : undefined).then(unwrap),
67
+
68
+ /** Archive — preserves history, hides from default list, blocks execution. Canonical /stations/* surface. */
69
+ archive: (id) => ctx.post(`/api/v1/stations/${enc(id)}/archive`).then(unwrap),
70
+
71
+ /** Unarchive — undoes archive. */
72
+ unarchive: (id) => ctx.post(`/api/v1/stations/${enc(id)}/unarchive`).then(unwrap),
73
+
74
+ /**
75
+ * Trigger a station run. `overrides` are shallow-merged into every step's
76
+ * config server-side. Returns `{ work_record_id }`.
77
+ */
78
+ run: (id, { overrides } = {}) => {
79
+ const body = {};
80
+ if (overrides && Object.keys(overrides).length > 0) body.step_overrides = overrides;
81
+ return ctx.post(`/api/v1/stations/${enc(id)}/run`, body).then(unwrap);
82
+ },
83
+
84
+ /** Current tags on a station. */
85
+ getTags: (id) => ctx.get(`/api/v1/stations/${enc(id)}/tags`).then((r) => r?.data ?? []),
86
+
87
+ /** Replace a station's tags (full set, by tag id). */
88
+ setTags: (id, tagIds) => ctx.put(`/api/v1/stations/${enc(id)}/tags`, { tags: tagIds }).then(unwrap),
89
+ };
90
+ }
@@ -0,0 +1,37 @@
1
+ // @ts-check
2
+ /**
3
+ * The `supporting-docs` resource — metadata fetch + a binary download stream.
4
+ *
5
+ * `downloadStream` stays pure (no filesystem): it returns the raw Response so
6
+ * the CLI handler writes the bytes. This keeps the client importable anywhere.
7
+ */
8
+
9
+ /**
10
+ * @typedef {import('../types/general/index.js').Transport} Transport
11
+ * @typedef {import('../types/api/SupportingDoc.types.js').SupportingDoc} SupportingDoc
12
+ */
13
+
14
+ /**
15
+ * @typedef {Object} SupportingDocsApi
16
+ * @property {(id: string) => Promise<SupportingDoc|null>} get
17
+ * @property {(id: string) => Promise<{ response: Response, url: URL }>} downloadStream
18
+ */
19
+
20
+ /** @param {any} r @returns {any} */
21
+ const unwrap = (r) => r?.data ?? null;
22
+ /** @param {string} s */
23
+ const enc = (s) => encodeURIComponent(s);
24
+
25
+ /**
26
+ * @param {Transport} ctx
27
+ * @returns {SupportingDocsApi}
28
+ */
29
+ export function buildSupportingDocs(ctx) {
30
+ return {
31
+ /** Document metadata (+ `content` for markdown docs). */
32
+ get: (id) => ctx.get(`/api/v1/supporting-docs/${enc(id)}`).then(unwrap),
33
+
34
+ /** Open the binary download as a stream; the caller writes it to disk. */
35
+ downloadStream: (id) => ctx.getStream(`/api/v1/supporting-docs/${enc(id)}/download`),
36
+ };
37
+ }