@xlinklight/publishing 3.3.0 → 3.3.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 (80) hide show
  1. package/README.md +1 -1
  2. package/dist/src/acceptance-delivery-binding.js +59 -0
  3. package/dist/src/acceptance.js +79 -0
  4. package/dist/src/client.js +146 -0
  5. package/dist/src/index.js +3 -0
  6. package/dist/src/node/acceptance-delivery.js +88 -0
  7. package/dist/src/node/activation.js +3 -0
  8. package/dist/src/node/authorization.js +76 -0
  9. package/dist/src/node/cli.js +20 -0
  10. package/dist/src/node/index.js +9 -0
  11. package/dist/src/node/journal.js +282 -0
  12. package/dist/src/node/publishing-command.js +220 -0
  13. package/dist/src/node/session.js +223 -0
  14. package/dist/src/node/solution-package.js +217 -0
  15. package/dist/src/node/source-error.js +15 -0
  16. package/dist/src/node/source-producer.js +145 -0
  17. package/dist/src/node/workflow.js +455 -0
  18. package/dist/src/package.js +74 -0
  19. package/dist/src/protocol.js +105 -0
  20. package/dist/src/shared/activation.js +111 -0
  21. package/dist/src/shared/records.js +26 -0
  22. package/dist/src/worker/activation.js +10 -0
  23. package/dist/src/worker/index.js +6 -0
  24. package/dist/src/worker/journal.js +301 -0
  25. package/dist/src/worker/package.js +116 -0
  26. package/dist/src/worker/release.js +59 -0
  27. package/dist/src/worker/runtime.js +98 -0
  28. package/dist/src/worker/service.js +494 -0
  29. package/package.json +17 -14
  30. package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -2
  31. package/{src/client.d.mts → types/client.d.ts} +1 -1
  32. package/{src/index.d.mts → types/index.d.ts} +6 -6
  33. package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
  34. package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
  35. package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
  36. package/types/node/index.d.ts +17 -0
  37. package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
  38. package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
  39. package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
  40. package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
  41. package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
  42. package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
  43. package/types/worker/index.d.ts +6 -0
  44. package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
  45. package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
  46. package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
  47. package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
  48. package/src/acceptance-delivery-binding.mjs +0 -49
  49. package/src/acceptance.mjs +0 -67
  50. package/src/client.mjs +0 -74
  51. package/src/index.mjs +0 -3
  52. package/src/node/acceptance-delivery.mjs +0 -70
  53. package/src/node/activation.mjs +0 -3
  54. package/src/node/authorization.mjs +0 -49
  55. package/src/node/cli.mjs +0 -12
  56. package/src/node/index.d.mts +0 -17
  57. package/src/node/index.mjs +0 -9
  58. package/src/node/journal.mjs +0 -135
  59. package/src/node/publishing-command.mjs +0 -104
  60. package/src/node/session.mjs +0 -134
  61. package/src/node/solution-package.mjs +0 -113
  62. package/src/node/source-error.mjs +0 -9
  63. package/src/node/source-producer.mjs +0 -103
  64. package/src/node/workflow.mjs +0 -320
  65. package/src/package.mjs +0 -36
  66. package/src/protocol.mjs +0 -50
  67. package/src/shared/activation.mjs +0 -64
  68. package/src/worker/activation.mjs +0 -4
  69. package/src/worker/index.d.mts +0 -6
  70. package/src/worker/index.mjs +0 -6
  71. package/src/worker/journal.mjs +0 -151
  72. package/src/worker/package.mjs +0 -32
  73. package/src/worker/release.mjs +0 -21
  74. package/src/worker/runtime.mjs +0 -23
  75. package/src/worker/service.mjs +0 -251
  76. /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
  77. /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
  78. /package/{src/package.d.mts → types/package.d.ts} +0 -0
  79. /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
  80. /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
@@ -0,0 +1,282 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID, createHash } from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { validatePortableRelativePath } from '@openge/forge-path-safety';
7
+ import { GeneratedArtifactError, generatedArtifactErrorCodes } from '@openge/forge-generated-artifacts';
8
+ import { publishingError, protocolRecord, publishingRequestId, publishingDigest } from '../protocol.js';
9
+ import { jsonSnapshot, operationRecord } from '../shared/records.js';
10
+ const fail = (code) => publishingError('JOURNAL_' + code);
11
+ const keyValid = (value) => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,191}$/.test(value);
12
+ const recordBytes = (key, revision, payload) => Buffer.byteLength('{"key":' + JSON.stringify(key) + ',"revision":' + revision + ',"payload":' + payload + '}');
13
+ const fileMissing = (error) => error instanceof Error && 'code' in error && error.code === 'ENOENT';
14
+ function storageFailure(error) {
15
+ if (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && error.code.startsWith('PUBLISHING_'))
16
+ throw error;
17
+ const code = error && typeof error === 'object' && 'errcode' in error ? error.errcode : undefined;
18
+ throw fail(code === 5 || code === 6 ? 'BUSY' : 'STORAGE_UNKNOWN');
19
+ }
20
+ function checkedLimits(value) {
21
+ if (!protocolRecord(value, ['maximumBytes', 'maximumRecords', 'maximumRecordBytes', 'maximumBlobs', 'maximumBlobBytes', 'minimumFreeBytes']) || !Object.values(value).every(Number.isSafeInteger) || value.maximumBytes < 65536 || value.maximumBytes > 1073741824 || value.maximumRecords < 1 || value.maximumRecords > 4096 || value.maximumRecordBytes < 1 || value.maximumRecordBytes > 1048576 || value.maximumBlobs < 1 || value.maximumBlobs > 32768 || value.maximumBlobBytes < 1 || value.maximumBlobBytes > 134217728 || value.minimumFreeBytes < 0)
22
+ throw fail('LIMIT_INVALID');
23
+ return { ...value };
24
+ }
25
+ const occupied = (error) => error instanceof GeneratedArtifactError && error.code === generatedArtifactErrorCodes.destinationOccupied && error.details.cleanupFailed !== true;
26
+ async function capacity(root, limits) {
27
+ const info = await fs.statfs(root, { bigint: true });
28
+ if (info.bavail * info.bsize < BigInt(limits.minimumFreeBytes) + BigInt(limits.maximumBytes) * 2n + 65536n)
29
+ throw fail('CAPACITY_REQUIRED');
30
+ }
31
+ async function markerBytes(file) {
32
+ const before = await fs.lstat(file, { bigint: true });
33
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1n || before.size > 4096n || await fs.realpath(file) !== file)
34
+ throw fail('OWNERSHIP_INVALID');
35
+ const body = await fs.readFile(file), after = await fs.lstat(file, { bigint: true });
36
+ if (body.byteLength > 4096 || ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].some(key => before[key] !== after[key]))
37
+ throw fail('OWNERSHIP_INVALID');
38
+ try {
39
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body));
40
+ }
41
+ catch {
42
+ throw fail('OWNERSHIP_INVALID');
43
+ }
44
+ }
45
+ /** SQLite owns CAS; Foundation owns durable publication of the directory/owner bytes. */
46
+ export async function openPublishingJournal({ root, directory, filesystem, limits, signal }) {
47
+ signal?.throwIfAborted();
48
+ limits = checkedLimits(limits);
49
+ if (typeof root !== 'string' || !path.isAbsolute(root) || !filesystem || typeof filesystem.ensureDirectory !== 'function' || typeof filesystem.publishBytes !== 'function')
50
+ throw fail('INPUT_INVALID');
51
+ root = path.resolve(root);
52
+ const rootInfo = await fs.lstat(root, { bigint: true });
53
+ if (!rootInfo.isDirectory() || rootInfo.isSymbolicLink() || await fs.realpath(root) !== root)
54
+ throw fail('BOUNDARY');
55
+ try {
56
+ directory = validatePortableRelativePath(directory);
57
+ }
58
+ catch {
59
+ throw fail('BOUNDARY');
60
+ }
61
+ await capacity(root, limits);
62
+ signal?.throwIfAborted();
63
+ try {
64
+ await filesystem.ensureDirectory(root, directory);
65
+ }
66
+ catch {
67
+ throw fail('PERSISTENCE_UNKNOWN');
68
+ }
69
+ const absolute = path.join(root, ...directory.split('/')), markerFile = path.join(absolute, 'owner.json'), databaseFile = path.join(absolute, 'journal.sqlite');
70
+ const context = { schemaVersion: 1, root: { dev: String(rootInfo.dev), ino: String(rootInfo.ino) }, directory, limits };
71
+ let marker;
72
+ try {
73
+ marker = await markerBytes(markerFile);
74
+ }
75
+ catch (error) {
76
+ if (!fileMissing(error))
77
+ throw error;
78
+ if ((await fs.readdir(absolute)).length)
79
+ throw fail('OCCUPIED');
80
+ const value = { ...context, ownerId: randomUUID() };
81
+ try {
82
+ await filesystem.publishBytes(root, directory + '/owner.json', new TextEncoder().encode(JSON.stringify(value) + '\n'), { mode: 'exclusive' });
83
+ }
84
+ catch (error) {
85
+ if (!occupied(error))
86
+ throw fail('PERSISTENCE_UNKNOWN');
87
+ }
88
+ marker = await markerBytes(markerFile);
89
+ }
90
+ if (!protocolRecord(marker, ['schemaVersion', 'root', 'directory', 'limits', 'ownerId']) || !publishingRequestId(marker.ownerId) || !isDeepStrictEqual({ ...marker, ownerId: undefined }, { ...context, ownerId: undefined }))
91
+ throw fail('CONTEXT_CHANGED');
92
+ const allowed = new Set(['owner.json', 'journal.sqlite', 'journal.sqlite-journal']);
93
+ let retained = 0;
94
+ for (const name of await fs.readdir(absolute)) {
95
+ if (!allowed.has(name))
96
+ throw fail('OCCUPIED');
97
+ const file = path.join(absolute, name), info = await fs.lstat(file);
98
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || await fs.realpath(file) !== file)
99
+ throw fail('BOUNDARY');
100
+ retained += info.size;
101
+ }
102
+ if (retained > limits.maximumBytes * 2 + 65536)
103
+ throw fail('BYTE_LIMIT');
104
+ try {
105
+ await fs.lstat(databaseFile);
106
+ }
107
+ catch (error) {
108
+ if (!fileMissing(error))
109
+ throw error;
110
+ try {
111
+ await filesystem.publishBytes(root, directory + '/journal.sqlite', new Uint8Array(), { mode: 'exclusive' });
112
+ }
113
+ catch (error) {
114
+ if (!occupied(error))
115
+ throw fail('PERSISTENCE_UNKNOWN');
116
+ }
117
+ }
118
+ signal?.throwIfAborted();
119
+ let opened;
120
+ try {
121
+ const database = opened = new DatabaseSync(databaseFile, { enableForeignKeyConstraints: true, enableDoubleQuotedStringLiterals: false, allowExtension: false });
122
+ const tables = database.prepare("SELECT name FROM sqlite_schema WHERE type='table' AND substr(name,1,7)<>'sqlite_' ORDER BY name").all().map(row => row.name);
123
+ if (tables.length === 0) {
124
+ database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;');
125
+ database.exec('BEGIN IMMEDIATE');
126
+ try {
127
+ database.exec('CREATE TABLE journal_metadata (id INTEGER PRIMARY KEY CHECK(id=1),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_records (key TEXT PRIMARY KEY,revision INTEGER NOT NULL CHECK(revision>0),payload TEXT NOT NULL) STRICT;CREATE TABLE journal_blobs (sha256 TEXT PRIMARY KEY,byte_length INTEGER NOT NULL CHECK(byte_length>=0),bytes BLOB NOT NULL) STRICT;');
128
+ database.prepare('INSERT INTO journal_metadata(id,payload) VALUES(1,?)').run(JSON.stringify(marker));
129
+ database.exec('COMMIT');
130
+ }
131
+ catch (error) {
132
+ try {
133
+ database.exec('ROLLBACK');
134
+ }
135
+ catch { }
136
+ throw error;
137
+ }
138
+ }
139
+ else if (tables.join(',') !== 'journal_blobs,journal_metadata,journal_records')
140
+ throw fail('OWNERSHIP_INVALID');
141
+ const stored = database.prepare('SELECT payload FROM journal_metadata WHERE id=1').get();
142
+ if (!stored || typeof stored.payload !== 'string' || !isDeepStrictEqual(JSON.parse(stored.payload), marker))
143
+ throw fail('OWNERSHIP_INVALID');
144
+ database.exec('PRAGMA journal_mode=DELETE;PRAGMA synchronous=FULL;PRAGMA foreign_keys=ON;PRAGMA trusted_schema=OFF;PRAGMA temp_store=MEMORY;PRAGMA busy_timeout=0;');
145
+ const pages = Math.floor(limits.maximumBytes / 4096);
146
+ database.exec('PRAGMA max_page_count=' + pages);
147
+ if (Number(database.prepare('PRAGMA page_size').get()?.page_size) !== 4096 || Number(database.prepare('PRAGMA max_page_count').get()?.max_page_count) !== pages)
148
+ throw fail('BYTE_LIMIT');
149
+ await filesystem.ensureDirectory(root, directory);
150
+ signal?.throwIfAborted();
151
+ }
152
+ catch (error) {
153
+ try {
154
+ opened?.close();
155
+ }
156
+ catch { }
157
+ storageFailure(error);
158
+ }
159
+ if (!opened)
160
+ throw fail('STORAGE_UNKNOWN');
161
+ const database = opened;
162
+ let closed = false;
163
+ const ready = () => { if (closed)
164
+ throw fail('CLOSED'); };
165
+ const load = async (key, { signal } = {}) => {
166
+ ready();
167
+ signal?.throwIfAborted();
168
+ if (!keyValid(key))
169
+ throw fail('KEY_INVALID');
170
+ const row = database.prepare('SELECT revision,payload FROM journal_records WHERE key=?').get(key);
171
+ if (!row)
172
+ return undefined;
173
+ if (typeof row.revision !== 'number' || typeof row.payload !== 'string' || !Number.isSafeInteger(row.revision) || row.revision < 1 || recordBytes(key, row.revision, row.payload) > limits.maximumRecordBytes)
174
+ throw fail('RECORD_INVALID');
175
+ let payload;
176
+ try {
177
+ payload = JSON.parse(row.payload);
178
+ }
179
+ catch {
180
+ throw fail('RECORD_INVALID');
181
+ }
182
+ return { revision: row.revision, payload };
183
+ };
184
+ const readBlob = async ({ sha256, byteLength }, { signal } = {}) => {
185
+ ready();
186
+ signal?.throwIfAborted();
187
+ if (!publishingDigest(sha256) || !Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > limits.maximumBlobBytes)
188
+ throw fail('BLOB_INVALID');
189
+ const row = database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(sha256);
190
+ if (!row)
191
+ return undefined;
192
+ if (row.byte_length !== byteLength || !(row.bytes instanceof Uint8Array) || row.bytes.byteLength !== byteLength || createHash('sha256').update(row.bytes).digest('hex') !== sha256)
193
+ throw fail('BLOB_INVALID');
194
+ return new Uint8Array(row.bytes);
195
+ };
196
+ const compareAndSet = async ({ key, expectedRevision, payload, blobs = [] }, { signal } = {}) => {
197
+ ready();
198
+ signal?.throwIfAborted();
199
+ if (!keyValid(key) || !Number.isSafeInteger(expectedRevision) || expectedRevision < 0 || expectedRevision === Number.MAX_SAFE_INTEGER)
200
+ throw fail('RECORD_INVALID');
201
+ let encoded;
202
+ try {
203
+ encoded = JSON.stringify(payload);
204
+ }
205
+ catch {
206
+ throw fail('RECORD_INVALID');
207
+ }
208
+ if (typeof encoded !== 'string')
209
+ throw fail('RECORD_INVALID');
210
+ if (recordBytes(key, expectedRevision + 1, encoded) > limits.maximumRecordBytes)
211
+ throw fail('BYTE_LIMIT');
212
+ if (!Array.isArray(blobs) || blobs.length > limits.maximumBlobs)
213
+ throw fail('BLOB_LIMIT');
214
+ const snapshots = [];
215
+ let blobBytes = 0;
216
+ for (const blob of blobs) {
217
+ if (!protocolRecord(blob, ['sha256', 'bytes']) || !publishingDigest(blob.sha256) || !(blob.bytes instanceof Uint8Array) || blob.bytes.byteLength > limits.maximumBlobBytes)
218
+ throw fail('BLOB_INVALID');
219
+ blobBytes += blob.bytes.byteLength;
220
+ if (blobBytes > limits.maximumBytes)
221
+ throw fail('BYTE_LIMIT');
222
+ const bytes = new Uint8Array(blob.bytes);
223
+ if (createHash('sha256').update(bytes).digest('hex') !== blob.sha256)
224
+ throw fail('BLOB_INVALID');
225
+ snapshots.push({ sha256: blob.sha256, bytes });
226
+ }
227
+ await capacity(root, limits);
228
+ ready();
229
+ signal?.throwIfAborted();
230
+ try {
231
+ database.exec('BEGIN IMMEDIATE');
232
+ }
233
+ catch (error) {
234
+ storageFailure(error);
235
+ }
236
+ try {
237
+ const row = database.prepare('SELECT revision FROM journal_records WHERE key=?').get(key);
238
+ if ((row?.revision ?? 0) !== expectedRevision) {
239
+ database.exec('ROLLBACK');
240
+ return 'conflict';
241
+ }
242
+ if (!row && Number(database.prepare('SELECT count(*) AS amount FROM journal_records').get()?.amount) >= limits.maximumRecords)
243
+ throw fail('RECORD_LIMIT');
244
+ for (const blob of snapshots) {
245
+ const existing = database.prepare('SELECT byte_length,bytes FROM journal_blobs WHERE sha256=?').get(blob.sha256);
246
+ if (existing) {
247
+ if (existing.byte_length !== blob.bytes.byteLength || !(existing.bytes instanceof Uint8Array) || !Buffer.from(existing.bytes).equals(blob.bytes))
248
+ throw fail('BLOB_INVALID');
249
+ }
250
+ else
251
+ database.prepare('INSERT INTO journal_blobs(sha256,byte_length,bytes) VALUES(?,?,?)').run(blob.sha256, blob.bytes.byteLength, blob.bytes);
252
+ }
253
+ if (Number(database.prepare('SELECT count(*) AS amount FROM journal_blobs').get()?.amount) > limits.maximumBlobs)
254
+ throw fail('BLOB_LIMIT');
255
+ database.prepare('INSERT INTO journal_records(key,revision,payload) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,payload=excluded.payload').run(key, expectedRevision + 1, encoded);
256
+ database.exec('COMMIT');
257
+ return 'stored';
258
+ }
259
+ catch (error) {
260
+ try {
261
+ database.exec('ROLLBACK');
262
+ }
263
+ catch { }
264
+ storageFailure(error);
265
+ }
266
+ };
267
+ return Object.freeze({
268
+ load, readBlob, compareAndSet,
269
+ operationJournal() {
270
+ return {
271
+ async load(requestId, context) { if (!keyValid(requestId))
272
+ throw fail('KEY_INVALID'); return operationRecord(await load('operation:' + requestId, context), () => fail('RECORD_INVALID')); },
273
+ async compareAndSet({ expectedRevision, next }, context) { if (!next?.binding || !keyValid(next.binding.requestId) || next.revision !== expectedRevision + 1)
274
+ throw fail('RECORD_INVALID'); return compareAndSet({ key: 'operation:' + next.binding.requestId, expectedRevision, payload: jsonSnapshot(next) }, context); },
275
+ };
276
+ },
277
+ close() { if (!closed) {
278
+ database.close();
279
+ closed = true;
280
+ } },
281
+ });
282
+ }
@@ -0,0 +1,220 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { createLinuxDurableArtifactFilesystem, createWindowsNtfsDurableArtifactFilesystem } from '@openge/forge-generated-artifacts/node';
4
+ import { validatePortableRelativePath } from '@openge/forge-path-safety';
5
+ import { parsePublishingConfiguration, protocolRecord, publishingError, publishingRequestId } from '../protocol.js';
6
+ import { openPublishingJournal } from './journal.js';
7
+ import { installPublishingAuthorization, loadPublishingAuthorization } from './authorization.js';
8
+ import { createPublishingWorkflow } from './workflow.js';
9
+ import { defaultProducer } from './source-producer.js';
10
+ import { parseAcceptanceDeliveryCredential } from './acceptance-delivery.js';
11
+ import { errorCode, objectRecord } from '../shared/records.js';
12
+ const commands = ['credentials', 'check', 'publish', 'status', 'recover', 'verify', 'abandon'];
13
+ const journalLimits = Object.freeze({ maximumBytes: 536870912, maximumRecords: 256, maximumRecordBytes: 1048576, maximumBlobs: 12000, maximumBlobBytes: 134217728, minimumFreeBytes: 67108864 });
14
+ const fail = (code) => publishingError(code);
15
+ function parse(args) {
16
+ if (!Array.isArray(args) || !args.length || args.some(value => typeof value !== 'string' || !value || value.includes('\0') || value.length > 4096))
17
+ throw fail('CLI_ARGUMENT_INVALID');
18
+ if (args.length === 1 && args[0] === '--help')
19
+ return { command: 'help' };
20
+ const command = commands.find(command => command === args[0]);
21
+ if (!command)
22
+ throw fail('CLI_ARGUMENT_INVALID');
23
+ const selected = { command }, seen = new Set();
24
+ for (let index = 1; index < args.length; index++) {
25
+ const flag = args[index];
26
+ if (seen.has(flag))
27
+ throw fail('CLI_ARGUMENT_INVALID');
28
+ seen.add(flag);
29
+ if (flag === '--root' || flag === '--state' || flag === '--producer') {
30
+ const value = args[++index];
31
+ if (!value || value.startsWith('--') || flag === '--producer' && !['check', 'publish'].includes(command))
32
+ throw fail('CLI_ARGUMENT_INVALID');
33
+ selected[flag === '--root' ? 'root' : flag === '--state' ? 'state' : 'producer'] = value;
34
+ }
35
+ else if (flag === '--stdin' && command === 'credentials')
36
+ selected.stdin = true;
37
+ else if (flag === '--no-wait' && command === 'publish')
38
+ selected.waitMs = 0;
39
+ else if (flag === '--wait-ms' && command === 'publish') {
40
+ const value = args[++index];
41
+ if (!/^[1-9]\d{0,6}$/.test(value ?? '') || Number(value) > 3600000)
42
+ throw fail('CLI_ARGUMENT_INVALID');
43
+ selected.waitMs = Number(value);
44
+ }
45
+ else if (flag === '--replace-credential' && command === 'credentials')
46
+ selected.replaceCredential = true;
47
+ else if (flag === '--new-preparation' && ['check', 'publish'].includes(command))
48
+ selected.newPreparation = true;
49
+ else
50
+ throw fail('CLI_ARGUMENT_INVALID');
51
+ }
52
+ if (command === 'credentials' && !selected.stdin)
53
+ throw fail('CLI_ARGUMENT_INVALID');
54
+ if (seen.has('--no-wait') && seen.has('--wait-ms'))
55
+ throw fail('CLI_ARGUMENT_INVALID');
56
+ for (const key of ['state', 'producer']) {
57
+ const value = selected[key];
58
+ if (value !== undefined) {
59
+ try {
60
+ if (validatePortableRelativePath(value) !== value || key === 'producer' && !value.endsWith('.mjs'))
61
+ throw Error();
62
+ }
63
+ catch {
64
+ throw fail('CLI_ARGUMENT_INVALID');
65
+ }
66
+ }
67
+ }
68
+ return selected;
69
+ }
70
+ async function credentialInput(stdin, signal, timeoutMilliseconds) {
71
+ if (!stdin || stdin.isTTY === true || ['on', 'off', 'destroy', 'resume'].some(name => typeof stdin[name] !== 'function'))
72
+ throw fail('CREDENTIAL_INPUT_NON_TTY_REQUIRED');
73
+ if (!Number.isSafeInteger(timeoutMilliseconds) || timeoutMilliseconds < 1 || timeoutMilliseconds > 300000)
74
+ throw fail('CREDENTIAL_INPUT_LIMIT_INVALID');
75
+ const chunks = [];
76
+ let bytes = 0, timer, abort, data, end, error, close;
77
+ let closedListener;
78
+ const closed = stdin.closed ? Promise.resolve(true) : new Promise(resolve => { closedListener = () => resolve(true); stdin.once('close', closedListener); });
79
+ try {
80
+ if (signal?.aborted)
81
+ throw fail('CREDENTIAL_INPUT_CANCELLED');
82
+ await new Promise((resolve, reject) => {
83
+ let settled = false;
84
+ const rejectOnce = (code) => { if (!settled) {
85
+ settled = true;
86
+ reject(fail(code));
87
+ } };
88
+ data = value => { if (settled)
89
+ return; if (!(value instanceof Uint8Array) && typeof value !== 'string')
90
+ return rejectOnce('CREDENTIAL_INPUT_INVALID'); const chunk = typeof value === 'string' ? Buffer.from(value) : Buffer.from(value); bytes += chunk.byteLength; if (bytes > 16384)
91
+ return rejectOnce('CREDENTIAL_INPUT_BYTE_LIMIT'); chunks.push(chunk); };
92
+ end = () => { if (!settled) {
93
+ settled = true;
94
+ resolve();
95
+ } };
96
+ error = () => rejectOnce('CREDENTIAL_INPUT_INVALID');
97
+ close = () => rejectOnce('CREDENTIAL_INPUT_CLOSED');
98
+ abort = () => rejectOnce('CREDENTIAL_INPUT_CANCELLED');
99
+ stdin.on('data', data);
100
+ stdin.once('end', end);
101
+ stdin.once('error', error);
102
+ stdin.once('close', close);
103
+ signal?.addEventListener('abort', abort, { once: true });
104
+ timer = setTimeout(() => rejectOnce('CREDENTIAL_INPUT_TIMEOUT'), timeoutMilliseconds);
105
+ stdin.resume();
106
+ });
107
+ let value;
108
+ try {
109
+ value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
110
+ }
111
+ catch {
112
+ throw fail('CREDENTIAL_INPUT_INVALID');
113
+ }
114
+ if (!protocolRecord(value, ['configuration', 'credential'], ['acceptanceDelivery']) || typeof value.credential !== 'string' || !/^[A-Za-z0-9_-]{32,4096}$/.test(value.credential))
115
+ throw fail('CREDENTIAL_INPUT_INVALID');
116
+ return { configuration: value.configuration, credential: value.credential, acceptanceDelivery: value.acceptanceDelivery };
117
+ }
118
+ catch (error) {
119
+ if (errorCode(error)?.startsWith('PUBLISHING_CREDENTIAL_INPUT_'))
120
+ throw error;
121
+ throw fail(signal?.aborted ? 'CREDENTIAL_INPUT_CANCELLED' : 'CREDENTIAL_INPUT_INVALID');
122
+ }
123
+ finally {
124
+ clearTimeout(timer);
125
+ if (abort)
126
+ signal?.removeEventListener('abort', abort);
127
+ for (const [name, listener] of [['data', data], ['end', end], ['error', error], ['close', close]])
128
+ if (listener)
129
+ stdin.off(name, listener);
130
+ // Explicit credential input is owned by this call, including blocked pipes.
131
+ stdin.destroy();
132
+ let closureTimer;
133
+ try {
134
+ if (!await Promise.race([closed, new Promise(resolve => { closureTimer = setTimeout(() => resolve(false), 1000); })]))
135
+ throw fail('CREDENTIAL_INPUT_CLOSURE_UNKNOWN');
136
+ }
137
+ finally {
138
+ clearTimeout(closureTimer);
139
+ if (closedListener)
140
+ stdin.off('close', closedListener);
141
+ }
142
+ }
143
+ }
144
+ function diagnostic(error) {
145
+ const supplied = errorCode(error), code = supplied && /^PUBLISHING_[A-Z0-9_]{1,96}$/.test(supplied) ? supplied : 'PUBLISHING_COMMAND_FAILED';
146
+ return { error: { code } };
147
+ }
148
+ /** Bounded one-shot CLI. No token, private producer cause, provider output or
149
+ * environment is returned. Callers own private storage ACLs and backup policy. */
150
+ async function executeCommand(selected, options) {
151
+ let journal;
152
+ try {
153
+ const { signal, allowLoopback = false, request, clientLimits, metadataTransport } = options;
154
+ const raw = selected.command === 'credentials' ? await credentialInput(options.stdin ?? process.stdin, signal, options.credentialInputTimeoutMilliseconds ?? 30000) : undefined;
155
+ const input = raw ? { ...raw, configuration: parsePublishingConfiguration(raw.configuration, { allowLoopback }) } : undefined;
156
+ signal?.throwIfAborted();
157
+ const root = path.resolve(options.cwd ?? process.cwd(), selected.root ?? '.'), info = await fs.lstat(root);
158
+ if (!info.isDirectory() || info.isSymbolicLink() || await fs.realpath(root) !== root)
159
+ throw fail('CLI_ROOT_INVALID');
160
+ const filesystem = options.filesystem ?? await (process.platform === 'win32' ? createWindowsNtfsDurableArtifactFilesystem() : process.platform === 'linux' ? createLinuxDurableArtifactFilesystem() : Promise.reject(fail('CLI_PLATFORM_UNSUPPORTED')));
161
+ if (!filesystem)
162
+ throw fail('CLI_PLATFORM_UNSUPPORTED');
163
+ journal = await openPublishingJournal({ root, directory: selected.state ?? 'state/solution-publishing', filesystem, limits: options.journalLimits ?? journalLimits, signal });
164
+ const shared = { journal, allowLoopback, ...(request ? { request } : {}), ...(clientLimits ? { clientLimits } : {}), signal };
165
+ if (selected.command === 'credentials') {
166
+ if (!input)
167
+ throw fail('CREDENTIAL_INPUT_INVALID');
168
+ const installed = await installPublishingAuthorization({ ...shared, configuration: input.configuration, credential: input.credential, ...(input.acceptanceDelivery === undefined ? {} : { acceptanceDelivery: parseAcceptanceDeliveryCredential(input.acceptanceDelivery) }), replaceCredential: selected.replaceCredential === true });
169
+ return { exitCode: 0, output: { state: installed.status.toLowerCase(), projectId: installed.projectId, policyRevision: installed.policyRevision } };
170
+ }
171
+ const authorization = await loadPublishingAuthorization(shared);
172
+ if (!authorization)
173
+ throw fail('CREDENTIAL_REQUIRED');
174
+ const workflow = createPublishingWorkflow({ ...shared, ...authorization, root, ...(metadataTransport ? { metadataTransport } : {}), ...(options.operationLimits ? { operationLimits: options.operationLimits } : {}) });
175
+ let result;
176
+ try {
177
+ result = await workflow[selected.command]({ signal, ...(selected.producer ? { producer: selected.producer } : {}), ...(selected.newPreparation ? { newPreparation: true } : {}), ...(selected.command === 'publish' ? { waitMs: selected.waitMs ?? 300000 } : {}) });
178
+ }
179
+ catch (error) {
180
+ const code = diagnostic(error).error.code;
181
+ const ambiguous = code.endsWith('_UNKNOWN') || ['PUBLISHING_SERVICE_UNREACHABLE', 'PUBLISHING_PROVIDER_FAILED', 'PUBLISHING_BUSY'].includes(code) || error instanceof Error && error.name === 'TimeoutError';
182
+ let requestId = objectRecord(error) ? error.requestId : undefined;
183
+ if (requestId == null) {
184
+ const saved = (await journal.load('active:' + authorization.configuration.projectId))?.payload;
185
+ if (objectRecord(saved))
186
+ requestId = saved.requestId;
187
+ }
188
+ if (!publishingRequestId(requestId))
189
+ throw error;
190
+ return { exitCode: ambiguous ? 3 : 1, output: { ...(ambiguous ? { state: 'unknown', active: false } : {}), requestId, error: { code } } };
191
+ }
192
+ const exitCode = result.state === 'active' || selected.command === 'check' && result.state === 'checked' || selected.command === 'abandon' && result.state === 'abandoned' ? 0 : result.state === 'failed' ? 1 : 3;
193
+ return { exitCode, output: result };
194
+ }
195
+ finally {
196
+ try {
197
+ journal?.close();
198
+ }
199
+ catch {
200
+ throw fail('JOURNAL_CLOSURE_UNKNOWN');
201
+ }
202
+ }
203
+ }
204
+ export async function runPublishingCommand(args, options = {}) {
205
+ let selected;
206
+ try {
207
+ selected = parse(args);
208
+ }
209
+ catch {
210
+ return { exitCode: 2, output: { error: { code: 'PUBLISHING_CLI_ARGUMENT_INVALID' } } };
211
+ }
212
+ if (selected.command === 'help')
213
+ return { exitCode: 0, output: { commands, sourceProducer: defaultProducer, stateDirectory: 'state/solution-publishing', publishWaitMs: 300000, publishOptions: ['--no-wait', '--wait-ms <1..3600000>'] } };
214
+ try {
215
+ return await executeCommand(selected, options);
216
+ }
217
+ catch (error) {
218
+ return { exitCode: 1, output: diagnostic(error) };
219
+ }
220
+ }