@assemblyline/al-orc 0.9.0 → 0.11.0

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.
@@ -1,6 +1,5 @@
1
1
  // @ts-check
2
2
  import { clientFor } from '../_helpers.js';
3
- import { buildStationLabelMap, stationLabel } from '../utils/station-labels.js';
4
3
  import { formatHeader, formatField, formatTable, formatSection, formatDate, formatDuration, localTzLabel, truncate } from '../utils/format.js';
5
4
 
6
5
  /** `al-orc stations show <id>` — one station's definition, optionally with recent work records. */
@@ -30,17 +29,14 @@ export async function showStationHandler(argv) {
30
29
  const tags = station.tags?.map((t) => (typeof t === 'string' ? t : t.name)).join(', ');
31
30
  if (tags) console.log(formatField('Tags', tags, lw));
32
31
 
33
- // `dependencies` comes back as bare station ids, so each needs resolving to a
34
- // short_code — printing them verbatim shows opaque ids where the reader
35
- // expects `EM0`. Best-effort: an unresolvable ref falls through unchanged.
36
- let deps = 'none';
37
- if (station.dependencies?.length) {
38
- const labels = await buildStationLabelMap(orc);
39
- deps = station.dependencies
40
- .map((d) => (typeof d === 'string' ? stationLabel(d, labels) : d.short_code || stationLabel(d.id, labels)))
41
- .join(', ');
42
- }
43
- console.log(formatField('Dependencies', deps, lw));
32
+ const from = station.conveyor?.from;
33
+ console.log(formatField('From', from ? [].concat(from).join(', ') : 'none', lw));
34
+ console.log(formatField('Enabled', station.is_enabled ? 'yes' : 'no', lw));
35
+ const schedule = station.schedule_cron
36
+ ? `${station.schedule_cron} (${station.schedule_timezone || 'UTC'}), ${station.schedule_enabled ? 'on' : 'off'}`
37
+ : 'none';
38
+ console.log(formatField('Schedule', schedule, lw));
39
+ console.log(formatField('Auto-drain', station.auto_drain_enabled ? 'on' : 'off', lw));
44
40
 
45
41
  console.log(formatSection('Config'));
46
42
  console.log(JSON.stringify(station.config ?? {}, null, 2));
@@ -23,10 +23,15 @@
23
23
  * @property {(data: object) => Promise<Line|null>} create
24
24
  * @property {(id: string, data: object) => Promise<Line|null>} update
25
25
  * @property {(id: string) => Promise<any>} delete
26
+ * @property {(id: string) => Promise<Line|null>} archive
27
+ * @property {(id: string) => Promise<Line|null>} unarchive
26
28
  */
27
29
 
28
30
  /** @param {any} r @returns {any} */
29
31
  const unwrap = (r) => r?.data ?? null;
32
+ /** Unwrap a write's response, keeping the restart warnings the orchestrator sent with it.
33
+ * @param {any} r @returns {any} */
34
+ const unwrapWithWarnings = (r) => (r?.data && r.warnings ? { ...r.data, warnings: r.warnings } : unwrap(r));
30
35
  /** @param {string} s */
31
36
  const enc = (s) => encodeURIComponent(s);
32
37
 
@@ -49,7 +54,13 @@ export function buildLines(ctx) {
49
54
  create: (data) => ctx.post('/api/v1/lines', data).then(unwrap),
50
55
 
51
56
  /** Update line fields (PUT). Returns the updated record. */
52
- update: (id, data) => ctx.put(`/api/v1/lines/${enc(id)}`, data).then(unwrap),
57
+ update: (id, data) => ctx.put(`/api/v1/lines/${enc(id)}`, data).then(unwrapWithWarnings),
58
+
59
+ /** Archive a line. Refused by the server while a station on it is not archived. */
60
+ archive: (id) => ctx.post(`/api/v1/lines/${enc(id)}/archive`).then(unwrapWithWarnings),
61
+
62
+ /** Unarchive a line. Its stations stay archived. */
63
+ unarchive: (id) => ctx.post(`/api/v1/lines/${enc(id)}/unarchive`).then(unwrapWithWarnings),
53
64
 
54
65
  /** Delete a line. Refused by the server while stations are still on it. */
55
66
  delete: (id) => ctx.delete(`/api/v1/lines/${enc(id)}`).then(unwrap),
@@ -4,7 +4,8 @@
4
4
  *
5
5
  * Every route lives under `/api/v1/stations/*`.
6
6
  *
7
- * Return shapes: single-record ops return the unwrapped record; `list` returns
7
+ * Return shapes: single-record ops return the unwrapped record (a write adds the orchestrator's
8
+ * restart `warnings` when there are any); `list` returns
8
9
  * the raw `{ data, page_context }` envelope; `getAll` returns a flat array.
9
10
  */
10
11
 
@@ -37,6 +38,11 @@
37
38
  * @returns {any} */
38
39
  const unwrap = (r) => r?.data ?? null;
39
40
 
41
+ /** Unwrap a write's response, keeping the restart warnings the orchestrator sent with it.
42
+ * @param {any} r
43
+ * @returns {any} */
44
+ const unwrapWithWarnings = (r) => (r?.data && r.warnings ? { ...r.data, warnings: r.warnings } : unwrap(r));
45
+
40
46
  /** @param {string} s */
41
47
  const enc = (s) => encodeURIComponent(s);
42
48
 
@@ -56,20 +62,20 @@ export function buildStations(ctx) {
56
62
  get: (id) => ctx.get(`/api/v1/stations/${enc(id)}`).then(unwrap),
57
63
 
58
64
  /** Create a station (`data` uses API field names). Returns the created record. */
59
- create: (data) => ctx.post('/api/v1/stations', data).then(unwrap),
65
+ create: (data) => ctx.post('/api/v1/stations', data).then(unwrapWithWarnings),
60
66
 
61
67
  /** Update station fields (PUT). Returns the updated record. */
62
- update: (id, data) => ctx.put(`/api/v1/stations/${enc(id)}`, data).then(unwrap),
68
+ update: (id, data) => ctx.put(`/api/v1/stations/${enc(id)}`, data).then(unwrapWithWarnings),
63
69
 
64
70
  /** Delete a station. Refused while it has work records, unless `cascade` (which deletes them too). */
65
71
  delete: (id, { cascade } = {}) =>
66
72
  ctx.delete(`/api/v1/stations/${enc(id)}`, cascade ? { searchParams: { cascade: true } } : undefined).then(unwrap),
67
73
 
68
74
  /** 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),
75
+ archive: (id) => ctx.post(`/api/v1/stations/${enc(id)}/archive`).then(unwrapWithWarnings),
70
76
 
71
77
  /** Unarchive — undoes archive. */
72
- unarchive: (id) => ctx.post(`/api/v1/stations/${enc(id)}/unarchive`).then(unwrap),
78
+ unarchive: (id) => ctx.post(`/api/v1/stations/${enc(id)}/unarchive`).then(unwrapWithWarnings),
73
79
 
74
80
  /**
75
81
  * Trigger a station run. `overrides` are shallow-merged into the station's config
@@ -11,6 +11,7 @@
11
11
  * @property {LineStationRef[]} [stations] Live stations on the line (read-only, server-derived).
12
12
  * @property {string} [created_at]
13
13
  * @property {string|null} [archived_at]
14
+ * @property {string[]} [warnings] Restart warnings returned by a write.
14
15
  */
15
16
 
16
17
  /**
@@ -9,7 +9,12 @@
9
9
  * @property {string} [description]
10
10
  * @property {Record<string, any>} [config] The station's config, passed to its handler.
11
11
  * @property {{ from: string | string[] } | null} [conveyor] Bins the factory session moves workpieces from into input/
12
- * @property {(string|{ id: string, short_code?: string })[]} [dependencies] Station ids or short_codes this one depends on (or station objects).
12
+ * @property {boolean} [is_enabled] Off: nothing runs, not even by hand.
13
+ * @property {string|null} [schedule_cron]
14
+ * @property {string|null} [schedule_timezone]
15
+ * @property {boolean} [schedule_enabled] Cron on or off.
16
+ * @property {boolean} [auto_drain_enabled] The factory session runs it whenever work is waiting.
17
+ * @property {string[]} [warnings] Restart warnings returned by a write.
13
18
  * @property {(string|Tag)[]} [tags]
14
19
  * @property {string} [applies_to]
15
20
  * @property {boolean} [archived]
@@ -1,47 +0,0 @@
1
- // @ts-check
2
- import { clientFor } from '../_helpers.js';
3
- import { saveLine, getLinesDir } from '../utils/line-files.js';
4
-
5
- /**
6
- * Write every line to `.orchestrator/lines/`. Shared with `stations pull --all`,
7
- * which pulls lines first so a factory repo never has station files whose line it
8
- * cannot resolve.
9
- * @returns {Promise<number>} lines written
10
- */
11
- export async function pullAllLines(orc) {
12
- const lines = await orc.lines.getAll({ include_archived: true });
13
- for (const line of lines) {
14
- console.log(`Saved: ${saveLine(line)}`);
15
- }
16
- return lines.length;
17
- }
18
-
19
- /** `al-orc lines pull` — write orchestrator line definitions to `.orchestrator/lines/`. */
20
- export async function pullLinesHandler(argv) {
21
- const { id, all } = argv;
22
-
23
- if (!id && !all) {
24
- console.error('Usage: al-orc lines pull <code|id>');
25
- console.error(' al-orc lines pull --all');
26
- console.error('');
27
- console.error('Run "al-orc lines list" to see available lines');
28
- process.exit(1);
29
- }
30
-
31
- const orc = clientFor();
32
- console.log(`Saving to: ${getLinesDir()}/`);
33
-
34
- if (id) {
35
- const line = await orc.lines.get(id);
36
- if (!line) {
37
- console.error(`Line not found: ${id}`);
38
- process.exit(1);
39
- }
40
- console.log(`Saved: ${saveLine(line)}`);
41
- return;
42
- }
43
-
44
- const count = await pullAllLines(orc);
45
- console.log('');
46
- console.log(`Total: ${count} lines pulled`);
47
- }
@@ -1,83 +0,0 @@
1
- // @ts-check
2
- import { clientFor } from '../_helpers.js';
3
- import { listAllLineFiles, loadLineByFilename, findLineFile, saveLine, getLinesDir } from '../utils/line-files.js';
4
-
5
- /**
6
- * Push one line file — create (no `id`) or update (has `id`). On create the
7
- * file is rewritten with the server-assigned id.
8
- */
9
- async function pushLineFile(orc, filepath) {
10
- const line = loadLineByFilename(filepath);
11
- if (!line) {
12
- console.error(`Line file not found: ${filepath}`);
13
- process.exit(1);
14
- }
15
- if (!line.code || !line.location) {
16
- throw new Error(`${filepath}: a line file needs at least "code" and "location"`);
17
- }
18
-
19
- const { id, stations, created_at, archived_at, ...data } = line;
20
-
21
- if (!id) {
22
- const created = await orc.lines.create(data);
23
- console.log(`Created: ${created.id} -> ${saveLine(created)}`);
24
- return { created: true };
25
- }
26
-
27
- const updated = await orc.lines.update(id, data);
28
- console.log(`Updated: ${updated.code} (${id})`);
29
- return { created: false };
30
- }
31
-
32
- /**
33
- * Push every local line file. Shared with `stations push --all`, which pushes
34
- * lines first so a new station's `line` code already exists server-side.
35
- * @returns {Promise<{ created: number, updated: number }>}
36
- */
37
- export async function pushAllLines(orc) {
38
- const totals = { created: 0, updated: 0 };
39
- for (const filepath of listAllLineFiles()) {
40
- const { created } = await pushLineFile(orc, filepath);
41
- if (created) totals.created++;
42
- else totals.updated++;
43
- }
44
- return totals;
45
- }
46
-
47
- /** `al-orc lines push` — create/update orchestrator lines from local files. */
48
- export async function pushLinesHandler(argv) {
49
- const { id, all } = argv;
50
-
51
- if (!id && !all) {
52
- console.error('Usage: al-orc lines push <filename|code|id>');
53
- console.error(' al-orc lines push --all');
54
- process.exit(1);
55
- }
56
-
57
- const orc = clientFor();
58
- console.log(`Reading from: ${getLinesDir()}/`);
59
-
60
- if (id) {
61
- const filepath = id.endsWith('.json') ? id : findLineFile(id);
62
- if (!filepath) {
63
- console.error(`line not found locally: ${id}`);
64
- console.error('Use a filename (e.g. VM.json) or a line code/ID');
65
- process.exit(1);
66
- }
67
- await pushLineFile(orc, filepath);
68
- return;
69
- }
70
-
71
- if (listAllLineFiles().length === 0) {
72
- console.log('No local lines found');
73
- console.log('Run "al-orc lines pull --all" first, or create a line file in .orchestrator/lines/');
74
- return;
75
- }
76
-
77
- const { created, updated } = await pushAllLines(orc);
78
- console.log('');
79
- const parts = [];
80
- if (updated > 0) parts.push(`${updated} updated`);
81
- if (created > 0) parts.push(`${created} created`);
82
- console.log(`Total: ${parts.join(', ')}`);
83
- }
@@ -1,74 +0,0 @@
1
- // @ts-check
2
- import { clientFor } from '../_helpers.js';
3
- import { saveStation, getStationsDir } from '../utils/station-files.js';
4
- import { pullAllLines } from '../lines/pull.js';
5
- import { getLinesDir } from '../utils/line-files.js';
6
-
7
- /**
8
- * Convert dependency IDs to short_codes using an id→short_code map.
9
- * Values without a match pass through unchanged.
10
- */
11
- function dependenciesToShortCodes(dependencies, id_to_short_code) {
12
- if (!dependencies?.length) return dependencies;
13
- return dependencies.map((dep) => id_to_short_code.get(dep) || dep);
14
- }
15
-
16
- /** Normalize a fetched station for local storage: tags → names, deps → short_codes. */
17
- function normalizeForLocal(station, id_to_short_code) {
18
- if (station.tags) station.tags = station.tags.map((t) => (typeof t === 'string' ? t : t.name));
19
- station.dependencies = dependenciesToShortCodes(station.dependencies, id_to_short_code);
20
- return station;
21
- }
22
-
23
- /** `al-orc stations pull` — write orchestrator station definitions to `.orchestrator/stations/`. */
24
- export async function pullStationsHandler(argv) {
25
- const { id, all } = argv;
26
-
27
- if (!id && !all) {
28
- console.error('Usage: al-orc stations pull <id|short_code>');
29
- console.error(' al-orc stations pull --all');
30
- console.error('');
31
- console.error('Run "al-orc stations list" to see available stations');
32
- process.exit(1);
33
- }
34
-
35
- const orc = clientFor();
36
-
37
- if (id) {
38
- console.log(`Saving to: ${getStationsDir()}/`);
39
- // Single station — also fetch the list for dependency resolution.
40
- const [station, all_stations] =await Promise.all([orc.stations.get(id), orc.stations.getAll()]);
41
- if (!station) {
42
- console.error(`Station not found: ${id}`);
43
- process.exit(1);
44
- }
45
- const id_to_short_code = new Map(all_stations.filter((s) => s.short_code).map((s) => [s.id, s.short_code]));
46
- const filepath = saveStation(normalizeForLocal(station, id_to_short_code));
47
- console.log(`Saved: ${filepath}`);
48
- return;
49
- }
50
-
51
- // All stations — lines first, so every station's `line` code resolves locally
52
- // (the factory session refuses to start on a station whose line file is missing).
53
- console.log(`Saving to: ${getLinesDir()}/`);
54
- const line_count = await pullAllLines(orc);
55
- console.log(`Total: ${line_count} lines pulled`);
56
- console.log('');
57
- console.log(`Saving to: ${getStationsDir()}/`);
58
-
59
- const stations = await orc.stations.getAll();
60
- if (stations.length === 0) {
61
- console.log('No stations found');
62
- return;
63
- }
64
- const id_to_short_code = new Map(stations.filter((s) => s.short_code).map((s) => [s.id, s.short_code]));
65
-
66
- for (const summary of stations) {
67
- // Fetch full details (the list may omit fields).
68
- const full = await orc.stations.get(summary.id);
69
- const filepath = saveStation(normalizeForLocal(full, id_to_short_code));
70
- console.log(`Saved: ${filepath}`);
71
- }
72
- console.log('');
73
- console.log(`Total: ${stations.length} stations pulled`);
74
- }
@@ -1,216 +0,0 @@
1
- // @ts-check
2
- import { clientFor } from '../_helpers.js';
3
- import {
4
- loadStation,
5
- listLocalStationIds,
6
- listAllStationFiles,
7
- loadStationByFilename,
8
- finalizeNewStationFile,
9
- findStationFile,
10
- getStationsDir,
11
- } from '../utils/station-files.js';
12
- import { pushAllLines } from '../lines/push.js';
13
- import { listAllLineFiles } from '../utils/line-files.js';
14
-
15
- /**
16
- * Build a short_code → ID map from remote stations (once per push session),
17
- * falling back to local files if the fetch fails. Cached on `cache`.
18
- */
19
- async function getShortCodeMap(orc, cache) {
20
- if (cache.map) return cache.map;
21
- cache.map = new Map();
22
- try {
23
- for (const s of await orc.stations.getAll()) {
24
- if (s.short_code) cache.map.set(s.short_code, s.id);
25
- }
26
- } catch {
27
- for (const id of listLocalStationIds()) {
28
- const station = loadStation(id);
29
- if (station?.short_code) cache.map.set(station.short_code, station.id);
30
- }
31
- }
32
- return cache.map;
33
- }
34
-
35
- /** Resolve short_codes in a dependencies array to database IDs (unknown values pass through). */
36
- async function resolveDependencies(orc, cache, dependencies) {
37
- if (!dependencies?.length) return dependencies;
38
- const map = await getShortCodeMap(orc, cache);
39
- const resolved = dependencies.map((dep) => map.get(dep) || dep);
40
- const changed = dependencies.filter((dep, i) => dep !== resolved[i]);
41
- if (changed.length > 0) {
42
- console.log(` Dependencies resolved: ${changed.map((dep) => `${dep} -> ${map.get(dep)}`).join(', ')}`);
43
- }
44
- return resolved;
45
- }
46
-
47
- /** Map tag names → ids, creating any that don't exist. Returns { ids, created }. */
48
- async function resolveTagNamesCreating(orc, names) {
49
- const { data = [] } = await orc.tags.list();
50
- const by_name = new Map(data.map((t) => [t.name, t.id]));
51
- const ids = [];
52
- const created = [];
53
- for (const name of names) {
54
- let id = by_name.get(name);
55
- if (!id) {
56
- const tag = await orc.tags.create({ name });
57
- id = tag.id;
58
- by_name.set(name, id);
59
- created.push(name);
60
- }
61
- ids.push(id);
62
- }
63
- return { ids, created };
64
- }
65
-
66
- /**
67
- * Sync tags after push. `undefined` = leave untouched; `[]` = clear all;
68
- * otherwise resolve (auto-creating missing) and replace.
69
- */
70
- async function syncTags(orc, station_id, tags) {
71
- if (tags === undefined) return;
72
- if (tags.length === 0) {
73
- await orc.stations.setTags(station_id, []);
74
- console.log(' Tags cleared');
75
- return;
76
- }
77
- const { ids, created } = await resolveTagNamesCreating(orc, tags);
78
- await orc.stations.setTags(station_id, ids);
79
- if (created.length > 0) console.log(` Auto-created tags: ${created.join(', ')}`);
80
- console.log(` Tags synced: ${tags.join(', ')}`);
81
- }
82
-
83
- /**
84
- * Push one station file — create (no `id`) or update (has `id`). With `force`, a
85
- * 404 on update falls back to create-with-same-id (promoting across environments).
86
- */
87
- async function pushByFilename(orc, cache, filename, { force = false } = {}) {
88
- const station = loadStationByFilename(filename);
89
- if (!station) {
90
- console.error(`Station file not found: ${filename}`);
91
- process.exit(1);
92
- }
93
-
94
- // `location` moved to the line (orchestrator D3); the API rejects it on a
95
- // station. Drop it here so an un-repulled file still pushes, and say so.
96
- if (station.location !== undefined) {
97
- console.log(` Ignoring "location" in ${filename} — location now lives on line "${station.line}" (.orchestrator/lines/)`);
98
- delete station.location;
99
- }
100
- if (!station.line) {
101
- throw new Error(`${filename}: station has no "line". Every station is on a line; add "line": "<CODE>" and push the line file first.`);
102
- }
103
-
104
- if (!station.id) {
105
- const { created_at, org, tags, ...create_data } = station;
106
- create_data.dependencies = await resolveDependencies(orc, cache, create_data.dependencies);
107
- create_data.conveyor = station.conveyor ?? null;
108
- const created = await orc.stations.create(create_data);
109
- const new_path = finalizeNewStationFile(filename, created);
110
- console.log(`Created: ${created.id} -> ${new_path}`);
111
- await syncTags(orc, created.id, tags);
112
- return;
113
- }
114
-
115
- const { id, created_at, org, tags, ...update_data } = station;
116
- update_data.dependencies = await resolveDependencies(orc, cache, update_data.dependencies);
117
- // The file is the truth: a file without a conveyor clears the station's.
118
- update_data.conveyor = station.conveyor ?? null;
119
-
120
- try {
121
- await orc.stations.update(id, update_data);
122
- console.log(`Updated: ${id}`);
123
- await syncTags(orc, id, tags);
124
- } catch (err) {
125
- if (err.status !== 404) throw err;
126
- if (!force) {
127
- const label = station.short_code ? `station "${station.short_code}" (id: ${id})` : `station with id "${id}"`;
128
- throw new Error(
129
- `${label} does not exist in the orchestrator. Re-run with --force to create it remotely with this id ` +
130
- `(use this when promoting a config from one environment to another).`,
131
- );
132
- }
133
- console.log(` Not visible to this org (${id}), creating with --force...`);
134
- let created;
135
- try {
136
- created = await orc.stations.create({ id, ...update_data });
137
- } catch (createErr) {
138
- if (createErr.status === 409) {
139
- const label = station.short_code ? `station "${station.short_code}"` : 'station';
140
- throw new Error(
141
- `Cannot create ${label} with id "${id}" — that id is already used by another org in the orchestrator ` +
142
- `(ids are globally unique across the multi-tenant database). Either change the id in the local file to a ` +
143
- `different alphanumeric (1-24 chars), or remove the "id" field entirely to let the orchestrator generate ` +
144
- `a fresh one — the file will be rewritten with the new id after push.`,
145
- );
146
- }
147
- throw createErr;
148
- }
149
- const new_path = finalizeNewStationFile(filename, created);
150
- console.log(`Created: ${created.id} -> ${new_path}`);
151
- await syncTags(orc, created.id, tags);
152
- }
153
- }
154
-
155
- /** `al-orc stations push` — create/update orchestrator stations from local files. */
156
- export async function pushStationsHandler(argv) {
157
- const { id, all, force } = argv;
158
-
159
- if (!id && !all) {
160
- console.error('Usage: al-orc stations push <filename> (create or update based on content)');
161
- console.error(' al-orc stations push <id|short_code> (update by station ID or short_code)');
162
- console.error(' al-orc stations push --all');
163
- console.error('');
164
- console.error('Run "al-orc stations list" to see available stations');
165
- process.exit(1);
166
- }
167
-
168
- const orc = clientFor();
169
- const cache = {};
170
- console.log(`Reading from: ${getStationsDir()}/`);
171
-
172
- if (id) {
173
- const filename = id.endsWith('.json') ? id : `${id}.json`;
174
- if (loadStationByFilename(filename)) {
175
- await pushByFilename(orc, cache, filename, { force });
176
- } else {
177
- const filepath = findStationFile(id);
178
- if (!filepath) {
179
- console.error(`station not found locally: ${id}`);
180
- console.error('Use a filename (e.g. AP1__document_intake.json) or a station ID/short_code');
181
- process.exit(1);
182
- }
183
- await pushByFilename(orc, cache, filepath, { force });
184
- }
185
- return;
186
- }
187
-
188
- // Lines first: a new station's `line` code must already exist server-side.
189
- if (listAllLineFiles().length > 0) {
190
- const { created, updated } = await pushAllLines(orc);
191
- console.log(`Lines: ${updated} updated, ${created} created`);
192
- console.log('');
193
- }
194
-
195
- const all_paths = listAllStationFiles();
196
- if (all_paths.length === 0) {
197
- console.log('No local stations found');
198
- console.log('Run "al-orc stations pull --all" first, or create a new station file');
199
- return;
200
- }
201
-
202
- let updated_count = 0;
203
- let created_count = 0;
204
- for (const filepath of all_paths) {
205
- const has_id =!!loadStationByFilename(filepath).id;
206
- await pushByFilename(orc, cache, filepath, { force });
207
- if (has_id)updated_count++;
208
- else created_count++;
209
- }
210
-
211
- console.log('');
212
- const parts = [];
213
- if (updated_count > 0) parts.push(`${updated_count} updated`);
214
- if (created_count > 0) parts.push(`${created_count} created`);
215
- console.log(`Total: ${parts.join(', ')}`);
216
- }
@@ -1,85 +0,0 @@
1
- // @ts-check
2
- /**
3
- * Local line file cache — `.orchestrator/lines/<CODE>.json`, one per line.
4
- *
5
- * A line file carries what the factory needs to route (`code`, `location`) and
6
- * what people need to recognise it (`name`, `description`). Station files
7
- * reference their line by `code`; `@assemblyline/lib-factory` joins the two to decide
8
- * which stations this factory session serves.
9
- */
10
-
11
- import fs from 'node:fs';
12
- import path from 'node:path';
13
-
14
- const LINES_DIR = '.orchestrator/lines';
15
-
16
- /** Fields worth persisting locally, in a stable order. */
17
- const LOCAL_FIELDS = ['id', 'code', 'name', 'description', 'location'];
18
-
19
- /** Path of the local lines directory (shown in pull/push output). */
20
- export function getLinesDir() {
21
- return LINES_DIR;
22
- }
23
-
24
- /** All line JSON file paths under `.orchestrator/lines/`. */
25
- export function listAllLineFiles() {
26
- if (!fs.existsSync(LINES_DIR)) return [];
27
- return fs
28
- .readdirSync(LINES_DIR)
29
- .filter((f) => f.endsWith('.json'))
30
- .map((f) => path.join(LINES_DIR, f));
31
- }
32
-
33
- /** Every local line, parsed. Malformed files are skipped. */
34
- export function listLocalLines() {
35
- const lines = [];
36
- for (const filepath of listAllLineFiles()) {
37
- try {
38
- lines.push({ filepath, data: JSON.parse(fs.readFileSync(filepath, 'utf8')) });
39
- } catch {
40
- // skip malformed files
41
- }
42
- }
43
- return lines;
44
- }
45
-
46
- /** Find a line file by code or id. */
47
- export function findLineFile(identifier) {
48
- const direct = path.join(LINES_DIR, `${identifier}.json`);
49
- if (fs.existsSync(direct)) return direct;
50
- for (const { filepath, data } of listLocalLines()) {
51
- if (data.id === identifier || data.code === identifier) return filepath;
52
- }
53
- return null;
54
- }
55
-
56
- /** Load a line file by code or id. */
57
- export function loadLine(identifier) {
58
- const filepath = findLineFile(identifier);
59
- return filepath ? JSON.parse(fs.readFileSync(filepath, 'utf8')) : null;
60
- }
61
-
62
- /** Load a line from a bare filename or a relative path. */
63
- export function loadLineByFilename(arg) {
64
- const filepath = arg.includes('/') || arg.includes(path.sep) ? arg : path.join(LINES_DIR, arg);
65
- return fs.existsSync(filepath) ? JSON.parse(fs.readFileSync(filepath, 'utf8')) : null;
66
- }
67
-
68
- /**
69
- * Save a line locally as `<code>.json`, removing any stale file for the same
70
- * line (a renamed code leaves its old filename behind otherwise).
71
- */
72
- export function saveLine(line) {
73
- if (!fs.existsSync(LINES_DIR)) fs.mkdirSync(LINES_DIR, { recursive: true });
74
-
75
- const stale = findLineFile(line.id);
76
- const filepath = path.join(LINES_DIR, `${line.code}.json`);
77
- if (stale && stale !== filepath) fs.unlinkSync(stale);
78
-
79
- const local = {};
80
- for (const field of LOCAL_FIELDS) {
81
- if (line[field] !== undefined) local[field] = line[field];
82
- }
83
- fs.writeFileSync(filepath, JSON.stringify(local, null, 2));
84
- return filepath;
85
- }