@vmz/vmz 0.0.3 → 0.0.4

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.
@@ -0,0 +1,337 @@
1
+ /**
2
+ * A3 filesystem release packaging — digests, atomic pointer, rollback, artifact diff.
3
+ *
4
+ * Not the full CDN/StaticDelivery matrix. Same VPG build (`dist/`) is packed into
5
+ * `_vmz/*` manifests + content digests; publish retains previous release for rollback
6
+ * without rebuild.
7
+ */
8
+ // @ts-nocheck
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ export const RELEASE_ENVELOPE_SCHEMA = 'vmz.release.envelope.v0';
13
+ export const APPLICATION_ARTIFACT_SCHEMA = 'vmz.application.artifact.v0';
14
+ export const DELIVERY_ARTIFACT_MANIFEST_SCHEMA = 'vmz.profile.delivery_artifact_manifest.v0';
15
+ export const ROUTE_REALIZATION_TABLE_SCHEMA = 'vmz.profile.route_realization_table.v0';
16
+ export const ARTIFACT_DIFF_SCHEMA = 'vmz.artifact.diff.v0';
17
+ /**
18
+ * @param {Buffer | string} data
19
+ */
20
+ export function sha256Hex(data) {
21
+ return crypto.createHash('sha256').update(data).digest('hex');
22
+ }
23
+ /**
24
+ * @param {string} filePath
25
+ */
26
+ export function sha256File(filePath) {
27
+ return sha256Hex(fs.readFileSync(filePath));
28
+ }
29
+ /**
30
+ * @param {unknown} value
31
+ */
32
+ export function canonicalJson(value) {
33
+ return JSON.stringify(sortKeys(value));
34
+ }
35
+ /**
36
+ * @param {unknown} value
37
+ * @returns {unknown}
38
+ */
39
+ function sortKeys(value) {
40
+ if (Array.isArray(value))
41
+ return value.map(sortKeys);
42
+ if (value && typeof value === 'object') {
43
+ /** @type {Record<string, unknown>} */
44
+ const out = {};
45
+ for (const k of Object.keys(value).sort()) {
46
+ out[k] = sortKeys(/** @type {Record<string, unknown>} */ (value)[k]);
47
+ }
48
+ return out;
49
+ }
50
+ return value;
51
+ }
52
+ /**
53
+ * @param {string} distDir
54
+ * @returns {string[]}
55
+ */
56
+ function listContentFiles(distDir) {
57
+ /** @type {string[]} */
58
+ const out = [];
59
+ const skipDir = new Set(['_vmz', 'node_modules']);
60
+ const skipName = new Set(['vmz-serve-host.mjs', 'vmz-serve-host.js']);
61
+ /** @param {string} abs */
62
+ /** @param {string} rel */
63
+ function walk(abs, rel) {
64
+ let ents;
65
+ try {
66
+ ents = fs.readdirSync(abs, { withFileTypes: true });
67
+ }
68
+ catch {
69
+ return;
70
+ }
71
+ for (const e of ents) {
72
+ if (e.name.startsWith('.'))
73
+ continue;
74
+ const nextAbs = path.join(abs, e.name);
75
+ const nextRel = rel ? `${rel}/${e.name}` : e.name;
76
+ if (e.isDirectory()) {
77
+ if (skipDir.has(e.name))
78
+ continue;
79
+ walk(nextAbs, nextRel);
80
+ continue;
81
+ }
82
+ if (skipName.has(e.name))
83
+ continue;
84
+ out.push(nextRel.replace(/\\/g, '/'));
85
+ }
86
+ }
87
+ walk(distDir, '');
88
+ out.sort();
89
+ return out;
90
+ }
91
+ /**
92
+ * @param {string} chunkId
93
+ */
94
+ function pathPatternFromChunk(chunkId) {
95
+ const rel = chunkId.replace(/^pages\//, '');
96
+ const parts = rel.split('/').filter(Boolean);
97
+ const segs = [];
98
+ for (let i = 0; i < parts.length; i++) {
99
+ const p = parts[i];
100
+ if (p === 'index' && i === parts.length - 1)
101
+ continue;
102
+ segs.push(p);
103
+ }
104
+ return segs.length ? `/${segs.join('/')}` : '/';
105
+ }
106
+ /**
107
+ * Pack `dist/` into `_vmz` manifests + release envelope (filesystem Delivery Profile).
108
+ * @param {string} distDir
109
+ * @param {{ applicationId?: string }} [opts]
110
+ */
111
+ export function packRelease(distDir, opts = {}) {
112
+ const abs = path.resolve(distDir);
113
+ if (!fs.existsSync(abs)) {
114
+ throw new Error(`packRelease: missing dist ${abs}`);
115
+ }
116
+ const deploymentPath = path.join(abs, 'vmz-deployment.json');
117
+ if (!fs.existsSync(deploymentPath)) {
118
+ throw new Error(`packRelease: missing ${deploymentPath}`);
119
+ }
120
+ const deployment = JSON.parse(fs.readFileSync(deploymentPath, 'utf8'));
121
+ const files = listContentFiles(abs);
122
+ /** @type {Record<string, string>} */
123
+ const fileDigests = {};
124
+ for (const rel of files) {
125
+ fileDigests[rel] = sha256File(path.join(abs, ...rel.split('/')));
126
+ }
127
+ const pages = (deployment.units || []).filter((u) => u.kind === 'page');
128
+ const routeRealization = {
129
+ schema: ROUTE_REALIZATION_TABLE_SCHEMA,
130
+ routes: pages.map((u) => ({
131
+ routeId: String(u.chunkId),
132
+ chunkId: String(u.chunkId),
133
+ pathPattern: pathPatternFromChunk(String(u.chunkId)),
134
+ clientEntry: u.clientEntry || null,
135
+ programIr: u.programIr || null,
136
+ })),
137
+ };
138
+ const programParts = pages
139
+ .map((u) => u.programIr)
140
+ .filter(Boolean)
141
+ .map((rel) => fileDigests[String(rel).replace(/\\/g, '/')] || '')
142
+ .filter(Boolean)
143
+ .sort();
144
+ const programDigest = sha256Hex(programParts.join('|'));
145
+ const styleDigest = typeof deployment.styleBundleHash === 'string' && deployment.styleBundleHash ? deployment.styleBundleHash : null;
146
+ const deploymentDigest = fileDigests['vmz-deployment.json'] || sha256File(deploymentPath);
147
+ const applicationId = opts.applicationId || 'production-router';
148
+ const applicationArtifact = {
149
+ schema: APPLICATION_ARTIFACT_SCHEMA,
150
+ applicationId,
151
+ deliveryProfile: 'filesystem',
152
+ programDigest,
153
+ planDigest: programDigest,
154
+ deploymentDigest,
155
+ styleDigest,
156
+ routeDigest: sha256Hex(canonicalJson(routeRealization)),
157
+ fileDigests,
158
+ publicRouteContracts: routeRealization.routes.map((r) => r.routeId),
159
+ };
160
+ applicationArtifact.integrity = sha256Hex(canonicalJson({ ...applicationArtifact, integrity: undefined }));
161
+ const deliveryManifest = {
162
+ schema: DELIVERY_ARTIFACT_MANIFEST_SCHEMA,
163
+ deliveryProfile: 'filesystem',
164
+ copiesSemanticIr: false,
165
+ applicationId,
166
+ applicationIntegrity: applicationArtifact.integrity,
167
+ routeCount: routeRealization.routes.length,
168
+ assetCount: Object.keys(fileDigests).length,
169
+ styleDigest,
170
+ deploymentDigest,
171
+ };
172
+ const envelopeBody = {
173
+ schema: RELEASE_ENVELOPE_SCHEMA,
174
+ applicationId,
175
+ deliveryProfile: 'filesystem',
176
+ applicationIntegrity: applicationArtifact.integrity,
177
+ deploymentDigest,
178
+ programDigest,
179
+ styleDigest,
180
+ routeDigest: applicationArtifact.routeDigest,
181
+ fileDigests,
182
+ manifests: {
183
+ applicationArtifact: '_vmz/application-artifact.json',
184
+ deliveryArtifactManifest: '_vmz/delivery-artifact-manifest.json',
185
+ routeRealization: '_vmz/route-realization.json',
186
+ },
187
+ };
188
+ const artifactDigest = sha256Hex(canonicalJson(envelopeBody));
189
+ const envelope = { ...envelopeBody, artifactDigest };
190
+ const vmzDir = path.join(abs, '_vmz');
191
+ fs.mkdirSync(vmzDir, { recursive: true });
192
+ writeJson(path.join(vmzDir, 'application-artifact.json'), applicationArtifact);
193
+ writeJson(path.join(vmzDir, 'delivery-artifact-manifest.json'), deliveryManifest);
194
+ writeJson(path.join(vmzDir, 'route-realization.json'), routeRealization);
195
+ writeJson(path.join(vmzDir, 'release-envelope.json'), envelope);
196
+ return envelope;
197
+ }
198
+ /**
199
+ * @param {string} file
200
+ * @param {unknown} value
201
+ */
202
+ function writeJson(file, value) {
203
+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
204
+ }
205
+ /**
206
+ * @param {string} pointerPath
207
+ * @param {string} digest
208
+ */
209
+ export function atomicWritePointer(pointerPath, digest) {
210
+ const dir = path.dirname(pointerPath);
211
+ fs.mkdirSync(dir, { recursive: true });
212
+ const tmp = `${pointerPath}.${process.pid}.${Date.now()}.tmp`;
213
+ fs.writeFileSync(tmp, `${digest.trim()}\n`, 'utf8');
214
+ try {
215
+ fs.renameSync(tmp, pointerPath);
216
+ }
217
+ catch {
218
+ if (fs.existsSync(pointerPath))
219
+ fs.unlinkSync(pointerPath);
220
+ fs.renameSync(tmp, pointerPath);
221
+ }
222
+ }
223
+ /**
224
+ * @param {string} pointerPath
225
+ * @returns {string | null}
226
+ */
227
+ export function readPointer(pointerPath) {
228
+ if (!fs.existsSync(pointerPath))
229
+ return null;
230
+ const t = fs.readFileSync(pointerPath, 'utf8').trim();
231
+ return t || null;
232
+ }
233
+ /**
234
+ * Publish packed dist into releases root; retain previous pointer for rollback.
235
+ * @param {string} releasesRoot
236
+ * @param {string} distDir
237
+ * @param {ReturnType<typeof packRelease>} envelope
238
+ */
239
+ export function publishRelease(releasesRoot, distDir, envelope) {
240
+ const digest = envelope.artifactDigest;
241
+ if (!digest)
242
+ throw new Error('publishRelease: envelope missing artifactDigest');
243
+ const root = path.resolve(releasesRoot);
244
+ const dest = path.join(root, digest);
245
+ fs.mkdirSync(dest, { recursive: true });
246
+ // Immutable snapshot of packed dist (exclude prior releases nesting).
247
+ const destDist = path.join(dest, 'dist');
248
+ fs.rmSync(destDist, { recursive: true, force: true });
249
+ fs.cpSync(path.resolve(distDir), destDist, {
250
+ recursive: true,
251
+ filter: (src) => {
252
+ const n = src.replace(/\\/g, '/');
253
+ return !n.includes('/.vmz-releases/') && !n.includes('/dist/releases');
254
+ },
255
+ });
256
+ writeJson(path.join(dest, 'envelope.json'), envelope);
257
+ const currentPath = path.join(root, 'CURRENT');
258
+ const previousPath = path.join(root, 'PREVIOUS');
259
+ const prev = readPointer(currentPath);
260
+ if (prev && prev !== digest) {
261
+ atomicWritePointer(previousPath, prev);
262
+ }
263
+ atomicWritePointer(currentPath, digest);
264
+ return {
265
+ digest,
266
+ previous: prev && prev !== digest ? prev : readPointer(previousPath),
267
+ currentPath,
268
+ releaseDir: dest,
269
+ };
270
+ }
271
+ /**
272
+ * Rollback CURRENT → PREVIOUS without rebuild.
273
+ * @param {string} releasesRoot
274
+ */
275
+ export function rollbackRelease(releasesRoot) {
276
+ const root = path.resolve(releasesRoot);
277
+ const currentPath = path.join(root, 'CURRENT');
278
+ const previousPath = path.join(root, 'PREVIOUS');
279
+ const current = readPointer(currentPath);
280
+ const previous = readPointer(previousPath);
281
+ if (!previous) {
282
+ throw new Error('rollbackRelease: no PREVIOUS pointer');
283
+ }
284
+ if (!fs.existsSync(path.join(root, previous, 'envelope.json'))) {
285
+ throw new Error(`rollbackRelease: missing retained release ${previous}`);
286
+ }
287
+ if (current) {
288
+ atomicWritePointer(previousPath, current);
289
+ }
290
+ atomicWritePointer(currentPath, previous);
291
+ return {
292
+ restored: previous,
293
+ demoted: current,
294
+ releaseDir: path.join(root, previous),
295
+ };
296
+ }
297
+ /**
298
+ * Structured diff between two release envelopes / digest maps.
299
+ * @param {{ fileDigests?: Record<string, string>, artifactDigest?: string }} a
300
+ * @param {{ fileDigests?: Record<string, string>, artifactDigest?: string }} b
301
+ */
302
+ export function diffArtifacts(a, b) {
303
+ const da = a.fileDigests || {};
304
+ const db = b.fileDigests || {};
305
+ const keys = new Set([...Object.keys(da), ...Object.keys(db)]);
306
+ /** @type {string[]} */
307
+ const added = [];
308
+ /** @type {string[]} */
309
+ const removed = [];
310
+ /** @type {Array<{ path: string, before: string, after: string }>} */
311
+ const changed = [];
312
+ for (const k of [...keys].sort()) {
313
+ if (!(k in da))
314
+ added.push(k);
315
+ else if (!(k in db))
316
+ removed.push(k);
317
+ else if (da[k] !== db[k])
318
+ changed.push({ path: k, before: da[k], after: db[k] });
319
+ }
320
+ return {
321
+ schema: ARTIFACT_DIFF_SCHEMA,
322
+ beforeDigest: a.artifactDigest || null,
323
+ afterDigest: b.artifactDigest || null,
324
+ added,
325
+ removed,
326
+ changed,
327
+ identical: added.length === 0 && removed.length === 0 && changed.length === 0,
328
+ };
329
+ }
330
+ /**
331
+ * @param {string} releasesRoot
332
+ * @param {string} digest
333
+ */
334
+ export function loadReleaseEnvelope(releasesRoot, digest) {
335
+ const p = path.join(path.resolve(releasesRoot), digest, 'envelope.json');
336
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
337
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * A3-site: SiteDeliveryContract — embedded | filesystem | remote selection + release fallback.
3
+ * Authoring via defineConfig({ delivery }) / defineSite(...); pure data only.
4
+ */
5
+ export declare const SITE_DELIVERY_CONTRACT_SCHEMA = "vmz.site.delivery_contract.v0";
6
+ export declare const SITE_DELIVERY_RESOLUTION_SCHEMA = "vmz.site.delivery_resolution.v0";
7
+ /**
8
+ * Pure-data helper for `defineConfig({ delivery: defineSite(...) })`.
9
+ * Not a second config entry — CLI never auto-discovers `vmz.site.ts`.
10
+ * @param {Record<string, unknown>} delivery
11
+ */
12
+ export declare function defineSite(delivery: any): any;
13
+ /**
14
+ * Normalize authoring delivery → frozen SiteDeliveryContract.
15
+ * @param {unknown} raw
16
+ * @param {{ siteId?: string, projectRoot?: string }} [opts]
17
+ * @returns {{ ok: true, contract: Record<string, any> } | { ok: false, diagnostics: Array<{ code: string, message: string }> }}
18
+ */
19
+ export declare function normalizeSiteDelivery(raw: any, opts?: {}): {
20
+ ok: boolean;
21
+ diagnostics: any[];
22
+ contract?: undefined;
23
+ } | {
24
+ ok: boolean;
25
+ contract: {
26
+ schema: string;
27
+ schemaVersion: string;
28
+ siteId: any;
29
+ artifact: string;
30
+ expectedCompatibility: any;
31
+ sources: any[];
32
+ resolutionPolicy: {
33
+ mode: string;
34
+ fallback: any;
35
+ fileLevelMix: boolean;
36
+ };
37
+ failurePolicy: any;
38
+ updatePolicy: any;
39
+ rollbackPolicy: any;
40
+ securityPolicy: any;
41
+ activation: string;
42
+ };
43
+ diagnostics?: undefined;
44
+ };
45
+ /**
46
+ * Probe one physical source for release-level readiness (not per-URL).
47
+ * @param {{
48
+ * available?: boolean,
49
+ * artifactDigest?: string | null,
50
+ * integrityOk?: boolean,
51
+ * signatureOk?: boolean,
52
+ * objectClosureOk?: boolean,
53
+ * mixedDigestObjects?: boolean,
54
+ * error?: string | null,
55
+ * }} [probe]
56
+ */
57
+ export declare function normalizeSourceProbe(probe?: {}): {
58
+ available: boolean;
59
+ artifactDigest: any;
60
+ integrityOk: boolean;
61
+ signatureOk: boolean;
62
+ objectClosureOk: boolean;
63
+ mixedDigestObjects: boolean;
64
+ error: any;
65
+ };
66
+ /**
67
+ * Resolve one complete release per SiteDeliveryContract (no file-level mix).
68
+ * @param {Record<string, any>} contract
69
+ * @param {Record<string, ReturnType<typeof normalizeSourceProbe>>} probes by sourceId
70
+ */
71
+ export declare function resolveSiteRelease(contract: any, probes?: {}): {
72
+ schema: string;
73
+ status: string;
74
+ selectedSourceId: any;
75
+ selectedKind: any;
76
+ selectedDigest: any;
77
+ fallbackReason: string;
78
+ attempted: any[];
79
+ fileLevelMix: boolean;
80
+ activation: string;
81
+ contractDigest: any;
82
+ } | {
83
+ schema: string;
84
+ status: string;
85
+ selectedSourceId: any;
86
+ selectedKind: any;
87
+ selectedDigest: any;
88
+ fallbackReason: string;
89
+ attempted: any[];
90
+ fileLevelMix: boolean;
91
+ activation: string;
92
+ contractDigest: any;
93
+ resolutionDigest: any;
94
+ };
95
+ /**
96
+ * Read a packed release directory probe (expects _vmz/release-envelope.json + object closure).
97
+ * @param {string} releaseDir absolute path to a release snapshot (contains dist/ or is dist/)
98
+ */
99
+ export declare function probeReleaseDirectory(releaseDir: any): {
100
+ available: boolean;
101
+ artifactDigest: any;
102
+ integrityOk: boolean;
103
+ signatureOk: boolean;
104
+ objectClosureOk: boolean;
105
+ mixedDigestObjects: boolean;
106
+ error: any;
107
+ };
108
+ /**
109
+ * Emit normalized contract (+ optional resolution) under dist/_vmz.
110
+ * @param {string} outDir
111
+ * @param {unknown} deliveryRaw
112
+ * @param {{ siteId?: string, probes?: Record<string, any> }} [opts]
113
+ */
114
+ export declare function emitSiteDelivery(outDir: any, deliveryRaw: any, opts?: {}): {
115
+ contract: {
116
+ schema: string;
117
+ schemaVersion: string;
118
+ siteId: any;
119
+ artifact: string;
120
+ expectedCompatibility: any;
121
+ sources: any[];
122
+ resolutionPolicy: {
123
+ mode: string;
124
+ fallback: any;
125
+ fileLevelMix: boolean;
126
+ };
127
+ failurePolicy: any;
128
+ updatePolicy: any;
129
+ rollbackPolicy: any;
130
+ securityPolicy: any;
131
+ activation: string;
132
+ };
133
+ resolution: any;
134
+ };