@xlinklight/publishing 3.3.1 → 3.4.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.
Files changed (76) hide show
  1. package/README.md +22 -2
  2. package/dist/src/acceptance-delivery-binding.d.ts +20 -0
  3. package/dist/src/acceptance.d.ts +49 -0
  4. package/dist/src/client.d.ts +71 -0
  5. package/dist/src/index.d.ts +6 -0
  6. package/dist/src/node/acceptance-delivery.d.ts +34 -0
  7. package/dist/src/node/activation.d.ts +5 -0
  8. package/dist/src/node/authorization.d.ts +31 -0
  9. package/dist/src/node/cli.d.ts +2 -0
  10. package/dist/src/node/cli.js +4 -2
  11. package/dist/src/node/index.d.ts +20 -0
  12. package/dist/src/node/index.js +2 -0
  13. package/dist/src/node/journal-directory.d.ts +2 -0
  14. package/dist/src/node/journal-directory.js +121 -0
  15. package/dist/src/node/journal.d.ts +49 -0
  16. package/dist/src/node/journal.js +6 -8
  17. package/dist/src/node/local-json-file.d.ts +3 -0
  18. package/dist/src/node/local-json-file.js +49 -0
  19. package/dist/src/node/publishing-command.d.ts +46 -0
  20. package/dist/src/node/publishing-command.js +64 -16
  21. package/dist/src/node/session.d.ts +95 -0
  22. package/dist/src/node/solution-package.d.ts +55 -0
  23. package/dist/src/node/source-error.d.ts +10 -0
  24. package/dist/src/node/source-producer.d.ts +5 -0
  25. package/dist/src/node/terminal-network.d.ts +23 -0
  26. package/dist/src/node/terminal-network.js +122 -0
  27. package/dist/src/node/workflow.d.ts +74 -0
  28. package/dist/src/node/workflow.js +46 -34
  29. package/dist/src/package.d.ts +38 -0
  30. package/dist/src/protocol.d.ts +83 -0
  31. package/dist/src/protocol.js +1 -1
  32. package/dist/src/shared/activation-types.d.ts +37 -0
  33. package/dist/src/shared/activation-types.js +1 -0
  34. package/dist/src/shared/activation.d.ts +17 -0
  35. package/dist/src/shared/records.d.ts +10 -0
  36. package/dist/src/shared/release-version.d.ts +4 -0
  37. package/dist/src/shared/release-version.js +15 -0
  38. package/dist/src/worker/activation.d.ts +12 -0
  39. package/dist/src/worker/activation.js +2 -1
  40. package/dist/src/worker/durable-retention.d.ts +9 -0
  41. package/dist/src/worker/durable-retention.js +96 -0
  42. package/dist/src/worker/index.d.ts +12 -0
  43. package/dist/src/worker/index.js +1 -0
  44. package/dist/src/worker/journal.d.ts +129 -0
  45. package/dist/src/worker/journal.js +33 -6
  46. package/dist/src/worker/package.d.ts +60 -0
  47. package/dist/src/worker/release-retention.d.ts +34 -0
  48. package/dist/src/worker/release-retention.js +27 -0
  49. package/dist/src/worker/release.d.ts +22 -0
  50. package/dist/src/worker/runtime.d.ts +47 -0
  51. package/dist/src/worker/service.d.ts +128 -0
  52. package/dist/src/worker/service.js +38 -12
  53. package/package.json +13 -7
  54. package/types/acceptance.d.ts +0 -24
  55. package/types/client.d.ts +0 -16
  56. package/types/index.d.ts +0 -6
  57. package/types/node/acceptance-delivery.d.ts +0 -11
  58. package/types/node/activation.d.ts +0 -8
  59. package/types/node/authorization.d.ts +0 -8
  60. package/types/node/index.d.ts +0 -17
  61. package/types/node/journal.d.ts +0 -13
  62. package/types/node/publishing-command.d.ts +0 -20
  63. package/types/node/session.d.ts +0 -25
  64. package/types/node/solution-package.d.ts +0 -15
  65. package/types/node/source-error.d.ts +0 -5
  66. package/types/node/workflow.d.ts +0 -37
  67. package/types/package.d.ts +0 -11
  68. package/types/protocol.d.ts +0 -27
  69. package/types/shared/activation.d.ts +0 -5
  70. package/types/worker/activation.d.ts +0 -7
  71. package/types/worker/index.d.ts +0 -6
  72. package/types/worker/journal.d.ts +0 -21
  73. package/types/worker/package.d.ts +0 -16
  74. package/types/worker/release.d.ts +0 -7
  75. package/types/worker/runtime.d.ts +0 -4
  76. package/types/worker/service.d.ts +0 -41
@@ -2,7 +2,8 @@ import { errorCode, jsonSnapshot, objectRecord } from '../shared/records.js';
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
- import { createHash, randomUUID } from 'node:crypto';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { newerVersion, publishingVersionRequestId } from '../shared/release-version.js';
6
7
  import { setTimeout as delay } from 'node:timers/promises';
7
8
  import { createPublishingClient } from '../client.js';
8
9
  import { parsePublishingConfiguration, parsePublishingProject, parsePublishingIntent, publishingRequestId, protocolRecord, publishingError } from '../protocol.js';
@@ -22,17 +23,8 @@ function frozenPackage(record) {
22
23
  return typeof packageName === 'string' && typeof version === 'string' ? { packageName, version } : undefined;
23
24
  }
24
25
  const rejectedDelivery = new Set(['PUBLISHING_ACCEPTANCE_VERSION_CONFLICT', 'PUBLISHING_ACCEPTANCE_SIGNATURE_INVALID', 'PUBLISHING_ACCEPTANCE_DELIVERY_REJECTED']);
25
- function newerVersion(candidate, original) {
26
- const parts = candidate.split('.').map(Number), previous = original.split('.').map(Number);
27
- const index = parts.findIndex((part, n) => part !== previous[n]);
28
- return index >= 0 && parts[index] > previous[index];
29
- }
30
- function versionRequestId(configuration, packageName, version) {
31
- const bytes = createHash('sha256').update(JSON.stringify(['link-light/project-version/v1', configuration.serviceUrl, configuration.projectId, packageName, version])).digest().subarray(0, 16);
32
- bytes[6] = (bytes[6] & 15) | 128;
33
- bytes[8] = (bytes[8] & 63) | 128;
34
- const hex = bytes.toString('hex');
35
- return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
26
+ function closedForReplacement(status) {
27
+ return status.sideEffects === 'closed' && ['active', 'abandoned', 'failed', 'superseded'].includes(status.state);
36
28
  }
37
29
  const sourceOptions = (input) => {
38
30
  if (!protocolRecord(input, [], ['producer', 'newPreparation', 'signal']) || input.newPreparation !== undefined && typeof input.newPreparation !== 'boolean')
@@ -51,6 +43,24 @@ export function createPublishingWorkflow(options) {
51
43
  const verifier = (signal) => async (input) => { const timeout = AbortSignal.timeout(clientLimits?.requestMs ?? 30000); await verifyPublishingActivation({ ...input, allowLoopback, signal: signal ? AbortSignal.any([signal, timeout]) : timeout, ...(metadataTransport ? { metadataTransport } : {}) }); };
52
44
  const shared = { journal, configuration, credential, allowLoopback, ...(request ? { request } : {}), ...(clientLimits ? { clientLimits } : {}) };
53
45
  const client = (signal) => createPublishingClient({ ...shared, ...(clientLimits ? { limits: clientLimits } : {}), verifyActivation: verifier(signal) }), activeKey = 'active:' + configuration.projectId;
46
+ const selectVersion = async (project, version, signal) => {
47
+ const latest = await client(signal).getLatestRelease({ signal });
48
+ if (!latest)
49
+ return {};
50
+ const { intent, status } = latest;
51
+ if (intent.package.packageName !== project.packageName || intent.package.solutionId !== project.solutionId)
52
+ throw fail('PROJECT_BINDING_INVALID');
53
+ if (intent.package.version === version) {
54
+ if (status.state !== 'abandoned' && status.state !== 'superseded')
55
+ return { intent };
56
+ }
57
+ else if (closedForReplacement(status)) {
58
+ if (!newerVersion(version, intent.package.version))
59
+ throw fail('SOURCE_VERSION_NOT_NEWER');
60
+ return {};
61
+ }
62
+ return { observed: { requestId: intent.requestId, state: status.state, sideEffects: status.sideEffects, active: false } };
63
+ };
54
64
  const session = (record, signal) => createPublishingSession({ ...shared, verifyActivation: verifier(signal), packageLimits: record.payload.project.limits, pathCaseSensitivity: record.payload.pathCaseSensitivity, ...(operationLimits ? { operationLimits } : {}) });
55
65
  const replace = async (record, phase, signal, failure, createAttempt = record.payload.createAttempt) => {
56
66
  const payload = { ...record.payload, phase, ...(createAttempt ? { createAttempt } : {}) };
@@ -126,7 +136,7 @@ export function createPublishingWorkflow(options) {
126
136
  // next release. A prior terminal observation never authorizes an unknown,
127
137
  // still-running or currently unverified request to be replaced.
128
138
  const observed = await inspect({ signal }, true);
129
- if (observed.sideEffects !== 'closed' || !['abandoned', 'active', 'failed'].includes(observed.state)) {
139
+ if (!closedForReplacement(observed)) {
130
140
  if (automatic)
131
141
  return { observed: { ...observed, active: false } };
132
142
  throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
@@ -139,8 +149,20 @@ export function createPublishingWorkflow(options) {
139
149
  if (phase === 'preparing')
140
150
  throw fail('SOURCE_PREPARATION_UNKNOWN');
141
151
  if (['frozen', 'delivering', 'remote'].includes(phase)) {
142
- if (!newPreparation)
152
+ if (!newPreparation) {
153
+ const { project, selectedVersion, requestId, createAttempt } = previous.record.payload;
154
+ if (options.acceptanceDelivery && (phase !== 'remote' || !await operationClaim(requestId, 'create', signal, createAttempt))) {
155
+ const version = selectedVersion ?? frozenPackage(await journal.load('request:' + requestId, { signal }))?.version;
156
+ if (!version)
157
+ throw fail('FROZEN_REQUEST_INVALID');
158
+ const selection = await selectVersion(project, version, signal);
159
+ if (selection.observed)
160
+ return { observed: selection.observed };
161
+ if (selection.intent && selection.intent.requestId !== requestId)
162
+ throw fail('ACCEPTANCE_VERSION_CONFLICT');
163
+ }
143
164
  return previous.record;
165
+ }
144
166
  if (phase !== 'remote' || !previousCreateRejected)
145
167
  throw fail('SOURCE_ACTIVE_REQUEST_EXISTS');
146
168
  }
@@ -167,21 +189,11 @@ export function createPublishingWorkflow(options) {
167
189
  if (!version)
168
190
  throw fail('SOURCE_PACKAGE_BINDING_INVALID');
169
191
  selectedVersion = version;
170
- const latest = await client(signal).getLatestRelease({ signal });
171
- if (latest && (latest.intent.package.packageName !== project.packageName || latest.intent.package.solutionId !== project.solutionId))
172
- throw fail('PROJECT_BINDING_INVALID');
173
- if (latest?.intent.package.version === version) {
174
- inherited = latest.intent;
175
- requestId = inherited.requestId;
176
- }
177
- else {
178
- if (latest && (!['active', 'failed', 'superseded'].includes(latest.status.state) || latest.status.sideEffects !== 'closed')) {
179
- return { observed: { requestId: latest.intent.requestId, state: latest.status.state, sideEffects: latest.status.sideEffects, active: false } };
180
- }
181
- if (latest && !newerVersion(version, latest.intent.package.version))
182
- throw fail('SOURCE_VERSION_NOT_NEWER');
183
- requestId = versionRequestId(configuration, project.packageName, version);
184
- }
192
+ const selection = await selectVersion(project, version, signal);
193
+ if (selection.observed)
194
+ return { observed: selection.observed };
195
+ inherited = selection.intent;
196
+ requestId = inherited?.requestId ?? publishingVersionRequestId(configuration, project.packageName, version);
185
197
  }
186
198
  signal?.throwIfAborted();
187
199
  const payload = { schemaVersion: 1, requestId, project, pathCaseSensitivity, ...(selectedVersion ? { selectedVersion } : {}), ...(selectionFailure ? { phase: 'failed-closed', failure: { code: selectionFailure.code } } : { phase: 'preparing' }) };
@@ -246,7 +258,7 @@ export function createPublishingWorkflow(options) {
246
258
  const observedResult = async (record, status, signal) => {
247
259
  // The client/session authenticated this exact original intent, and ACTIVE
248
260
  // already passed the real signature and current Core-admission verifier.
249
- const terminal = { abandoned: 'abandoned', active: 'completed', failed: 'failed' };
261
+ const terminal = { abandoned: 'abandoned', active: 'completed', superseded: 'completed', failed: 'failed' };
250
262
  const phase = status.sideEffects === 'closed' ? terminal[status.state] : undefined;
251
263
  if (phase && record.payload.phase !== phase) {
252
264
  try {
@@ -274,7 +286,7 @@ export function createPublishingWorkflow(options) {
274
286
  if (record.payload.phase === 'delivering') {
275
287
  const bundle = await session(record, signal).acceptanceMetadata({ requestId: record.payload.requestId, signal });
276
288
  try {
277
- if (!bundle || !options.acceptanceDelivery || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
289
+ if (!bundle || !options.acceptanceDelivery || !('target' in bundle) || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
278
290
  throw fail('ACCEPTANCE_TRUST_CHANGED');
279
291
  if (await observeAcceptanceDelivery({ ...bundle, credential: options.acceptanceDelivery, request, signal }))
280
292
  return result(record, 'checked');
@@ -355,7 +367,7 @@ export function createPublishingWorkflow(options) {
355
367
  if (['frozen', 'delivering', 'delivery-rejected'].includes(record.payload.phase)) {
356
368
  const bundle = await selected.readAcceptanceArchive({ requestId, signal });
357
369
  if (bundle) {
358
- if (!options.acceptanceDelivery || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
370
+ if (!options.acceptanceDelivery || !('target' in bundle) || JSON.stringify(bundle.target) !== JSON.stringify(acceptanceDeliveryTarget(options.acceptanceDelivery)))
359
371
  return result(record, 'failed', { error: { code: 'PUBLISHING_ACCEPTANCE_TRUST_CHANGED' } });
360
372
  if (record.payload.phase !== 'delivering')
361
373
  record = await replace(record, 'delivering', signal);
@@ -385,12 +397,12 @@ export function createPublishingWorkflow(options) {
385
397
  let attempt = record.payload.createAttempt ?? 0, createClaim = await operationClaim(requestId, 'create', signal, attempt);
386
398
  if (rejectedCreate(createClaim)) {
387
399
  const latest = await client(signal).getLatestRelease({ signal });
388
- if (latest && latest.status.sideEffects !== 'closed')
400
+ if (latest && !closedForReplacement(latest.status))
389
401
  return { requestId: latest.intent.requestId, state: latest.status.state, sideEffects: latest.status.sideEffects, active: false };
390
402
  const version = record.payload.selectedVersion ?? frozenPackage(await journal.load('request:' + requestId, { signal }))?.version;
391
403
  if (!version)
392
404
  throw fail('FROZEN_REQUEST_INVALID');
393
- if (latest && latest.intent.package.version === version || attempt >= 64)
405
+ if (latest && !newerVersion(version, latest.intent.package.version) || attempt >= 64)
394
406
  return result(record, 'failed', { sideEffects: 'closed', error: { code: 'PUBLISHING_CONFLICT' } });
395
407
  // An authenticated rejection is durable. Advance only after observing
396
408
  // closure. Unknown create acknowledgements always use the original claim.
@@ -0,0 +1,38 @@
1
+ import type { Digest, JsonValue } from '@xlinklight/contracts';
2
+ export interface SolutionPackageLimits {
3
+ maximumFiles: number;
4
+ maximumFileBytes: number;
5
+ maximumTotalBytes: number;
6
+ maximumManifestBytes: number;
7
+ timeoutMs: number;
8
+ }
9
+ export interface SolutionPackageDescriptor {
10
+ readonly schemaVersion: 1;
11
+ readonly solutionId: string;
12
+ readonly publisherId: string;
13
+ readonly packageName: string;
14
+ readonly version: string;
15
+ readonly sdkApiVersion: '2.0.0';
16
+ readonly runtime: {
17
+ readonly entry: string;
18
+ readonly protocolVersion: 2;
19
+ readonly links: readonly {
20
+ readonly path: string;
21
+ readonly target: string;
22
+ }[];
23
+ };
24
+ readonly ui: {
25
+ readonly entry: string;
26
+ readonly bridgeVersion: 1;
27
+ };
28
+ readonly release: {
29
+ readonly permissions: JsonValue;
30
+ readonly display: JsonValue;
31
+ readonly queries: JsonValue;
32
+ readonly operations: JsonValue;
33
+ readonly capabilities: JsonValue;
34
+ readonly resourcesDigest: Digest;
35
+ };
36
+ }
37
+ export declare function parseSolutionPackageLimits(value: unknown): SolutionPackageLimits;
38
+ export declare function parseSolutionPackageDescriptor(value: unknown): SolutionPackageDescriptor;
@@ -0,0 +1,83 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { SolutionPackageLimits } from './package.js';
3
+ /** Consumer-owned read-only public metadata port. It carries no credentials or
4
+ * command body and does not require the optional platform implementation. */
5
+ export type PublishingMetadataTransport = (address: string, options: {
6
+ timeoutMs?: number;
7
+ signal?: AbortSignal;
8
+ }) => Promise<JsonValue>;
9
+ export interface PublishingConfiguration {
10
+ schemaVersion: 1;
11
+ serviceUrl: string;
12
+ projectId: string;
13
+ coreOrigin: string;
14
+ publisher: {
15
+ publisherId: string;
16
+ keys: {
17
+ keyId: string;
18
+ publicKey: string;
19
+ }[];
20
+ };
21
+ }
22
+ export interface PublishingIntent {
23
+ schemaVersion: 1;
24
+ requestId: string;
25
+ projectId: string;
26
+ policyRevision: number;
27
+ package: {
28
+ solutionId: string;
29
+ publisherId: string;
30
+ packageName: string;
31
+ version: string;
32
+ content: {
33
+ manifestSha256: string;
34
+ };
35
+ fileCount: number;
36
+ totalBytes: number;
37
+ };
38
+ provenance?: {
39
+ gitRevision: string;
40
+ };
41
+ }
42
+ export interface PublishingProject {
43
+ schemaVersion: 1;
44
+ configuration: PublishingConfiguration;
45
+ policyRevision: number;
46
+ solutionId: string;
47
+ packageName: string;
48
+ limits: SolutionPackageLimits;
49
+ }
50
+ export interface PublishingStatus {
51
+ schemaVersion: 1;
52
+ requestId: string;
53
+ projectId: string;
54
+ intentSha256: string;
55
+ state: 'uploading' | 'queued' | 'deploying' | 'registered' | 'awaiting-acceptance' | 'active' | 'failed' | 'unknown' | 'abandoned' | 'superseded';
56
+ sideEffects: 'none' | 'pending' | 'unknown' | 'closed';
57
+ missingFiles: {
58
+ path: string;
59
+ sha256: string;
60
+ byteLength: number;
61
+ receivedBytes: number;
62
+ }[];
63
+ activation?: JsonValue;
64
+ error?: {
65
+ code: string;
66
+ };
67
+ }
68
+ export declare const publishingError: (code: string) => Error & {
69
+ code: string;
70
+ };
71
+ export declare const protocolRecord: <T>(value: T, required: readonly string[], optional?: readonly string[]) => value is T & Record<string, unknown>;
72
+ export declare const publishingIdentifier: (value: unknown) => value is string;
73
+ export declare const publishingDigest: (value: unknown) => value is string;
74
+ export declare const publishingRequestId: (value: unknown) => value is string;
75
+ export declare function parsePublishingConfiguration(value: unknown, { allowLoopback }?: {
76
+ allowLoopback?: boolean;
77
+ }): PublishingConfiguration;
78
+ export declare function parsePublishingIntent(value: unknown): PublishingIntent;
79
+ export declare function parsePublishingProject(value: unknown, { allowLoopback }?: {
80
+ allowLoopback?: boolean;
81
+ }): PublishingProject;
82
+ export declare const publishingIntentBytes: (value: unknown) => Uint8Array;
83
+ export declare function parsePublishingStatus(value: unknown): PublishingStatus;
@@ -60,7 +60,7 @@ export function parsePublishingProject(value, { allowLoopback = false } = {}) {
60
60
  }
61
61
  return { schemaVersion: 1, configuration: parsePublishingConfiguration(value.configuration, { allowLoopback }), policyRevision: value.policyRevision, solutionId: value.solutionId, packageName: value.packageName, limits };
62
62
  }
63
- export const publishingIntentBytes = value => new TextEncoder().encode(JSON.stringify(parsePublishingIntent(value)));
63
+ export const publishingIntentBytes = (value) => new TextEncoder().encode(JSON.stringify(parsePublishingIntent(value)));
64
64
  export function parsePublishingStatus(value) {
65
65
  if (!protocolRecord(value, ['schemaVersion', 'requestId', 'projectId', 'intentSha256', 'state', 'sideEffects', 'missingFiles'], ['activation', 'error']) || value.schemaVersion !== 1 || !publishingRequestId(value.requestId) || !publishingIdentifier(value.projectId) || !publishingDigest(value.intentSha256) || !member(value.state, ['uploading', 'queued', 'deploying', 'registered', 'awaiting-acceptance', 'active', 'failed', 'unknown', 'abandoned', 'superseded']) || !member(value.sideEffects, ['none', 'pending', 'unknown', 'closed']) || !Array.isArray(value.missingFiles) || value.missingFiles.length > 10000)
66
66
  throw publishingError('STATUS_INVALID');
@@ -0,0 +1,37 @@
1
+ import type { Digest, SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type { PublishingConfiguration, PublishingIntent, PublishingMetadataTransport } from '../protocol.js';
3
+ export interface PublishingActivation {
4
+ payload: {
5
+ schemaVersion: 1;
6
+ projectId: string;
7
+ requestId: string;
8
+ policyRevision: number;
9
+ configurationSha256: string;
10
+ intentSha256: string;
11
+ releaseDigest: Digest;
12
+ acceptanceReceiptSha256: string;
13
+ };
14
+ manifest: SolutionReleaseManifest;
15
+ signature: {
16
+ keyId: string;
17
+ algorithm: 'Ed25519';
18
+ value: string;
19
+ };
20
+ }
21
+ interface ActivationContext {
22
+ configuration: PublishingConfiguration;
23
+ intent: PublishingIntent;
24
+ allowLoopback?: boolean;
25
+ metadataTransport?: PublishingMetadataTransport;
26
+ signal?: AbortSignal;
27
+ }
28
+ export interface CreateActivationInput extends ActivationContext {
29
+ manifest: SolutionReleaseManifest;
30
+ acceptanceReceiptSha256: string;
31
+ keyId: string;
32
+ privateKey: string;
33
+ }
34
+ export interface VerifyActivationInput extends ActivationContext {
35
+ activation: unknown;
36
+ }
37
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ import type { SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type * as Platform from '@xlinklight/platform/worker';
3
+ import type { PublishingMetadataTransport } from '../protocol.js';
4
+ import type { CreateActivationInput, PublishingActivation, VerifyActivationInput } from './activation-types.js';
5
+ type ActivationDomain = Pick<typeof Platform, 'publicPublisherMetadata' | 'verifySolutionRelease' | 'releasePayload' | 'canonicalMetadata' | 'metadataDigest'> & {
6
+ resolveApprovedIndependentRelease(input: Omit<Parameters<typeof Platform.resolveApprovedIndependentRelease>[0], 'transport'> & {
7
+ transport?: PublishingMetadataTransport;
8
+ }): ReturnType<typeof Platform.resolveApprovedIndependentRelease>;
9
+ };
10
+ export declare function createPublishingActivationFunctions(loadDomain: () => Promise<ActivationDomain>): {
11
+ createPublishingActivation: (input: CreateActivationInput) => Promise<PublishingActivation>;
12
+ verifyPublishingActivation: (input: VerifyActivationInput) => Promise<{
13
+ manifest: Readonly<SolutionReleaseManifest>;
14
+ acceptanceReceiptSha256: string;
15
+ }>;
16
+ };
17
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { ArtifactOperationRecord } from '@openge/forge-artifact-publish';
3
+ export declare const objectRecord: (value: unknown) => value is Record<string, unknown>;
4
+ export declare function errorCode(value: unknown): string | undefined;
5
+ export declare function jsonSnapshot(value: unknown): JsonValue;
6
+ export declare function jsonValue(value: unknown): value is JsonValue;
7
+ export declare function operationRecord(record: {
8
+ revision: number;
9
+ payload: unknown;
10
+ } | undefined, invalid: () => Error): ArtifactOperationRecord | undefined;
@@ -0,0 +1,4 @@
1
+ import type { PublishingConfiguration } from '../protocol.js';
2
+ export declare function newerVersion(candidate: string, original: string): boolean;
3
+ /** Stable across authorized workstations and independent of the credential or policy revision. */
4
+ export declare function publishingVersionRequestId(configuration: Pick<PublishingConfiguration, 'serviceUrl' | 'projectId'>, packageName: string, version: string): string;
@@ -0,0 +1,15 @@
1
+ import { createHash } from 'node:crypto';
2
+ export function newerVersion(candidate, original) {
3
+ const parts = candidate.split('.').map(Number), previous = original.split('.').map(Number);
4
+ const index = parts.findIndex((part, n) => part !== previous[n]);
5
+ return index >= 0 && parts[index] > previous[index];
6
+ }
7
+ /** Stable across authorized workstations and independent of the credential or policy revision. */
8
+ export function publishingVersionRequestId(configuration, packageName, version) {
9
+ const identity = ['link-light/project-version/v1', configuration.serviceUrl, configuration.projectId, packageName, version];
10
+ const bytes = createHash('sha256').update(JSON.stringify(identity)).digest().subarray(0, 16);
11
+ bytes[6] = (bytes[6] & 15) | 128;
12
+ bytes[8] = (bytes[8] & 63) | 128;
13
+ const hex = bytes.toString('hex');
14
+ return [hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-');
15
+ }
@@ -0,0 +1,12 @@
1
+ import type { SolutionReleaseManifest } from '@xlinklight/contracts';
2
+ import type { PublishingMetadataTransport } from '../protocol.js';
3
+ import type { CreateActivationInput, VerifyActivationInput, PublishingActivation } from '../shared/activation-types.js';
4
+ export type { PublishingActivation } from '../shared/activation-types.js';
5
+ type WorkerAdmission = {
6
+ metadataTransport: PublishingMetadataTransport;
7
+ };
8
+ export declare const createPublishingActivation: (input: CreateActivationInput & WorkerAdmission) => Promise<PublishingActivation>;
9
+ export declare const verifyPublishingActivation: (input: VerifyActivationInput & WorkerAdmission) => Promise<{
10
+ manifest: Readonly<SolutionReleaseManifest>;
11
+ acceptanceReceiptSha256: string;
12
+ }>;
@@ -7,4 +7,5 @@ const helpers = createPublishingActivationFunctions(async () => ({ publicPublish
7
7
  return resolveApprovedIndependentRelease({ ...input, transport: input.transport });
8
8
  },
9
9
  }));
10
- export const { createPublishingActivation, verifyPublishingActivation } = helpers;
10
+ export const createPublishingActivation = helpers.createPublishingActivation;
11
+ export const verifyPublishingActivation = helpers.verifyPublishingActivation;
@@ -0,0 +1,9 @@
1
+ import type { JsonValue } from '@xlinklight/contracts';
2
+ import type { PublishingClosedRequestReplacement, PublishingDurableStorage } from './journal.js';
3
+ type Sql = PublishingDurableStorage['sql'];
4
+ /** Called inside the same SQLite transaction as the new project revision. */
5
+ export declare function reclaimClosedRecords(sql: Sql, projectId: string, previous: JsonValue, next: JsonValue, retire: PublishingClosedRequestReplacement, now: number, maximumRecords: number): string[];
6
+ /** Keep legacy or opaque bytes with unknown ownership. For owned package bytes,
7
+ * retain every manifest or chunk still required by any project's full request. */
8
+ export declare function reclaimUnreferencedPackageBlobs(sql: Sql, digests: readonly string[]): void;
9
+ export {};
@@ -0,0 +1,96 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { objectRecord } from '../shared/records.js';
4
+ import { parsePublishingIntent, publishingIntentBytes, publishingDigest, publishingRequestId, publishingError } from '../protocol.js';
5
+ import { newerVersion, publishingVersionRequestId } from '../shared/release-version.js';
6
+ import { closedRelease, releaseReceipts } from './release-retention.js';
7
+ const fail = () => publishingError('DURABLE_RETIREMENT_CONFLICT');
8
+ function requests(value, projectId) {
9
+ if (!objectRecord(value) || !objectRecord(value.policy) || !objectRecord(value.policy.configuration) ||
10
+ value.policy.configuration.projectId !== projectId || !objectRecord(value.policy.configuration.publisher) || !Array.isArray(value.requests))
11
+ throw fail();
12
+ for (const row of value.requests) {
13
+ if (!objectRecord(row) || !Array.isArray(row.files) || typeof row.state !== 'string' || typeof row.sideEffects !== 'string')
14
+ throw fail();
15
+ const intent = parsePublishingIntent(row.intent);
16
+ if (intent.projectId !== projectId || intent.package.solutionId !== value.policy.solutionId || intent.package.packageName !== value.policy.packageName ||
17
+ intent.package.publisherId !== value.policy.configuration.publisher.publisherId ||
18
+ createHash('sha256').update(publishingIntentBytes(intent)).digest('hex') !== row.intentSha256)
19
+ throw fail();
20
+ for (const file of row.files) {
21
+ if (!objectRecord(file) || !Array.isArray(file.chunks) || file.chunks.some(chunk => !objectRecord(chunk) || !publishingDigest(chunk.sha256)))
22
+ throw fail();
23
+ }
24
+ }
25
+ return value.requests;
26
+ }
27
+ /** Called inside the same SQLite transaction as the new project revision. */
28
+ export function reclaimClosedRecords(sql, projectId, previous, next, retire, now, maximumRecords) {
29
+ const old = requests(previous, projectId), proposed = requests(next, projectId), created = proposed.at(-1);
30
+ if (!created || created.state !== 'uploading' || created.sideEffects !== 'none' || created.receiptOnly ||
31
+ !old.every(closedRelease) || !isDeepStrictEqual(proposed.slice(0, -1), releaseReceipts(old)) ||
32
+ old.some(row => !newerVersion(created.intent.package.version, row.intent.package.version)))
33
+ throw fail();
34
+ if (!objectRecord(previous) || !objectRecord(previous.policy) || !objectRecord(previous.policy.configuration))
35
+ throw fail();
36
+ const url = previous.policy.configuration.serviceUrl;
37
+ if (typeof url !== 'string' || created.intent.requestId !== publishingVersionRequestId({ serviceUrl: url, projectId }, created.intent.package.packageName, created.intent.package.version))
38
+ throw fail();
39
+ const full = old.filter(item => !item.receiptOnly), ids = full.map(item => item.intent.requestId);
40
+ if (!isDeepStrictEqual(retire.requestIds, ids) || new Set(ids).size !== ids.length || !ids.every(publishingRequestId) ||
41
+ !Array.isArray(retire.auxiliaryRecords) || retire.auxiliaryRecords.length > maximumRecords)
42
+ throw fail();
43
+ if (sql.exec('SELECT project FROM publishing_queue WHERE project=? UNION ALL SELECT project FROM publishing_leases WHERE project=? AND until_ms>? LIMIT 1', projectId, projectId, now).toArray().length)
44
+ throw fail();
45
+ const candidates = new Set();
46
+ for (const item of full) {
47
+ candidates.add(item.intent.package.content.manifestSha256);
48
+ for (const file of item.files)
49
+ for (const part of file.chunks)
50
+ candidates.add(part.sha256);
51
+ }
52
+ if (!ids.length && retire.auxiliaryRecords.length)
53
+ throw fail();
54
+ if (ids.length) {
55
+ if (sql.exec(`SELECT 1 FROM publishing_records AS record,json_each(record.payload,'$.requests') AS item
56
+ WHERE record.key GLOB 'project:*' AND record.key<>? AND json_extract(item.value,'$.intent.requestId') IN (SELECT value FROM json_each(?)) LIMIT 1`, 'project:' + projectId, JSON.stringify(ids)).toArray().length)
57
+ throw fail();
58
+ }
59
+ const auxiliaryKeys = new Set();
60
+ for (const entry of retire.auxiliaryRecords) {
61
+ if (!entry || typeof entry.key !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9:._/-]{0,511}$/.test(entry.key) ||
62
+ /^(project|operation|retirement):/.test(entry.key) || !Number.isSafeInteger(entry.revision) || entry.revision < 1 || auxiliaryKeys.has(entry.key))
63
+ throw fail();
64
+ auxiliaryKeys.add(entry.key);
65
+ const removed = sql.exec('DELETE FROM publishing_records WHERE key=? AND revision=? RETURNING key', entry.key, entry.revision).toArray();
66
+ if (removed.length !== 1)
67
+ throw fail();
68
+ }
69
+ for (const item of full) {
70
+ const id = item.intent.requestId;
71
+ // A lost historical operation never becomes a confirmed outcome through cleanup.
72
+ sql.exec(`DELETE FROM publishing_records WHERE key GLOB ? AND key='operation:'||json_extract(payload,'$.binding.requestId')
73
+ AND json_extract(payload,'$.binding.content.manifestSha256')=?
74
+ AND (json_extract(payload,'$.observation') IN ('succeeded','failed') OR json_extract(payload,'$.writeState')='rejected')`, 'operation:' + id + '.*', item.intent.package.content.manifestSha256);
75
+ }
76
+ return [...candidates];
77
+ }
78
+ /** Keep legacy or opaque bytes with unknown ownership. For owned package bytes,
79
+ * retain every manifest or chunk still required by any project's full request. */
80
+ export function reclaimUnreferencedPackageBlobs(sql, digests) {
81
+ if (!digests.length)
82
+ return;
83
+ const selected = JSON.stringify(digests);
84
+ sql.exec(`WITH full_requests AS MATERIALIZED (
85
+ SELECT item.value AS body FROM publishing_records AS p,json_each(p.payload,'$.requests') AS item
86
+ WHERE p.key GLOB 'project:*' AND json_extract(item.value,'$.receiptOnly') IS NOT 1
87
+ ), retained AS MATERIALIZED (
88
+ SELECT json_extract(body,'$.intent.package.content.manifestSha256') AS digest FROM full_requests
89
+ UNION SELECT json_extract(chunk.value,'$.sha256') FROM full_requests,
90
+ json_each(body,'$.files') AS file,json_each(file.value,'$.chunks') AS chunk
91
+ )
92
+ DELETE FROM publishing_blobs WHERE sha256 IN (
93
+ SELECT owner.sha256 FROM publishing_managed_blobs AS owner JOIN json_each(?) AS candidate ON candidate.value=owner.sha256
94
+ WHERE NOT EXISTS (SELECT 1 FROM retained WHERE retained.digest=owner.sha256)
95
+ )`, selected);
96
+ }
@@ -0,0 +1,12 @@
1
+ export { openPreparedPublishingPackage, publishingChunkBytes, publishingReadFileBytes } from './package.js';
2
+ export type { PublishingContentReader, PreparedPublishingPackage, PublishingPackageRecord } from './package.js';
3
+ export { createPublishingService, configurePublishingProject, createPublishingWorker } from './service.js';
4
+ export type { PublishingProjectPolicy, PublishingServiceLimits, PublishingService, PublishingClosedReleaseRetention, PublishingProjectLease, PublishingDeploymentStage, PublishingWorkerOptions, PublishingWorkerResult, } from './service.js';
5
+ export { openPublishingDurableJournal } from './journal.js';
6
+ export type { PublishingDurableStorage, PublishingDurableLimits, PublishingDispatch, PublishingQueueLease, PublishingMutationAuthority, PublishingRecordIdentity, PublishingClosedRequestReplacement, PublishingDurableJournal, } from './journal.js';
7
+ export { createPublishingDurableRuntime } from './runtime.js';
8
+ export type { PublishingDurableContext } from './runtime.js';
9
+ export { preparePublishingRelease } from './release.js';
10
+ export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
11
+ export type { PublishingActivation } from './activation.js';
12
+ export { publishingVersionRequestId } from '../shared/release-version.js';
@@ -4,3 +4,4 @@ export { openPublishingDurableJournal } from './journal.js';
4
4
  export { createPublishingDurableRuntime } from './runtime.js';
5
5
  export { preparePublishingRelease } from './release.js';
6
6
  export { createPublishingActivation, verifyPublishingActivation } from './activation.js';
7
+ export { publishingVersionRequestId } from '../shared/release-version.js';