@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.
- package/README.md +1 -1
- package/dist/src/acceptance-delivery-binding.js +59 -0
- package/dist/src/acceptance.js +79 -0
- package/dist/src/client.js +146 -0
- package/dist/src/index.js +3 -0
- package/dist/src/node/acceptance-delivery.js +88 -0
- package/dist/src/node/activation.js +3 -0
- package/dist/src/node/authorization.js +76 -0
- package/dist/src/node/cli.js +20 -0
- package/dist/src/node/index.js +9 -0
- package/dist/src/node/journal.js +282 -0
- package/dist/src/node/publishing-command.js +220 -0
- package/dist/src/node/session.js +223 -0
- package/dist/src/node/solution-package.js +217 -0
- package/dist/src/node/source-error.js +15 -0
- package/dist/src/node/source-producer.js +145 -0
- package/dist/src/node/workflow.js +455 -0
- package/dist/src/package.js +74 -0
- package/dist/src/protocol.js +105 -0
- package/dist/src/shared/activation.js +111 -0
- package/dist/src/shared/records.js +26 -0
- package/dist/src/worker/activation.js +10 -0
- package/dist/src/worker/index.js +6 -0
- package/dist/src/worker/journal.js +301 -0
- package/dist/src/worker/package.js +116 -0
- package/dist/src/worker/release.js +59 -0
- package/dist/src/worker/runtime.js +98 -0
- package/dist/src/worker/service.js +494 -0
- package/package.json +17 -14
- package/{src/acceptance.d.mts → types/acceptance.d.ts} +2 -2
- package/{src/client.d.mts → types/client.d.ts} +1 -1
- package/{src/index.d.mts → types/index.d.ts} +6 -6
- package/{src/node/acceptance-delivery.d.mts → types/node/acceptance-delivery.d.ts} +1 -1
- package/{src/node/activation.d.mts → types/node/activation.d.ts} +4 -4
- package/{src/node/authorization.d.mts → types/node/authorization.d.ts} +4 -4
- package/types/node/index.d.ts +17 -0
- package/{src/node/publishing-command.d.mts → types/node/publishing-command.d.ts} +4 -4
- package/{src/node/session.d.mts → types/node/session.d.ts} +7 -7
- package/{src/node/solution-package.d.mts → types/node/solution-package.d.ts} +2 -2
- package/{src/node/workflow.d.mts → types/node/workflow.d.ts} +7 -7
- package/{src/protocol.d.mts → types/protocol.d.ts} +1 -1
- package/{src/worker/activation.d.mts → types/worker/activation.d.ts} +3 -3
- package/types/worker/index.d.ts +6 -0
- package/{src/worker/package.d.mts → types/worker/package.d.ts} +2 -2
- package/{src/worker/release.d.mts → types/worker/release.d.ts} +3 -3
- package/{src/worker/runtime.d.mts → types/worker/runtime.d.ts} +2 -2
- package/{src/worker/service.d.mts → types/worker/service.d.ts} +7 -7
- package/src/acceptance-delivery-binding.mjs +0 -49
- package/src/acceptance.mjs +0 -67
- package/src/client.mjs +0 -74
- package/src/index.mjs +0 -3
- package/src/node/acceptance-delivery.mjs +0 -70
- package/src/node/activation.mjs +0 -3
- package/src/node/authorization.mjs +0 -49
- package/src/node/cli.mjs +0 -12
- package/src/node/index.d.mts +0 -17
- package/src/node/index.mjs +0 -9
- package/src/node/journal.mjs +0 -135
- package/src/node/publishing-command.mjs +0 -104
- package/src/node/session.mjs +0 -134
- package/src/node/solution-package.mjs +0 -113
- package/src/node/source-error.mjs +0 -9
- package/src/node/source-producer.mjs +0 -103
- package/src/node/workflow.mjs +0 -320
- package/src/package.mjs +0 -36
- package/src/protocol.mjs +0 -50
- package/src/shared/activation.mjs +0 -64
- package/src/worker/activation.mjs +0 -4
- package/src/worker/index.d.mts +0 -6
- package/src/worker/index.mjs +0 -6
- package/src/worker/journal.mjs +0 -151
- package/src/worker/package.mjs +0 -32
- package/src/worker/release.mjs +0 -21
- package/src/worker/runtime.mjs +0 -23
- package/src/worker/service.mjs +0 -251
- /package/{src/node/journal.d.mts → types/node/journal.d.ts} +0 -0
- /package/{src/node/source-error.d.mts → types/node/source-error.d.ts} +0 -0
- /package/{src/package.d.mts → types/package.d.ts} +0 -0
- /package/{src/shared/activation.d.mts → types/shared/activation.d.ts} +0 -0
- /package/{src/worker/journal.d.mts → types/worker/journal.d.ts} +0 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { errorCode, jsonSnapshot, objectRecord } from '../shared/records.js';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { bindArtifactOperation, performArtifactOperation, observeArtifactOperation } from '@openge/forge-artifact-publish';
|
|
4
|
+
import { createPublishingClient } from '../client.js';
|
|
5
|
+
import { parsePublishingConfiguration, parsePublishingIntent, publishingIntentBytes, publishingRequestId, protocolRecord, publishingError } from '../protocol.js';
|
|
6
|
+
import { verifySolutionPackageBytes } from './solution-package.js';
|
|
7
|
+
import { maximumAcceptanceArchiveBytes } from './acceptance-delivery.js';
|
|
8
|
+
import { publishingDigest } from '../protocol.js';
|
|
9
|
+
const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
10
|
+
const encoded = (value) => new TextEncoder().encode(JSON.stringify(value));
|
|
11
|
+
const fail = (code) => publishingError(code);
|
|
12
|
+
function validAcceptanceTarget(target) {
|
|
13
|
+
if (!protocolRecord(target, ['origin', 'keyId', 'publicKeySha256']) || typeof target.origin !== 'string' || !publishingDigest(target.publicKeySha256) ||
|
|
14
|
+
typeof target.keyId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(target.keyId))
|
|
15
|
+
return false;
|
|
16
|
+
const origin = URL.parse(target.origin);
|
|
17
|
+
return origin?.protocol === 'https:' && origin.origin === target.origin;
|
|
18
|
+
}
|
|
19
|
+
const operationDefaults = { timeoutMilliseconds: 30000, closeTimeoutMilliseconds: 2000 };
|
|
20
|
+
function checkBinding(intent, prepared, configuration) {
|
|
21
|
+
const item = intent.package, descriptor = prepared.descriptor;
|
|
22
|
+
if (intent.projectId !== configuration.projectId || item.publisherId !== configuration.publisher.publisherId || ['solutionId', 'publisherId', 'packageName', 'version'].some(key => item[key] !== descriptor[key]) || item.fileCount !== prepared.files.length || item.totalBytes !== prepared.payloadBytes || item.content.manifestSha256 !== prepared.content.manifestSha256)
|
|
23
|
+
throw fail('PACKAGE_BINDING_INVALID');
|
|
24
|
+
}
|
|
25
|
+
function transportFor({ client, intent, manifestBytes, target, configurationSha256, stage }) {
|
|
26
|
+
const pending = new Set(), controller = new AbortController();
|
|
27
|
+
let status, closed = false;
|
|
28
|
+
const run = (signal, execute) => {
|
|
29
|
+
if (closed)
|
|
30
|
+
throw fail('TRANSPORT_CLOSED');
|
|
31
|
+
const promise = Promise.resolve().then(() => execute(AbortSignal.any([signal, controller.signal])));
|
|
32
|
+
pending.add(promise);
|
|
33
|
+
const settled = () => pending.delete(promise);
|
|
34
|
+
promise.then(settled, settled);
|
|
35
|
+
return promise;
|
|
36
|
+
};
|
|
37
|
+
const transport = {
|
|
38
|
+
target, capability: stage === 'create' ? 'artifact-upload' : 'deployment-create', configurationSha256,
|
|
39
|
+
async execute(_binding, context) {
|
|
40
|
+
try {
|
|
41
|
+
status = await run(context.signal, async (signal) => { if (stage !== 'create')
|
|
42
|
+
return client.queueRequest({ intent, signal }); if (!manifestBytes)
|
|
43
|
+
throw fail('FROZEN_BYTES_MISSING'); return client.createRequest({ intent, manifestBytes, signal }); });
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (stage === 'create' && errorCode(error) === 'PUBLISHING_CONFLICT')
|
|
47
|
+
return { state: 'rejected', code: 'CONFLICT' };
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
return { state: 'accepted', reference: intent.requestId };
|
|
51
|
+
},
|
|
52
|
+
async observe(binding, _reference, context) {
|
|
53
|
+
try {
|
|
54
|
+
status = await run(context.signal, signal => client.getStatus({ intent, signal }));
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (errorCode(error) === 'PUBLISHING_REQUEST_NOT_FOUND')
|
|
58
|
+
return { state: 'absent', fingerprint: binding.fingerprint };
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const state = stage === 'create' ? 'succeeded' : status.state === 'uploading' ? 'pending' : status.state === 'unknown' ? 'unknown' : ['failed', 'abandoned', 'superseded'].includes(status.state) ? 'failed' : 'succeeded';
|
|
62
|
+
return { state, fingerprint: binding.fingerprint, reference: intent.requestId };
|
|
63
|
+
},
|
|
64
|
+
async close({ timeoutMilliseconds }) {
|
|
65
|
+
closed = true;
|
|
66
|
+
controller.abort();
|
|
67
|
+
let timer;
|
|
68
|
+
try {
|
|
69
|
+
await Promise.race([Promise.allSettled([...pending]), new Promise(resolve => { timer = setTimeout(resolve, timeoutMilliseconds); })]);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
}
|
|
74
|
+
return { status: pending.size ? 'unconfirmed' : 'closed', activeRequests: pending.size };
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
return { transport, status: () => status };
|
|
78
|
+
}
|
|
79
|
+
/** A project session holds no deployment-provider credential and never evaluates payloads. */
|
|
80
|
+
export function createPublishingSession({ journal, configuration, credential, allowLoopback = false, request, clientLimits, verifyActivation, packageLimits, pathCaseSensitivity, operationLimits = operationDefaults }) {
|
|
81
|
+
const config = parsePublishingConfiguration(configuration, { allowLoopback }), configurationSha256 = hash(encoded(config)), selectedLimits = { ...packageLimits }, selectedOperations = { ...operationLimits }, selectedClientLimits = clientLimits ? { ...clientLimits } : undefined;
|
|
82
|
+
if (!journal || ['load', 'compareAndSet', 'readBlob', 'operationJournal'].some(name => typeof journal[name] !== 'function') || !['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity))
|
|
83
|
+
throw fail('SESSION_INPUT_INVALID');
|
|
84
|
+
const client = createPublishingClient({ configuration: config, credential, allowLoopback, ...(request ? { request } : {}), ...(selectedClientLimits ? { limits: selectedClientLimits } : {}), ...(verifyActivation ? { verifyActivation } : {}) });
|
|
85
|
+
const key = (requestId) => { if (!publishingRequestId(requestId))
|
|
86
|
+
throw fail('REQUEST_ID_INVALID'); return 'request:' + requestId; };
|
|
87
|
+
const metadata = async ({ requestId, signal }) => {
|
|
88
|
+
const record = await journal.load(key(requestId), { signal });
|
|
89
|
+
if (!record)
|
|
90
|
+
throw fail('FROZEN_REQUEST_MISSING');
|
|
91
|
+
const saved = record.payload;
|
|
92
|
+
if (record.revision !== 1 || !protocolRecord(saved, ['schemaVersion', 'configuration', 'intent', 'manifestByteLength'], ['acceptanceArchive', 'acceptanceTarget']) || saved.schemaVersion !== 1 || typeof saved.manifestByteLength !== 'number' || !Number.isSafeInteger(saved.manifestByteLength) || saved.manifestByteLength < 1 || saved.manifestByteLength > 1048576)
|
|
93
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
94
|
+
const archive = saved.acceptanceArchive, target = saved.acceptanceTarget;
|
|
95
|
+
let installed;
|
|
96
|
+
if (archive !== undefined) {
|
|
97
|
+
if (!validAcceptanceTarget(target) || !protocolRecord(archive, ['archiveSha256', 'artifactSha256', 'byteLength']) || !publishingDigest(archive.archiveSha256) || !publishingDigest(archive.artifactSha256) || typeof archive.byteLength !== 'number' || !Number.isSafeInteger(archive.byteLength) || archive.byteLength < 1 || archive.byteLength > maximumAcceptanceArchiveBytes)
|
|
98
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
99
|
+
installed = { archive: { archiveSha256: archive.archiveSha256, artifactSha256: archive.artifactSha256, byteLength: archive.byteLength }, target };
|
|
100
|
+
}
|
|
101
|
+
else if (target !== undefined)
|
|
102
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
103
|
+
if (hash(encoded(parsePublishingConfiguration(saved.configuration, { allowLoopback }))) !== configurationSha256)
|
|
104
|
+
throw fail('CONFIGURATION_CHANGED');
|
|
105
|
+
const intent = parsePublishingIntent(saved.intent);
|
|
106
|
+
if (intent.requestId !== requestId || intent.projectId !== config.projectId || intent.package.publisherId !== config.publisher.publisherId)
|
|
107
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
108
|
+
return { intent, manifestByteLength: saved.manifestByteLength, installed };
|
|
109
|
+
};
|
|
110
|
+
const read = async ({ requestId, signal }) => {
|
|
111
|
+
const { intent, manifestByteLength } = await metadata({ requestId, signal });
|
|
112
|
+
const manifestBytes = await journal.readBlob({ sha256: intent.package.content.manifestSha256, byteLength: manifestByteLength }, { signal });
|
|
113
|
+
if (!manifestBytes)
|
|
114
|
+
throw fail('FROZEN_BYTES_MISSING');
|
|
115
|
+
let manifest;
|
|
116
|
+
try {
|
|
117
|
+
manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifestBytes));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
121
|
+
}
|
|
122
|
+
if (!objectRecord(manifest) || !Array.isArray(manifest.files) || manifest.files.length !== intent.package.fileCount)
|
|
123
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
124
|
+
const files = [];
|
|
125
|
+
for (const file of manifest.files) {
|
|
126
|
+
if (!objectRecord(file) || typeof file.path !== 'string' || !publishingDigest(file.sha256) || typeof file.byteLength !== 'number')
|
|
127
|
+
throw fail('FROZEN_REQUEST_INVALID');
|
|
128
|
+
const bytes = await journal.readBlob({ sha256: file.sha256, byteLength: file.byteLength }, { signal });
|
|
129
|
+
if (!bytes)
|
|
130
|
+
throw fail('FROZEN_BYTES_MISSING');
|
|
131
|
+
files.push({ path: file.path, bytes });
|
|
132
|
+
}
|
|
133
|
+
const prepared = await verifySolutionPackageBytes({ files, manifestBytes, expectedContent: intent.package.content, pathCaseSensitivity, limits: selectedLimits, signal });
|
|
134
|
+
checkBinding(intent, prepared, config);
|
|
135
|
+
return { intent, prepared };
|
|
136
|
+
};
|
|
137
|
+
const operation = async (mode, { requestId, signal, stage = 'create', attempt = 0 }) => {
|
|
138
|
+
if (!['create', 'commit'].includes(stage) || !Number.isSafeInteger(attempt) || attempt < 0 || attempt > 64 || stage === 'commit' && attempt !== 0)
|
|
139
|
+
throw fail('SESSION_INPUT_INVALID');
|
|
140
|
+
const { intent, manifestByteLength } = await metadata({ requestId, signal }), frozen = mode === 'create' ? await read({ requestId, signal }) : undefined, intentBytes = publishingIntentBytes(intent);
|
|
141
|
+
const target = { provider: 'link-light-publishing', namespace: config.projectId, endpoint: config.serviceUrl };
|
|
142
|
+
const operationId = requestId + '.' + stage + (attempt ? '.' + attempt : '');
|
|
143
|
+
const binding = await bindArtifactOperation({ requestId: operationId, content: intent.package.content, ...(intent.provenance ? { provenance: intent.provenance } : {}), target, capability: stage === 'create' ? 'artifact-upload' : 'deployment-create', configurationSha256, inputs: [{ name: 'intent.json', sha256: hash(intentBytes), byteLength: intentBytes.byteLength }, { name: 'content-manifest.json', sha256: intent.package.content.manifestSha256, byteLength: manifestByteLength }] });
|
|
144
|
+
const current = transportFor({ client, intent, manifestBytes: frozen?.prepared.manifestBytes, target, configurationSha256, stage });
|
|
145
|
+
const receipt = await (mode === 'create' ? performArtifactOperation : observeArtifactOperation)(current.transport, binding, journal.operationJournal(), { ...selectedOperations, signal });
|
|
146
|
+
return { receipt, ...(current.status() ? { status: current.status() } : {}) };
|
|
147
|
+
};
|
|
148
|
+
return Object.freeze({
|
|
149
|
+
async freeze({ intent: input, prepared: inputPackage, acceptanceArchive, acceptanceTarget, signal }) {
|
|
150
|
+
const intent = parsePublishingIntent(input);
|
|
151
|
+
key(intent.requestId);
|
|
152
|
+
if (await journal.load(key(intent.requestId), { signal }))
|
|
153
|
+
throw fail('REQUEST_EXISTS');
|
|
154
|
+
const prepared = await verifySolutionPackageBytes({ files: inputPackage.files, manifestBytes: inputPackage.manifestBytes, expectedContent: intent.package.content, pathCaseSensitivity, limits: selectedLimits, signal });
|
|
155
|
+
checkBinding(intent, prepared, config);
|
|
156
|
+
const files = new Map(prepared.manifest.files.map(file => [file.path, file]));
|
|
157
|
+
const blobs = [{ sha256: prepared.content.manifestSha256, bytes: prepared.manifestBytes }, ...prepared.files.map(file => { const entry = files.get(file.path); if (!entry)
|
|
158
|
+
throw fail('PACKAGE_BINDING_INVALID'); return { sha256: entry.sha256, bytes: file.bytes }; })];
|
|
159
|
+
let archive;
|
|
160
|
+
if (acceptanceArchive !== undefined) {
|
|
161
|
+
const { bytes, artifactSha256 } = acceptanceArchive;
|
|
162
|
+
if (!(bytes instanceof Uint8Array) || bytes.byteLength < 1 || bytes.byteLength > maximumAcceptanceArchiveBytes || !publishingDigest(artifactSha256) || !validAcceptanceTarget(acceptanceTarget))
|
|
163
|
+
throw fail('ACCEPTANCE_ARCHIVE_INVALID');
|
|
164
|
+
archive = { archiveSha256: hash(bytes), artifactSha256, byteLength: bytes.byteLength };
|
|
165
|
+
blobs.push({ sha256: archive.archiveSha256, bytes });
|
|
166
|
+
}
|
|
167
|
+
const result = await journal.compareAndSet({ key: key(intent.requestId), expectedRevision: 0, payload: jsonSnapshot({ schemaVersion: 1, configuration: config, intent, manifestByteLength: prepared.manifestBytes.byteLength, ...(archive ? { acceptanceArchive: archive, acceptanceTarget } : {}) }), blobs }, { signal });
|
|
168
|
+
if (result !== 'stored')
|
|
169
|
+
throw fail('REQUEST_EXISTS');
|
|
170
|
+
return { requestId: intent.requestId, content: prepared.content };
|
|
171
|
+
},
|
|
172
|
+
read,
|
|
173
|
+
async acceptanceMetadata({ requestId, signal }) {
|
|
174
|
+
const { installed, intent } = await metadata({ requestId, signal });
|
|
175
|
+
return installed ? { intent, ...installed } : undefined;
|
|
176
|
+
},
|
|
177
|
+
async readAcceptanceArchive({ requestId, signal }) {
|
|
178
|
+
const { installed, intent } = await metadata({ requestId, signal });
|
|
179
|
+
if (!installed)
|
|
180
|
+
return undefined;
|
|
181
|
+
const { archive, target } = installed;
|
|
182
|
+
const bytes = await journal.readBlob({ sha256: archive.archiveSha256, byteLength: archive.byteLength }, { signal });
|
|
183
|
+
if (!bytes || hash(bytes) !== archive.archiveSha256)
|
|
184
|
+
throw fail('FROZEN_BYTES_MISSING');
|
|
185
|
+
return { archive, bytes, intent, target };
|
|
186
|
+
},
|
|
187
|
+
create: input => operation('create', { ...input, stage: 'create' }),
|
|
188
|
+
observe: input => operation('observe', input),
|
|
189
|
+
queue: input => operation('create', { ...input, stage: 'commit' }),
|
|
190
|
+
async status({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.getStatus({ intent, signal }); },
|
|
191
|
+
async resume({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.resumeRequest({ intent, signal }); },
|
|
192
|
+
async recover({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.recoverRequest({ intent, signal }); },
|
|
193
|
+
async upload({ requestId, signal }) {
|
|
194
|
+
const { intent, prepared } = await read({ requestId, signal }), manifest = new Map(prepared.manifest.files.map(file => [file.path, file])), bodies = new Map(prepared.files.map(file => [file.path, file.bytes]));
|
|
195
|
+
const checked = async () => {
|
|
196
|
+
const status = await client.getStatus({ intent, signal }), seen = new Map();
|
|
197
|
+
for (const file of status.missingFiles) {
|
|
198
|
+
const original = manifest.get(file.path);
|
|
199
|
+
if (!original || original.sha256 !== file.sha256 || original.byteLength !== file.byteLength || file.receivedBytes >= file.byteLength || seen.has(file.sha256) && seen.get(file.sha256) !== file.receivedBytes)
|
|
200
|
+
throw fail('STATUS_BINDING_INVALID');
|
|
201
|
+
seen.set(file.sha256, file.receivedBytes);
|
|
202
|
+
}
|
|
203
|
+
return status;
|
|
204
|
+
};
|
|
205
|
+
const status = await checked();
|
|
206
|
+
if (status.state !== 'uploading')
|
|
207
|
+
return status;
|
|
208
|
+
const done = new Set(), chunkBytes = selectedClientLimits?.maximumChunkBytes ?? 262144;
|
|
209
|
+
for (const file of status.missingFiles) {
|
|
210
|
+
if (done.has(file.sha256))
|
|
211
|
+
continue;
|
|
212
|
+
done.add(file.sha256);
|
|
213
|
+
const bytes = bodies.get(file.path);
|
|
214
|
+
if (!bytes)
|
|
215
|
+
throw fail('FROZEN_BYTES_MISSING');
|
|
216
|
+
for (let offset = file.receivedBytes; offset < file.byteLength; offset += chunkBytes)
|
|
217
|
+
await client.uploadChunk({ requestId, file, offset, bytes: bytes.subarray(offset, Math.min(offset + chunkBytes, file.byteLength)), signal });
|
|
218
|
+
}
|
|
219
|
+
return checked();
|
|
220
|
+
},
|
|
221
|
+
async abandon({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.abandonRequest({ intent, signal }); },
|
|
222
|
+
});
|
|
223
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { calculateBytesIntegrity } from '@openge/forge-artifact-integrity';
|
|
4
|
+
import { createArtifactContentManifest } from '@openge/forge-artifact-publish';
|
|
5
|
+
import { captureArtifactFiles, verifyArtifactFiles } from '@openge/forge-artifact-publish/node';
|
|
6
|
+
import { parseSolutionPackageDescriptor, parseSolutionPackageLimits } from '../package.js';
|
|
7
|
+
const failure = (code) => Error('PUBLISHING_PACKAGE_' + code);
|
|
8
|
+
const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
9
|
+
const check = (signal) => signal.throwIfAborted();
|
|
10
|
+
function runtimeClosure(descriptor, files, pathCaseSensitivity) {
|
|
11
|
+
const names = new Set(files), links = new Map(), fold = (value) => pathCaseSensitivity === 'case-insensitive' ? value.toLowerCase() : value;
|
|
12
|
+
const overlaps = (first, second) => first === second || first.startsWith(second + '/') || second.startsWith(first + '/');
|
|
13
|
+
for (const link of descriptor.runtime.links) {
|
|
14
|
+
const name = fold(link.path);
|
|
15
|
+
if (files.some(file => overlaps(fold(file), name)) || [...links.keys()].some(file => overlaps(fold(file), name)))
|
|
16
|
+
throw failure('RUNTIME_LINK_INVALID');
|
|
17
|
+
links.set(link.path, link.target);
|
|
18
|
+
}
|
|
19
|
+
const resolve = (input, visited = new Set()) => {
|
|
20
|
+
if (visited.size > 64 || visited.has(input))
|
|
21
|
+
throw failure('RUNTIME_LINK_INVALID');
|
|
22
|
+
visited.add(input);
|
|
23
|
+
const match = [...links.keys()].filter(name => input === name || input.startsWith(name + '/')).sort((a, b) => b.length - a.length)[0];
|
|
24
|
+
if (match) {
|
|
25
|
+
const linkTarget = links.get(match);
|
|
26
|
+
if (linkTarget === undefined)
|
|
27
|
+
throw failure('RUNTIME_LINK_INVALID');
|
|
28
|
+
const target = path.posix.normalize(path.posix.join(path.posix.dirname(match), linkTarget, input.slice(match.length)));
|
|
29
|
+
if (!target.startsWith('server/'))
|
|
30
|
+
throw failure('RUNTIME_LINK_INVALID');
|
|
31
|
+
return resolve(target, visited);
|
|
32
|
+
}
|
|
33
|
+
if (!names.has(input) && !files.some(name => name.startsWith(input + '/')))
|
|
34
|
+
throw failure('RUNTIME_LINK_INVALID');
|
|
35
|
+
return input;
|
|
36
|
+
};
|
|
37
|
+
for (const name of links.keys())
|
|
38
|
+
resolve(name);
|
|
39
|
+
if (!names.has(descriptor.runtime.entry) || !names.has(descriptor.ui.entry))
|
|
40
|
+
throw failure('ENTRY_MISSING');
|
|
41
|
+
}
|
|
42
|
+
function packageNames(files, pathCaseSensitivity) {
|
|
43
|
+
if (!['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity))
|
|
44
|
+
throw failure('INPUT_INVALID');
|
|
45
|
+
const names = files.map(file => file.path), folded = names.map(name => pathCaseSensitivity === 'case-insensitive' ? name.toLowerCase() : name);
|
|
46
|
+
const paths = new Set(folded), collision = folded.some(name => { for (let slash = name.lastIndexOf('/'); slash >= 0; slash = name.lastIndexOf('/', slash - 1))
|
|
47
|
+
if (paths.has(name.slice(0, slash)))
|
|
48
|
+
return true; return false; });
|
|
49
|
+
if (paths.size !== folded.length || collision || names.some(name => name.split('/').some(part => part.startsWith('.env') || ['.git', '.npmrc', '.ssh', 'release-private'].includes(part))) || files.find(file => file.path === 'solution.json')?.role !== 'control')
|
|
50
|
+
throw failure('PLAN_INVALID');
|
|
51
|
+
return names;
|
|
52
|
+
}
|
|
53
|
+
function completed(prepared, captured, pathCaseSensitivity, total) {
|
|
54
|
+
let descriptor;
|
|
55
|
+
try {
|
|
56
|
+
const control = captured.find(file => file.path === 'solution.json');
|
|
57
|
+
if (!control)
|
|
58
|
+
throw failure('DESCRIPTOR_INVALID');
|
|
59
|
+
descriptor = parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(control.bytes)));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw failure('DESCRIPTOR_INVALID');
|
|
63
|
+
}
|
|
64
|
+
runtimeClosure(descriptor, packageNames(prepared.manifest.files, pathCaseSensitivity), pathCaseSensitivity);
|
|
65
|
+
const files = captured.sort((a, b) => compare(a.path, b.path));
|
|
66
|
+
const streamFile = async function* (path, { signal } = {}) { const file = files.find(file => file.path === path), declared = prepared.manifest.files.find(file => file.path === path); if (!file || !declared)
|
|
67
|
+
throw failure('CLOSURE'); const digest = createHash('sha256'); let count = 0; for (let offset = 0; offset < file.bytes.length; offset += 1048576) {
|
|
68
|
+
signal?.throwIfAborted();
|
|
69
|
+
const bytes = new Uint8Array(file.bytes.subarray(offset, Math.min(offset + 1048576, file.bytes.length)));
|
|
70
|
+
digest.update(bytes);
|
|
71
|
+
count += bytes.length;
|
|
72
|
+
yield bytes;
|
|
73
|
+
} if (count !== declared.byteLength || digest.digest('hex') !== declared.sha256)
|
|
74
|
+
throw failure('CHANGED'); };
|
|
75
|
+
const readFile = async (path, input) => { const declared = prepared.manifest.files.find(file => file.path === path), maximumBytes = input?.maximumBytes, signal = input?.signal; if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0 || maximumBytes > 16777216 || !declared || declared.byteLength > maximumBytes)
|
|
76
|
+
throw failure('BYTE_LIMIT'); const bytes = new Uint8Array(declared.byteLength); let offset = 0; for await (const part of streamFile(path, { signal })) {
|
|
77
|
+
bytes.set(part, offset);
|
|
78
|
+
offset += part.length;
|
|
79
|
+
} return bytes; };
|
|
80
|
+
return { descriptor, content: prepared.content, manifest: prepared.manifest, manifestBytes: prepared.bytes, files, payloadBytes: total, streamFile, readFile };
|
|
81
|
+
}
|
|
82
|
+
async function capturedPackage(declared, captured, pathCaseSensitivity, selected, current, total) {
|
|
83
|
+
const byPath = new Map(captured.map(file => [file.path, file])), manifestFiles = [];
|
|
84
|
+
if (byPath.size !== captured.length || declared.length !== captured.length)
|
|
85
|
+
throw failure('CLOSURE');
|
|
86
|
+
for (const file of declared) {
|
|
87
|
+
const capturedFile = byPath.get(file.path);
|
|
88
|
+
if (!capturedFile)
|
|
89
|
+
throw failure('CLOSURE');
|
|
90
|
+
const bytes = capturedFile.bytes, integrity = await calculateBytesIntegrity(bytes);
|
|
91
|
+
check(current);
|
|
92
|
+
manifestFiles.push({ ...file, byteLength: bytes.byteLength, sha256: integrity.sha256 });
|
|
93
|
+
}
|
|
94
|
+
const prepared = await createArtifactContentManifest({ schemaVersion: 1, files: manifestFiles });
|
|
95
|
+
check(current);
|
|
96
|
+
if (prepared.bytes.byteLength > selected.maximumManifestBytes || total + prepared.bytes.byteLength > selected.maximumTotalBytes)
|
|
97
|
+
throw failure('BYTE_LIMIT');
|
|
98
|
+
return completed(prepared, captured, pathCaseSensitivity, total);
|
|
99
|
+
}
|
|
100
|
+
async function canonicalManifest(manifestBytes, expectedContent, limits) {
|
|
101
|
+
if (!(manifestBytes instanceof Uint8Array) || manifestBytes.byteLength > limits.maximumManifestBytes || !expectedContent || Object.keys(expectedContent).join(',') !== 'manifestSha256' || !/^[a-f0-9]{64}$/.test(expectedContent.manifestSha256 ?? ''))
|
|
102
|
+
throw failure('MANIFEST_INVALID');
|
|
103
|
+
const snapshot = new Uint8Array(manifestBytes);
|
|
104
|
+
let manifest;
|
|
105
|
+
try {
|
|
106
|
+
manifest = await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(snapshot)));
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
throw failure('MANIFEST_INVALID');
|
|
110
|
+
}
|
|
111
|
+
if (manifest.content.manifestSha256 !== expectedContent.manifestSha256 || manifest.bytes.byteLength !== snapshot.byteLength || manifest.bytes.some((byte, index) => byte !== snapshot[index]))
|
|
112
|
+
throw failure('MANIFEST_CHANGED');
|
|
113
|
+
return manifest;
|
|
114
|
+
}
|
|
115
|
+
/** Capture exact artifact bytes, independently of source control or a deployment. */
|
|
116
|
+
export async function prepareSolutionPackage({ root, files, pathCaseSensitivity, limits, signal }) {
|
|
117
|
+
signal?.throwIfAborted();
|
|
118
|
+
const selected = parseSolutionPackageLimits(limits);
|
|
119
|
+
if (typeof root !== 'string' || !path.isAbsolute(root) || !['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity) || !Array.isArray(files) || !files.length || files.length > selected.maximumFiles)
|
|
120
|
+
throw failure('INPUT_INVALID');
|
|
121
|
+
let declared;
|
|
122
|
+
try {
|
|
123
|
+
declared = (await createArtifactContentManifest({ schemaVersion: 1, files: files.map(file => ({ ...file, byteLength: 0, sha256: '0'.repeat(64) })) })).manifest.files;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
throw failure('PLAN_INVALID');
|
|
127
|
+
}
|
|
128
|
+
if (files.some(file => Object.keys(file).sort().join(',') !== (file.role === 'asset' ? 'path,responseHeaders,role' : 'path,role')))
|
|
129
|
+
throw failure('PLAN_INVALID');
|
|
130
|
+
packageNames(declared, pathCaseSensitivity);
|
|
131
|
+
return captureSolution({ root, files, pathCaseSensitivity, selected, signal });
|
|
132
|
+
}
|
|
133
|
+
async function captureSolution({ root, files, pathCaseSensitivity, selected, signal, manifestBytes, expectedContent }) {
|
|
134
|
+
const options = { sources: [{ rootDirectory: root, closure: 'exact', files: files.map(file => ({ ...file, sourcePath: file.path })) }], pathCaseSensitivity, maxFiles: selected.maximumFiles, maxEntries: selected.maximumFiles * 8, maxFileBytes: selected.maximumFileBytes, maxTotalBytes: selected.maximumTotalBytes, maxManifestBytes: selected.maximumManifestBytes, timeoutMilliseconds: selected.timeoutMs, ...(signal ? { signal } : {}) };
|
|
135
|
+
let captured;
|
|
136
|
+
try {
|
|
137
|
+
captured = await (manifestBytes ? verifyArtifactFiles({ ...options, manifestBytes, expectedContent }) : captureArtifactFiles(options));
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
signal?.throwIfAborted();
|
|
141
|
+
const reasons = { INVALID_PLAN: 'PLAN_INVALID', INVALID_SOURCE: 'CLOSURE', INTEGRITY_MISMATCH: 'CHANGED', BUDGET_EXCEEDED: 'BYTE_LIMIT', CLOSURE_UNCONFIRMED: 'CLOSE_FAILED' };
|
|
142
|
+
throw failure(error instanceof Error && 'code' in error && typeof error.code === 'string' ? (reasons[error.code] ?? 'CAPTURE_FAILED') : 'CAPTURE_FAILED');
|
|
143
|
+
}
|
|
144
|
+
return completed({ manifest: captured.manifest, content: captured.content, bytes: captured.manifestBytes }, captured.manifest.files.map(file => ({ path: file.path, bytes: captured.readFile(file.path) })), pathCaseSensitivity, captured.payloadByteLength);
|
|
145
|
+
}
|
|
146
|
+
/** Compose already-captured components without staging a second directory tree. */
|
|
147
|
+
export async function prepareSolutionPackageBytes({ files, pathCaseSensitivity, limits, signal }) {
|
|
148
|
+
signal?.throwIfAborted();
|
|
149
|
+
const selected = parseSolutionPackageLimits(limits), deadline = AbortSignal.timeout(selected.timeoutMs), current = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
150
|
+
if (!Array.isArray(files) || !files.length || files.length > selected.maximumFiles)
|
|
151
|
+
throw failure('INPUT_INVALID');
|
|
152
|
+
const captured = [], plan = [];
|
|
153
|
+
let total = 0;
|
|
154
|
+
for (const file of files) {
|
|
155
|
+
if (!file || !(file.bytes instanceof Uint8Array) || Object.keys(file).sort().join(',') !== (file.role === 'asset' ? 'bytes,path,responseHeaders,role' : 'bytes,path,role'))
|
|
156
|
+
throw failure('PLAN_INVALID');
|
|
157
|
+
if (file.bytes.byteLength > selected.maximumFileBytes)
|
|
158
|
+
throw failure('BYTE_LIMIT');
|
|
159
|
+
total += file.bytes.byteLength;
|
|
160
|
+
if (total > selected.maximumTotalBytes)
|
|
161
|
+
throw failure('BYTE_LIMIT');
|
|
162
|
+
captured.push({ path: file.path, bytes: new Uint8Array(file.bytes) });
|
|
163
|
+
const { bytes, ...declaration } = file;
|
|
164
|
+
void bytes;
|
|
165
|
+
plan.push({ ...declaration, byteLength: 0, sha256: '0'.repeat(64) });
|
|
166
|
+
}
|
|
167
|
+
let declared;
|
|
168
|
+
try {
|
|
169
|
+
declared = (await createArtifactContentManifest({ schemaVersion: 1, files: plan })).manifest.files;
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
throw failure('PLAN_INVALID');
|
|
173
|
+
}
|
|
174
|
+
packageNames(declared, pathCaseSensitivity);
|
|
175
|
+
return capturedPackage(declared, captured, pathCaseSensitivity, selected, current, total);
|
|
176
|
+
}
|
|
177
|
+
export async function verifySolutionPackage({ root, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }) {
|
|
178
|
+
const selected = parseSolutionPackageLimits(limits), manifest = await canonicalManifest(manifestBytes, expectedContent, selected);
|
|
179
|
+
packageNames(manifest.manifest.files, pathCaseSensitivity);
|
|
180
|
+
return captureSolution({ root, files: manifest.manifest.files.map(file => file.role === 'asset' ? { path: file.path, role: file.role, responseHeaders: file.responseHeaders } : { path: file.path, role: file.role }), pathCaseSensitivity, selected, signal, manifestBytes: manifest.bytes, expectedContent });
|
|
181
|
+
}
|
|
182
|
+
/** Validate opaque received bytes without importing or executing the payload. */
|
|
183
|
+
export async function verifySolutionPackageBytes({ files, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }) {
|
|
184
|
+
signal?.throwIfAborted();
|
|
185
|
+
const selected = parseSolutionPackageLimits(limits), deadline = AbortSignal.timeout(selected.timeoutMs), current = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
186
|
+
if (!Array.isArray(files) || files.length < 1 || files.length > selected.maximumFiles)
|
|
187
|
+
throw failure('CLOSURE');
|
|
188
|
+
const captured = [], seen = new Set();
|
|
189
|
+
let total = 0;
|
|
190
|
+
for (const file of files) {
|
|
191
|
+
if (!file || Object.keys(file).sort().join(',') !== 'bytes,path' || typeof file.path !== 'string' || !(file.bytes instanceof Uint8Array) || seen.has(file.path))
|
|
192
|
+
throw failure('CLOSURE');
|
|
193
|
+
if (file.bytes.byteLength > selected.maximumFileBytes)
|
|
194
|
+
throw failure('BYTE_LIMIT');
|
|
195
|
+
total += file.bytes.byteLength;
|
|
196
|
+
if (total > selected.maximumTotalBytes)
|
|
197
|
+
throw failure('BYTE_LIMIT');
|
|
198
|
+
seen.add(file.path);
|
|
199
|
+
captured.push({ path: file.path, bytes: new Uint8Array(file.bytes) });
|
|
200
|
+
}
|
|
201
|
+
const prepared = await canonicalManifest(manifestBytes, expectedContent, selected);
|
|
202
|
+
check(current);
|
|
203
|
+
if (total + prepared.bytes.byteLength > selected.maximumTotalBytes)
|
|
204
|
+
throw failure('BYTE_LIMIT');
|
|
205
|
+
if (prepared.manifest.files.length !== captured.length)
|
|
206
|
+
throw failure('CLOSURE');
|
|
207
|
+
const byPath = new Map(captured.map(file => [file.path, file]));
|
|
208
|
+
for (const declared of prepared.manifest.files) {
|
|
209
|
+
const file = byPath.get(declared.path);
|
|
210
|
+
if (!file)
|
|
211
|
+
throw failure('CLOSURE');
|
|
212
|
+
if (file.bytes.byteLength !== declared.byteLength || (await calculateBytesIntegrity(file.bytes)).sha256 !== declared.sha256)
|
|
213
|
+
throw failure('CHANGED');
|
|
214
|
+
check(current);
|
|
215
|
+
}
|
|
216
|
+
return completed(prepared, captured, pathCaseSensitivity, total);
|
|
217
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Only a source owner that observed its process lifecycle may assert closure.
|
|
2
|
+
* The original cause stays private; CLI diagnostics emit only the stable code. */
|
|
3
|
+
export class PublishingSourceError extends Error {
|
|
4
|
+
code;
|
|
5
|
+
processesClosed;
|
|
6
|
+
constructor({ cause, processesClosed }) {
|
|
7
|
+
if (typeof processesClosed !== 'boolean')
|
|
8
|
+
throw TypeError('PUBLISHING_SOURCE_CLOSURE_REQUIRED');
|
|
9
|
+
const code = processesClosed ? 'PUBLISHING_SOURCE_PREPARATION_FAILED' : 'PUBLISHING_SOURCE_PREPARATION_UNKNOWN';
|
|
10
|
+
super(code, { cause });
|
|
11
|
+
this.name = 'PublishingSourceError';
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.processesClosed = processesClosed;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createRequire, findPackageJSON } from 'node:module';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { validatePortableRelativePath } from '@openge/forge-path-safety';
|
|
6
|
+
import { protocolRecord, publishingError } from '../protocol.js';
|
|
7
|
+
export const defaultProducer = 'deployment/publishing.mjs';
|
|
8
|
+
const maximumSourceBytes = 65536n;
|
|
9
|
+
const fail = (code) => publishingError('SOURCE_' + code);
|
|
10
|
+
const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
11
|
+
const sameFile = (before, after) => ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every(key => before[key] === after[key]);
|
|
12
|
+
const readOnlyFlags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
13
|
+
export function validateLocalProducer(relative) {
|
|
14
|
+
try {
|
|
15
|
+
if (validatePortableRelativePath(relative) === relative && relative.endsWith('.mjs'))
|
|
16
|
+
return relative;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw fail('PATH_INVALID');
|
|
20
|
+
}
|
|
21
|
+
throw fail('PATH_INVALID');
|
|
22
|
+
}
|
|
23
|
+
async function localProducerFile(root, relative) {
|
|
24
|
+
const parts = relative.split('/');
|
|
25
|
+
let current = root;
|
|
26
|
+
for (const [index, part] of parts.entries()) {
|
|
27
|
+
current = path.join(current, part);
|
|
28
|
+
const info = await fs.lstat(current, { bigint: true });
|
|
29
|
+
if (info.isSymbolicLink() || await fs.realpath(current) !== current || (index === parts.length - 1 ? !info.isFile() || info.nlink !== 1n || info.size > maximumSourceBytes : !info.isDirectory()))
|
|
30
|
+
throw fail('PATH_INVALID');
|
|
31
|
+
}
|
|
32
|
+
return current;
|
|
33
|
+
}
|
|
34
|
+
async function readManifest(file, { checkout = false } = {}) {
|
|
35
|
+
let before;
|
|
36
|
+
try {
|
|
37
|
+
before = await fs.lstat(file, { bigint: true });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (checkout && error instanceof Error && 'code' in error && error.code === 'ENOENT')
|
|
41
|
+
return undefined;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
if (!before.isFile() || before.size > maximumSourceBytes || checkout && before.nlink !== 1n)
|
|
45
|
+
throw fail('METADATA_INVALID');
|
|
46
|
+
const handle = await fs.open(file, readOnlyFlags);
|
|
47
|
+
try {
|
|
48
|
+
if (!sameFile(before, await handle.stat({ bigint: true })))
|
|
49
|
+
throw fail('METADATA_INVALID');
|
|
50
|
+
const bytes = Buffer.alloc(Number(before.size) + 1);
|
|
51
|
+
let offset = 0;
|
|
52
|
+
while (offset < bytes.length) {
|
|
53
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
|
|
54
|
+
if (bytesRead === 0)
|
|
55
|
+
break;
|
|
56
|
+
offset += bytesRead;
|
|
57
|
+
}
|
|
58
|
+
if (offset !== Number(before.size) || !sameFile(before, await handle.stat({ bigint: true })) || !sameFile(before, await fs.lstat(file, { bigint: true })))
|
|
59
|
+
throw fail('METADATA_INVALID');
|
|
60
|
+
const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, offset)));
|
|
61
|
+
if (!record(value))
|
|
62
|
+
throw fail('METADATA_INVALID');
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
await handle.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export async function checkoutReleaseVersion(root, packageName) {
|
|
70
|
+
const manifest = await readManifest(path.join(root, 'package.json'), { checkout: true });
|
|
71
|
+
if (!manifest || manifest.name === undefined && manifest.version === undefined)
|
|
72
|
+
return undefined;
|
|
73
|
+
if (manifest.name !== packageName || typeof manifest.version !== 'string' ||
|
|
74
|
+
!/^(?:0|[1-9]\d{0,7})(?:\.(?:0|[1-9]\d{0,7})){2}$/.test(manifest.version))
|
|
75
|
+
throw fail('PACKAGE_BINDING_INVALID');
|
|
76
|
+
return manifest.version;
|
|
77
|
+
}
|
|
78
|
+
export async function checkoutRequiresAcceptanceDelivery(root) {
|
|
79
|
+
const manifest = await readManifest(path.join(root, 'package.json'), { checkout: true });
|
|
80
|
+
const metadata = manifest?.linkLight;
|
|
81
|
+
const mode = record(metadata) ? metadata.acceptanceDelivery : undefined;
|
|
82
|
+
if (mode !== undefined && mode !== 'required')
|
|
83
|
+
throw fail('METADATA_INVALID');
|
|
84
|
+
return mode === 'required';
|
|
85
|
+
}
|
|
86
|
+
function contains(parent, child) {
|
|
87
|
+
const relative = path.relative(parent, child);
|
|
88
|
+
return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
|
|
89
|
+
}
|
|
90
|
+
async function packageProducerFile(root, manifest, checkout, selection) {
|
|
91
|
+
if (!protocolRecord(selection, ['module']) || typeof selection.module !== 'string' || selection.module.length > 512)
|
|
92
|
+
throw fail('METADATA_INVALID');
|
|
93
|
+
const specifier = selection.module;
|
|
94
|
+
const match = /^((?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*)(\/[A-Za-z0-9_-][A-Za-z0-9._-]*)+$/.exec(specifier);
|
|
95
|
+
if (match?.[0] !== specifier)
|
|
96
|
+
throw fail('METADATA_INVALID');
|
|
97
|
+
const packageName = match[1];
|
|
98
|
+
if (![checkout.dependencies, checkout.devDependencies].some(group => record(group) && Object.hasOwn(group, packageName) && typeof group[packageName] === 'string' && group[packageName].trim()))
|
|
99
|
+
throw fail('PACKAGE_UNDECLARED');
|
|
100
|
+
const modules = path.join(root, 'node_modules');
|
|
101
|
+
if (await fs.realpath(modules) !== modules)
|
|
102
|
+
throw fail('PATH_INVALID');
|
|
103
|
+
const installed = await fs.realpath(path.join(modules, ...packageName.split('/')));
|
|
104
|
+
if (!contains(modules, installed))
|
|
105
|
+
throw fail('PATH_INVALID');
|
|
106
|
+
const dependency = await readManifest(path.join(installed, 'package.json'));
|
|
107
|
+
if (dependency.name !== packageName || dependency.exports == null)
|
|
108
|
+
throw fail('PACKAGE_EXPORT_INVALID');
|
|
109
|
+
const file = await fs.realpath(createRequire(manifest).resolve(specifier));
|
|
110
|
+
if (!contains(installed, file))
|
|
111
|
+
throw fail('PATH_INVALID');
|
|
112
|
+
if (!file.endsWith('.mjs')) {
|
|
113
|
+
if (!file.endsWith('.js'))
|
|
114
|
+
throw fail('PATH_INVALID');
|
|
115
|
+
const scope = findPackageJSON(pathToFileURL(file));
|
|
116
|
+
if (!scope)
|
|
117
|
+
throw fail('PATH_INVALID');
|
|
118
|
+
const scopePath = await fs.realpath(scope);
|
|
119
|
+
if (!contains(installed, scopePath))
|
|
120
|
+
throw fail('PATH_INVALID');
|
|
121
|
+
const metadata = scopePath === path.join(installed, 'package.json') ? dependency : await readManifest(scope);
|
|
122
|
+
if (metadata.type !== 'module')
|
|
123
|
+
throw fail('PATH_INVALID');
|
|
124
|
+
}
|
|
125
|
+
const info = await fs.lstat(file, { bigint: true });
|
|
126
|
+
if (!info.isFile() || info.size > maximumSourceBytes)
|
|
127
|
+
throw fail('PATH_INVALID');
|
|
128
|
+
return file;
|
|
129
|
+
}
|
|
130
|
+
export async function selectProducerFile(root, explicit) {
|
|
131
|
+
if (explicit !== undefined)
|
|
132
|
+
return localProducerFile(root, explicit);
|
|
133
|
+
const manifest = path.join(root, 'package.json'), checkout = await readManifest(manifest, { checkout: true });
|
|
134
|
+
const metadata = checkout?.linkLight;
|
|
135
|
+
if (metadata !== undefined && !record(metadata))
|
|
136
|
+
throw fail('METADATA_INVALID');
|
|
137
|
+
const selection = metadata?.publishingProducer;
|
|
138
|
+
if (selection === undefined)
|
|
139
|
+
return localProducerFile(root, defaultProducer);
|
|
140
|
+
if (typeof selection === 'string')
|
|
141
|
+
return localProducerFile(root, validateLocalProducer(selection));
|
|
142
|
+
if (!checkout)
|
|
143
|
+
throw fail('METADATA_INVALID');
|
|
144
|
+
return packageProducerFile(root, manifest, checkout, selection);
|
|
145
|
+
}
|