@gfean/react-native-bundle-drop 0.7.0 → 0.8.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 +215 -0
- package/android/build.gradle +7 -5
- package/lib/CLI/cli.js +5 -0
- package/lib/CLI/scripts/sight-artifacts.d.ts +9 -1
- package/lib/CLI/scripts/sight-artifacts.js +20 -8
- package/lib/CLI/scripts/sight-assets.d.ts +15 -0
- package/lib/CLI/scripts/sight-assets.js +71 -0
- package/lib/CLI/scripts/sight-cli.d.ts +3 -0
- package/lib/CLI/scripts/sight-cli.js +50 -4
- package/lib/CLI/scripts/sight-compare/assets.d.ts +6 -0
- package/lib/CLI/scripts/sight-compare/assets.js +73 -0
- package/lib/CLI/scripts/sight-compare/dependencies.d.ts +22 -0
- package/lib/CLI/scripts/sight-compare/dependencies.js +289 -0
- package/lib/CLI/scripts/sight-compare/git.d.ts +22 -0
- package/lib/CLI/scripts/sight-compare/git.js +116 -0
- package/lib/CLI/scripts/sight-compare/inspect-project.d.ts +37 -0
- package/lib/CLI/scripts/sight-compare/inspect-project.js +191 -0
- package/lib/CLI/scripts/sight-compare/metadata.d.ts +4 -0
- package/lib/CLI/scripts/sight-compare/metadata.js +39 -0
- package/lib/CLI/scripts/sight-compare/process.d.ts +22 -0
- package/lib/CLI/scripts/sight-compare/process.js +221 -0
- package/lib/CLI/scripts/sight-compare/run.d.ts +3 -0
- package/lib/CLI/scripts/sight-compare/run.js +290 -0
- package/lib/CLI/scripts/sight-compare/snapshot.d.ts +26 -0
- package/lib/CLI/scripts/sight-compare/snapshot.js +279 -0
- package/lib/CLI/scripts/sight-compare/types.d.ts +87 -0
- package/lib/CLI/scripts/sight-compare/types.js +2 -0
- package/lib/CLI/scripts/sight-ota.d.ts +18 -0
- package/lib/CLI/scripts/sight-ota.js +260 -0
- package/lib/CLI/scripts/sight-session.d.ts +9 -2
- package/lib/CLI/scripts/sight-session.js +58 -20
- package/lib/scripts/bundle.d.ts +3 -0
- package/lib/scripts/bundle.js +7 -4
- package/package.json +12 -12
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.comparisonEnvironment = comparisonEnvironment;
|
|
7
|
+
exports.runSightComparison = runSightComparison;
|
|
8
|
+
const crypto_1 = require("crypto");
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
10
|
+
const os_1 = __importDefault(require("os"));
|
|
11
|
+
const path_1 = __importDefault(require("path"));
|
|
12
|
+
const prompts_1 = __importDefault(require("prompts"));
|
|
13
|
+
const chalk_1 = __importDefault(require("chalk"));
|
|
14
|
+
const logo_1 = require("../../logo");
|
|
15
|
+
const sight_artifacts_1 = require("../sight-artifacts");
|
|
16
|
+
const sight_ota_1 = require("../sight-ota");
|
|
17
|
+
const sight_session_1 = require("../sight-session");
|
|
18
|
+
const dependencies_1 = require("./dependencies");
|
|
19
|
+
const inspect_project_1 = require("./inspect-project");
|
|
20
|
+
const metadata_1 = require("./metadata");
|
|
21
|
+
const assets_1 = require("./assets");
|
|
22
|
+
const process_1 = require("./process");
|
|
23
|
+
const snapshot_1 = require("./snapshot");
|
|
24
|
+
const SIGHT_URL = 'https://bundledrop.app/sight';
|
|
25
|
+
function comparisonEnvironment(source) {
|
|
26
|
+
const env = { ...source };
|
|
27
|
+
for (const name of [
|
|
28
|
+
'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR',
|
|
29
|
+
'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'INIT_CWD', 'PWD', 'NODE_PATH',
|
|
30
|
+
])
|
|
31
|
+
delete env[name];
|
|
32
|
+
return env;
|
|
33
|
+
}
|
|
34
|
+
function configurationFingerprint(plan) {
|
|
35
|
+
const hash = (0, crypto_1.createHash)('sha256');
|
|
36
|
+
const files = new Set(plan.inputFiles);
|
|
37
|
+
for (const directory of new Set([plan.installRoot, plan.projectRoot])) {
|
|
38
|
+
for (const name of fs_1.default.readdirSync(directory)) {
|
|
39
|
+
if (/^(?:(?:metro|babel|app)\.config\.[cm]?[jt]s|bundle\.drop\.config\.js|app\.json|tsconfig\.json|\.babelrc(?:\.json|\.[cm]?js)?)$/.test(name)) {
|
|
40
|
+
const file = path_1.default.join(directory, name);
|
|
41
|
+
if (fs_1.default.statSync(file).isFile())
|
|
42
|
+
files.add(file);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
for (const file of [...files].sort()) {
|
|
47
|
+
hash.update(path_1.default.relative(plan.snapshotRoot, file).split(path_1.default.sep).join('/'));
|
|
48
|
+
hash.update('\0');
|
|
49
|
+
hash.update(fs_1.default.readFileSync(file));
|
|
50
|
+
hash.update('\0');
|
|
51
|
+
}
|
|
52
|
+
return hash.digest('hex');
|
|
53
|
+
}
|
|
54
|
+
async function selectPlatform(projectRoot, platform) {
|
|
55
|
+
if (platform)
|
|
56
|
+
return platform;
|
|
57
|
+
const available = ['ios', 'android'].filter(name => fs_1.default.existsSync(path_1.default.join(projectRoot, name)));
|
|
58
|
+
if (available.length === 1)
|
|
59
|
+
return available[0];
|
|
60
|
+
if (!process.stdin.isTTY)
|
|
61
|
+
throw new Error('Pass --platform ios or --platform android for noninteractive comparison.');
|
|
62
|
+
const answer = await (0, prompts_1.default)({
|
|
63
|
+
type: 'select', name: 'platform', message: 'Which platform should Sight compare?',
|
|
64
|
+
choices: [{ title: 'iOS', value: 'ios' }, { title: 'Android', value: 'android' }],
|
|
65
|
+
});
|
|
66
|
+
if (!answer.platform)
|
|
67
|
+
throw new Error('No platform was selected.');
|
|
68
|
+
return answer.platform;
|
|
69
|
+
}
|
|
70
|
+
function outputDirectory(projectRoot, requested) {
|
|
71
|
+
if (!requested)
|
|
72
|
+
return fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-comparison-'));
|
|
73
|
+
const directory = path_1.default.resolve(projectRoot, requested);
|
|
74
|
+
if (fs_1.default.existsSync(directory)) {
|
|
75
|
+
if (!fs_1.default.lstatSync(directory).isDirectory() || fs_1.default.lstatSync(directory).isSymbolicLink() || fs_1.default.readdirSync(directory).length) {
|
|
76
|
+
throw new Error('Sight comparison output must be an empty real directory.');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
else
|
|
80
|
+
fs_1.default.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
81
|
+
return directory;
|
|
82
|
+
}
|
|
83
|
+
function manualInstructions(artifacts) {
|
|
84
|
+
console.log(chalk_1.default.green(`\nComparison files: ${artifacts.outputDirectory}`));
|
|
85
|
+
console.log(` Metadata: ${artifacts.metadataPath}`);
|
|
86
|
+
console.log(` Assets: ${artifacts.assetManifestPath}`);
|
|
87
|
+
console.log(` Baseline: ${artifacts.baseline.bundlePath}`);
|
|
88
|
+
console.log(` ${artifacts.baseline.sourceMapPath}`);
|
|
89
|
+
console.log(` Current: ${artifacts.current.bundlePath}`);
|
|
90
|
+
console.log(` ${artifacts.current.sourceMapPath}`);
|
|
91
|
+
console.log(`Open ${SIGHT_URL}, choose Compare, and attach the four bundle/map files for a JavaScript-only comparison.`);
|
|
92
|
+
console.log('Git labels, build context and asset sizes are included through automatic CLI loading.');
|
|
93
|
+
}
|
|
94
|
+
async function runSightComparison(options) {
|
|
95
|
+
if (!options.compare?.trim())
|
|
96
|
+
throw new Error('--compare requires a Git ref.');
|
|
97
|
+
const projectRoot = process.cwd();
|
|
98
|
+
const platform = await selectPlatform(projectRoot, options.platform);
|
|
99
|
+
const environment = comparisonEnvironment(process.env);
|
|
100
|
+
const buildEnvironment = { ...environment, NODE_ENV: 'production', BUNDLE_DROP_OTA_BUILD: '1' };
|
|
101
|
+
const controller = new AbortController();
|
|
102
|
+
const cancel = () => controller.abort(new Error('Sight comparison cancelled.'));
|
|
103
|
+
process.once('SIGINT', cancel);
|
|
104
|
+
process.once('SIGTERM', cancel);
|
|
105
|
+
const diagnostics = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-logs-'));
|
|
106
|
+
let snapshots;
|
|
107
|
+
let artifacts;
|
|
108
|
+
let directory;
|
|
109
|
+
let complete = false;
|
|
110
|
+
let succeeded = false;
|
|
111
|
+
try {
|
|
112
|
+
console.log((0, logo_1.buildBundleDropLogo)());
|
|
113
|
+
console.log(chalk_1.default.bold.cyan('\nBundle Drop Sight — Compare'));
|
|
114
|
+
snapshots = await (0, snapshot_1.createComparisonSnapshots)({
|
|
115
|
+
projectRoot, compareRef: options.compare, fetch: options.fetch,
|
|
116
|
+
include: options.include, signal: controller.signal,
|
|
117
|
+
});
|
|
118
|
+
console.log(chalk_1.default.gray(`Baseline: ${snapshots.baselineLabel} → ${snapshots.baselineCommit}`));
|
|
119
|
+
console.log(chalk_1.default.gray(`Current: ${snapshots.currentLabel} → ${snapshots.currentCommit}${snapshots.currentDirty ? ' + working-tree changes' : ''}`));
|
|
120
|
+
console.log(chalk_1.default.gray(`Platform: ${platform} · production · minified JavaScript`));
|
|
121
|
+
console.log(chalk_1.default.gray('Metric: raw JavaScript bytes'));
|
|
122
|
+
console.log(chalk_1.default.gray('Assets: emitted file bytes, measured separately'));
|
|
123
|
+
console.log(chalk_1.default.green('✓ Captured current source files'));
|
|
124
|
+
const relativeApp = path_1.default.relative(snapshots.currentRoot, snapshots.currentProjectRoot);
|
|
125
|
+
const common = { signal: controller.signal, env: environment };
|
|
126
|
+
const plans = {
|
|
127
|
+
baseline: await (0, dependencies_1.inspectDependencyPlan)({ ...common, snapshotRoot: snapshots.baselineRoot, projectRelativePath: relativeApp }),
|
|
128
|
+
current: await (0, dependencies_1.inspectDependencyPlan)({ ...common, snapshotRoot: snapshots.currentRoot, projectRelativePath: relativeApp }),
|
|
129
|
+
};
|
|
130
|
+
const configuration = {
|
|
131
|
+
baseline: configurationFingerprint(plans.baseline),
|
|
132
|
+
current: configurationFingerprint(plans.current),
|
|
133
|
+
};
|
|
134
|
+
directory = outputDirectory(projectRoot, options.output);
|
|
135
|
+
console.log(chalk_1.default.yellow('Dependency installs may download packages and run project scripts.'));
|
|
136
|
+
for (const side of ['baseline', 'current']) {
|
|
137
|
+
await snapshots.assertIdentity();
|
|
138
|
+
await (0, dependencies_1.installDependencies)(plans[side], { ...common, logPath: path_1.default.join(diagnostics, `${side}-install.log`) });
|
|
139
|
+
await snapshots.assertIdentity();
|
|
140
|
+
console.log(chalk_1.default.green(`✓ Installed ${side} dependencies`));
|
|
141
|
+
}
|
|
142
|
+
const current = await (0, inspect_project_1.inspectSightProject)({
|
|
143
|
+
snapshotRoot: snapshots.currentRoot, projectRoot: snapshots.currentProjectRoot, platform,
|
|
144
|
+
explicitType: options.projectType, entryFile: options.entryFile,
|
|
145
|
+
}, { ...common, env: buildEnvironment });
|
|
146
|
+
const baseline = await (0, inspect_project_1.inspectSightProject)({
|
|
147
|
+
snapshotRoot: snapshots.baselineRoot, projectRoot: snapshots.baselineProjectRoot, platform,
|
|
148
|
+
explicitType: options.projectType, logicalEntry: current.entry,
|
|
149
|
+
}, { ...common, env: buildEnvironment });
|
|
150
|
+
if (baseline.projectType !== current.projectType)
|
|
151
|
+
throw new Error('Baseline and current have different project types; Sight cannot compare these builds.');
|
|
152
|
+
const inspected = { baseline, current };
|
|
153
|
+
const pairs = {};
|
|
154
|
+
const sides = {};
|
|
155
|
+
const assetEntries = {};
|
|
156
|
+
const ota = {};
|
|
157
|
+
for (const side of ['baseline', 'current']) {
|
|
158
|
+
const plan = plans[side];
|
|
159
|
+
const temp = path_1.default.join(snapshots.directory, `${side}-cache`);
|
|
160
|
+
const assetsDirectory = path_1.default.join(snapshots.directory, `${side}-assets`);
|
|
161
|
+
fs_1.default.mkdirSync(temp, { recursive: true });
|
|
162
|
+
const env = { ...buildEnvironment, TMPDIR: temp, TMP: temp, TEMP: temp };
|
|
163
|
+
await snapshots.assertIdentity();
|
|
164
|
+
pairs[side] = await (0, sight_artifacts_1.generateSightArtifacts)({
|
|
165
|
+
projectRoot: plan.projectRoot, projectType: inspected[side].projectType, platform,
|
|
166
|
+
entryFile: inspected[side].resolvedEntryFile, output: path_1.default.join(directory, side),
|
|
167
|
+
sourceMapRoot: plan.snapshotRoot,
|
|
168
|
+
assetsDirectory,
|
|
169
|
+
runCommand: async (cwd, command, args) => {
|
|
170
|
+
await (0, process_1.runComparisonProcess)({
|
|
171
|
+
command: process.execPath, args: [command, ...args], cwd, env,
|
|
172
|
+
phase: `Build ${side}`, signal: controller.signal,
|
|
173
|
+
logPath: path_1.default.join(diagnostics, `${side}-build.log`),
|
|
174
|
+
});
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
await snapshots.assertIdentity();
|
|
178
|
+
if (configurationFingerprint(plan) !== configuration[side]) {
|
|
179
|
+
throw new Error(`The ${side} build modified its dependency or build configuration inputs.`);
|
|
180
|
+
}
|
|
181
|
+
assetEntries[side] = await (0, assets_1.collectComparisonAssets)(assetsDirectory, controller.signal);
|
|
182
|
+
console.log(chalk_1.default.gray(`Measuring ${side} Bundle Drop OTA archive with its JavaScript engine…`));
|
|
183
|
+
ota[side] = await (0, sight_ota_1.measureSightOta)({
|
|
184
|
+
projectRoot: plan.projectRoot, snapshotRoot: plan.snapshotRoot,
|
|
185
|
+
projectType: inspected[side].projectType, platform,
|
|
186
|
+
entryFile: inspected[side].resolvedEntryFile,
|
|
187
|
+
bundlePath: pairs[side].bundlePath, sourceMapPath: pairs[side].sourceMapPath,
|
|
188
|
+
assetsDirectory, workDirectory: snapshots.directory,
|
|
189
|
+
}, { signal: controller.signal, env, logPath: path_1.default.join(diagnostics, `${side}-ota.log`) });
|
|
190
|
+
await snapshots.assertIdentity();
|
|
191
|
+
if (configurationFingerprint(plan) !== configuration[side]) {
|
|
192
|
+
throw new Error(`The ${side} OTA measurement modified its dependency or build configuration inputs.`);
|
|
193
|
+
}
|
|
194
|
+
const measurement = ota[side];
|
|
195
|
+
console.log(measurement.status === 'available'
|
|
196
|
+
? chalk_1.default.green(`✓ ${side} Bundle Drop OTA size: ${measurement.zipBytes} bytes (${measurement.engine})`)
|
|
197
|
+
: chalk_1.default.yellow(`${side} Bundle Drop OTA size unavailable: ${measurement.reason}`));
|
|
198
|
+
fs_1.default.rmSync(assetsDirectory, { recursive: true, force: true });
|
|
199
|
+
sides[side] = {
|
|
200
|
+
label: side === 'baseline' ? snapshots.baselineLabel : snapshots.currentLabel,
|
|
201
|
+
commit: side === 'baseline' ? snapshots.baselineCommit : snapshots.currentCommit,
|
|
202
|
+
branch: side === 'current' ? snapshots.currentBranch : null,
|
|
203
|
+
dirty: side === 'current' && snapshots.currentDirty,
|
|
204
|
+
projectType: inspected[side].projectType, versions: inspected[side].versions,
|
|
205
|
+
packageManager: plan.packageManager, builtAt: new Date().toISOString(),
|
|
206
|
+
inputFingerprint: side === 'current' ? snapshots.snapshotHash : (0, crypto_1.createHash)('sha256').update(snapshots.baselineInputFingerprint).digest('hex'),
|
|
207
|
+
configFingerprint: configuration[side],
|
|
208
|
+
sourceContext: {
|
|
209
|
+
repositoryRoot: plan.snapshotRoot, projectRelativePath: relativeApp.split(path_1.default.sep).join('/'),
|
|
210
|
+
sourcesBase: inspected[side].sourceMapBase,
|
|
211
|
+
pathConvention: inspected[side].sourcePathConvention,
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
console.log(chalk_1.default.green(`✓ Generated ${side} bundle, matching source map and inventory of ${assetEntries[side].length} emitted assets`));
|
|
215
|
+
}
|
|
216
|
+
artifacts = {
|
|
217
|
+
...pairs, outputDirectory: directory, metadataPath: path_1.default.join(directory, 'comparison.json'),
|
|
218
|
+
assetManifestPath: path_1.default.join(directory, 'comparison-assets.json'),
|
|
219
|
+
};
|
|
220
|
+
(0, assets_1.writeComparisonAssetManifest)(artifacts.assetManifestPath, {
|
|
221
|
+
version: 1, metric: 'emitted-asset-bytes', ...assetEntries, ota,
|
|
222
|
+
});
|
|
223
|
+
const warnings = [
|
|
224
|
+
'Both builds use detached HEAD; original staging partitions are not reproduced.',
|
|
225
|
+
...(JSON.stringify(baseline.versions) !== JSON.stringify(current.versions) ? ['Framework or bundler versions differ between builds.'] : []),
|
|
226
|
+
...(sides.baseline.configFingerprint !== sides.current.configFingerprint ? ['Dependency or build configuration inputs differ between builds.'] : []),
|
|
227
|
+
];
|
|
228
|
+
(0, metadata_1.writeComparisonMetadata)(artifacts, {
|
|
229
|
+
version: 2, mode: 'compare', metric: 'javascript-utf8-bytes',
|
|
230
|
+
settings: { platform, dev: false, minify: true, nodeVersion: process.version, entryPoint: current.entry },
|
|
231
|
+
...sides, includedPaths: snapshots.includedPaths, warnings,
|
|
232
|
+
});
|
|
233
|
+
complete = true;
|
|
234
|
+
const shouldOpen = options.open !== false && process.stdin.isTTY && (await (0, prompts_1.default)({
|
|
235
|
+
type: 'confirm', name: 'openSight', message: 'Open Bundle Drop Sight and start the local comparison?', initial: true,
|
|
236
|
+
})).openSight === true;
|
|
237
|
+
controller.signal.throwIfAborted();
|
|
238
|
+
if (!shouldOpen) {
|
|
239
|
+
manualInstructions(artifacts);
|
|
240
|
+
succeeded = true;
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const session = await (0, sight_session_1.startSightSession)({
|
|
244
|
+
comparison: artifacts, sightPageUrl: process.env.BUNDLE_DROP_SIGHT_URL || SIGHT_URL, signal: controller.signal,
|
|
245
|
+
});
|
|
246
|
+
try {
|
|
247
|
+
try {
|
|
248
|
+
await (0, sight_session_1.openSightInBrowser)(session.sightUrl);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
console.log(chalk_1.default.yellow(`Open this one-time URL manually:\n${session.sightUrl}`));
|
|
252
|
+
}
|
|
253
|
+
await session.waitForTransfer();
|
|
254
|
+
console.log(chalk_1.default.green('✓ Comparison files loaded into Sight'));
|
|
255
|
+
if (!options.keep && !options.output)
|
|
256
|
+
fs_1.default.rmSync(directory, { recursive: true, force: true });
|
|
257
|
+
else
|
|
258
|
+
manualInstructions(artifacts);
|
|
259
|
+
}
|
|
260
|
+
finally {
|
|
261
|
+
await session.close();
|
|
262
|
+
}
|
|
263
|
+
succeeded = true;
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (complete && artifacts)
|
|
267
|
+
manualInstructions(artifacts);
|
|
268
|
+
console.error(`Comparison diagnostics: ${diagnostics}`);
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
finally {
|
|
272
|
+
process.removeListener('SIGINT', cancel);
|
|
273
|
+
process.removeListener('SIGTERM', cancel);
|
|
274
|
+
try {
|
|
275
|
+
await snapshots?.cleanup();
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
const message = `Could not remove comparison worktrees at ${snapshots?.directory}: ${String(error)}`;
|
|
279
|
+
console.error(message);
|
|
280
|
+
if (succeeded) {
|
|
281
|
+
console.error(`Comparison diagnostics: ${diagnostics}`);
|
|
282
|
+
throw new Error(message);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (!complete && directory && !options.output)
|
|
286
|
+
fs_1.default.rmSync(directory, { recursive: true, force: true });
|
|
287
|
+
if (succeeded)
|
|
288
|
+
fs_1.default.rmSync(diagnostics, { recursive: true, force: true });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type ComparisonSnapshotOptions = {
|
|
2
|
+
projectRoot: string;
|
|
3
|
+
compareRef: string;
|
|
4
|
+
fetch?: boolean;
|
|
5
|
+
include?: string[];
|
|
6
|
+
signal?: AbortSignal;
|
|
7
|
+
};
|
|
8
|
+
export type ComparisonSnapshots = {
|
|
9
|
+
directory: string;
|
|
10
|
+
currentRoot: string;
|
|
11
|
+
baselineRoot: string;
|
|
12
|
+
currentProjectRoot: string;
|
|
13
|
+
baselineProjectRoot: string;
|
|
14
|
+
currentCommit: string;
|
|
15
|
+
baselineCommit: string;
|
|
16
|
+
currentLabel: string;
|
|
17
|
+
baselineLabel: string;
|
|
18
|
+
currentBranch: string | null;
|
|
19
|
+
currentDirty: boolean;
|
|
20
|
+
snapshotHash: string;
|
|
21
|
+
baselineInputFingerprint: string;
|
|
22
|
+
includedPaths: string[];
|
|
23
|
+
assertIdentity: () => Promise<void>;
|
|
24
|
+
cleanup: () => Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
export declare function createComparisonSnapshots(options: ComparisonSnapshotOptions): Promise<ComparisonSnapshots>;
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.createComparisonSnapshots = createComparisonSnapshots;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const os_1 = __importDefault(require("os"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const crypto_1 = require("crypto");
|
|
11
|
+
const git_1 = require("./git");
|
|
12
|
+
const process_1 = require("./process");
|
|
13
|
+
function isWithin(root, candidate) {
|
|
14
|
+
const relative = path_1.default.relative(root, candidate);
|
|
15
|
+
return relative !== '..' && !relative.startsWith(`..${path_1.default.sep}`) && !path_1.default.isAbsolute(relative);
|
|
16
|
+
}
|
|
17
|
+
function baselineLinkTarget(repositoryRoot, baselineRoot, link) {
|
|
18
|
+
if (isWithin(repositoryRoot, link))
|
|
19
|
+
return path_1.default.join(baselineRoot, path_1.default.relative(repositoryRoot, link));
|
|
20
|
+
// Recognize repository aliases (for example /var on macOS) without resolving
|
|
21
|
+
// the target against current files: it may exist only in the baseline.
|
|
22
|
+
let ancestor = path_1.default.dirname(link);
|
|
23
|
+
while (true) {
|
|
24
|
+
if (fs_1.default.existsSync(ancestor) && fs_1.default.realpathSync(ancestor) === repositoryRoot) {
|
|
25
|
+
return path_1.default.join(baselineRoot, path_1.default.relative(ancestor, link));
|
|
26
|
+
}
|
|
27
|
+
const parent = path_1.default.dirname(ancestor);
|
|
28
|
+
if (parent === ancestor)
|
|
29
|
+
return undefined;
|
|
30
|
+
ancestor = parent;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function forbiddenPath(name) {
|
|
34
|
+
const parts = name.split('/');
|
|
35
|
+
return parts.some(part => part === '.git' || part === 'node_modules' || part === '.pnp.cjs' || part === '.pnp.loader.mjs') ||
|
|
36
|
+
/(^|\/)\.bundle-drop\/sight(?:\/|$)/.test(name) ||
|
|
37
|
+
/(^|\/)\.yarn\/(?:install-state\.gz|unplugged)(?:\/|$)/.test(name);
|
|
38
|
+
}
|
|
39
|
+
function parseTree(output) {
|
|
40
|
+
return output.split('\0').filter(Boolean).map(line => {
|
|
41
|
+
const separator = line.indexOf('\t');
|
|
42
|
+
return { mode: line.slice(0, 6), name: line.slice(separator + 1) };
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function relevantToApp(name, appRelativePath) {
|
|
46
|
+
if (!appRelativePath)
|
|
47
|
+
return true;
|
|
48
|
+
const app = appRelativePath.split(path_1.default.sep).join('/');
|
|
49
|
+
return name === app || name.startsWith(`${app}/`) || app.startsWith(`${name}/`);
|
|
50
|
+
}
|
|
51
|
+
function validateTree(entries, appRelativePath) {
|
|
52
|
+
for (const entry of entries) {
|
|
53
|
+
if (entry.name.split('/').includes('node_modules')) {
|
|
54
|
+
throw new Error('Tracked node_modules are not supported by Sight comparison.');
|
|
55
|
+
}
|
|
56
|
+
if (entry.mode === '160000' && relevantToApp(entry.name, appRelativePath)) {
|
|
57
|
+
throw new Error(`Sight comparison cannot build Git submodule "${entry.name}". Use a project with its build inputs in this repository.`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function checkFilters(root, names, signal) {
|
|
62
|
+
if (!names.length)
|
|
63
|
+
return;
|
|
64
|
+
const attributes = (await (0, git_1.runComparisonGit)(root, ['check-attr', '--cached', '-z', '--stdin', 'filter'], signal, undefined, `${names.join('\0')}\0`)).split('\0');
|
|
65
|
+
for (let index = 0; index + 2 < attributes.length; index += 3) {
|
|
66
|
+
if (attributes[index + 2] !== 'unspecified' && attributes[index + 2] !== 'unset') {
|
|
67
|
+
throw new Error(`Sight comparison does not support Git LFS or checkout filters: ${attributes[index]}. Sight cannot establish that this path is unrelated before executing build configuration. Use a checkout without Git-filtered inputs.`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function includeFiles(repositoryRoot, projectRoot, includes) {
|
|
72
|
+
const files = new Set();
|
|
73
|
+
const visit = (absolute) => {
|
|
74
|
+
const name = path_1.default.relative(repositoryRoot, absolute).split(path_1.default.sep).join('/');
|
|
75
|
+
const dependencyInputs = ['package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'bun.lock', 'bun.lockb'];
|
|
76
|
+
if (!isWithin(repositoryRoot, absolute) || !name || forbiddenPath(name) || dependencyInputs.includes(path_1.default.basename(name))) {
|
|
77
|
+
throw new Error(`Unsafe --include path: ${name || '.'}. Choose source/configuration files inside the repository.`);
|
|
78
|
+
}
|
|
79
|
+
const stat = fs_1.default.lstatSync(absolute);
|
|
80
|
+
if (stat.isDirectory()) {
|
|
81
|
+
for (const child of fs_1.default.readdirSync(absolute).sort())
|
|
82
|
+
visit(path_1.default.join(absolute, child));
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
files.add(name);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
for (const input of includes) {
|
|
89
|
+
if (!input.trim() || path_1.default.isAbsolute(input))
|
|
90
|
+
throw new Error('--include requires a relative file or directory inside the repository.');
|
|
91
|
+
visit(path_1.default.resolve(projectRoot, input));
|
|
92
|
+
}
|
|
93
|
+
return [...files].sort();
|
|
94
|
+
}
|
|
95
|
+
function copyFiles(repositoryRoot, names, destination, signal) {
|
|
96
|
+
const files = [];
|
|
97
|
+
for (const name of names) {
|
|
98
|
+
(0, process_1.checkComparisonAbort)(signal);
|
|
99
|
+
const source = path_1.default.join(repositoryRoot, name);
|
|
100
|
+
if (!isWithin(repositoryRoot, source) || forbiddenPath(name))
|
|
101
|
+
throw new Error(`Unsafe snapshot path: ${name}.`);
|
|
102
|
+
let stat;
|
|
103
|
+
try {
|
|
104
|
+
stat = fs_1.default.lstatSync(source);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
if (['ENOENT', 'ENOTDIR'].includes(error.code))
|
|
108
|
+
continue;
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
// Cached Git paths can remain after an unstaged file/directory replacement.
|
|
112
|
+
// The untracked listing supplies the replacement files separately.
|
|
113
|
+
if (stat.isDirectory())
|
|
114
|
+
continue;
|
|
115
|
+
if (!isWithin(repositoryRoot, fs_1.default.realpathSync(path_1.default.dirname(source)))) {
|
|
116
|
+
throw new Error(`Snapshot input escapes the repository through a symlink: ${name}.`);
|
|
117
|
+
}
|
|
118
|
+
const target = destination && path_1.default.join(destination, name);
|
|
119
|
+
if (target)
|
|
120
|
+
fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
|
|
121
|
+
const mode = stat.mode & 0o777;
|
|
122
|
+
if (stat.isSymbolicLink()) {
|
|
123
|
+
const originalLink = fs_1.default.readlinkSync(source);
|
|
124
|
+
const resolved = fs_1.default.realpathSync(path_1.default.resolve(path_1.default.dirname(source), originalLink));
|
|
125
|
+
if (!isWithin(repositoryRoot, resolved)) {
|
|
126
|
+
throw new Error(`External symlink is not supported by Sight comparison: ${name}.`);
|
|
127
|
+
}
|
|
128
|
+
const link = path_1.default.isAbsolute(originalLink) ? path_1.default.relative(path_1.default.dirname(source), resolved) : originalLink;
|
|
129
|
+
if (target)
|
|
130
|
+
fs_1.default.symlinkSync(link, target, fs_1.default.statSync(resolved).isDirectory() ? 'dir' : 'file');
|
|
131
|
+
files.push({ name, mode, link, hash: (0, crypto_1.createHash)('sha256').update(link).digest('hex') });
|
|
132
|
+
}
|
|
133
|
+
else if (stat.isFile()) {
|
|
134
|
+
const content = fs_1.default.readFileSync(source);
|
|
135
|
+
if (content.subarray(0, 80).toString().startsWith('version https://git-lfs.github.com/spec/v1\n')) {
|
|
136
|
+
throw new Error(`Git LFS pointer cannot be bundled: ${name}. Sight cannot establish that this path is unrelated before executing build configuration.`);
|
|
137
|
+
}
|
|
138
|
+
if (target) {
|
|
139
|
+
fs_1.default.writeFileSync(target, content, { mode });
|
|
140
|
+
fs_1.default.chmodSync(target, mode);
|
|
141
|
+
}
|
|
142
|
+
files.push({ name, mode, hash: (0, crypto_1.createHash)('sha256').update(content).digest('hex') });
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
throw new Error(`Snapshot input must be a regular file or internal symlink: ${name}.`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return files;
|
|
149
|
+
}
|
|
150
|
+
function fingerprint(files) {
|
|
151
|
+
return (0, crypto_1.createHash)('sha256').update(JSON.stringify(files)).digest('hex');
|
|
152
|
+
}
|
|
153
|
+
function verifyCopiedLinks(root, files) {
|
|
154
|
+
for (const file of files) {
|
|
155
|
+
if (file.link !== undefined && !fs_1.default.existsSync(path_1.default.join(root, file.name))) {
|
|
156
|
+
throw new Error(`Symlink target was not captured: ${file.name}. Include its ignored target explicitly with --include.`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function createComparisonSnapshots(options) {
|
|
161
|
+
const { compareRef, signal, include = [] } = options;
|
|
162
|
+
const projectRoot = fs_1.default.realpathSync(options.projectRoot);
|
|
163
|
+
const repository = await (0, git_1.inspectComparisonRepository)(projectRoot, compareRef, options);
|
|
164
|
+
const { repositoryRoot, appRelativePath, currentCommit, baselineCommit } = repository;
|
|
165
|
+
const baselineTree = parseTree(await (0, git_1.runComparisonGit)(repositoryRoot, ['ls-tree', '-rz', baselineCommit], signal));
|
|
166
|
+
const currentIndex = parseTree(await (0, git_1.runComparisonGit)(repositoryRoot, ['ls-files', '--stage', '-z'], signal));
|
|
167
|
+
validateTree(currentIndex, appRelativePath);
|
|
168
|
+
validateTree(baselineTree, appRelativePath);
|
|
169
|
+
const submodules = new Set(currentIndex.filter(entry => entry.mode === '160000').map(entry => entry.name));
|
|
170
|
+
const includedPaths = includeFiles(repositoryRoot, projectRoot, include);
|
|
171
|
+
const trackedNames = [...currentIndex, ...baselineTree].map(entry => entry.name);
|
|
172
|
+
for (const name of includedPaths) {
|
|
173
|
+
if (trackedNames.some(tracked => tracked === name || tracked.startsWith(`${name}/`) || name.startsWith(`${tracked}/`))) {
|
|
174
|
+
throw new Error(`--include cannot overwrite a tracked input on either side: ${name}.`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
const listCurrent = async () => {
|
|
178
|
+
const output = await (0, git_1.runComparisonGit)(repositoryRoot, ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], signal);
|
|
179
|
+
return [...new Set([...output.split('\0').filter(name => name && !forbiddenPath(name) && !submodules.has(name)), ...includeFiles(repositoryRoot, projectRoot, include)])].sort();
|
|
180
|
+
};
|
|
181
|
+
const directory = fs_1.default.realpathSync(fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'bundle-drop-sight-compare-')));
|
|
182
|
+
const frozenRoot = path_1.default.join(directory, 'frozen');
|
|
183
|
+
const privateGit = path_1.default.join(directory, 'repository.git');
|
|
184
|
+
const currentRoot = path_1.default.join(directory, 'current');
|
|
185
|
+
const baselineRoot = path_1.default.join(directory, 'baseline');
|
|
186
|
+
const worktrees = [];
|
|
187
|
+
const disabledHooks = path_1.default.join(directory, 'disabled-hooks');
|
|
188
|
+
const cleanup = async () => {
|
|
189
|
+
if (!fs_1.default.existsSync(directory))
|
|
190
|
+
return;
|
|
191
|
+
for (const root of worktrees) {
|
|
192
|
+
// Even a project hook that changes private Git config cannot strand original worktrees.
|
|
193
|
+
try {
|
|
194
|
+
await (0, git_1.runComparisonGit)(privateGit, ['worktree', 'remove', '--force', root]);
|
|
195
|
+
}
|
|
196
|
+
catch { /* Remove the owned repository below. */ }
|
|
197
|
+
}
|
|
198
|
+
fs_1.default.rmSync(directory, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
199
|
+
};
|
|
200
|
+
try {
|
|
201
|
+
fs_1.default.mkdirSync(frozenRoot);
|
|
202
|
+
fs_1.default.mkdirSync(disabledHooks);
|
|
203
|
+
const names = await listCurrent();
|
|
204
|
+
const files = copyFiles(repositoryRoot, names, frozenRoot, signal);
|
|
205
|
+
const snapshotHash = fingerprint(files);
|
|
206
|
+
if (snapshotHash !== fingerprint(copyFiles(repositoryRoot, await listCurrent(), undefined, signal)) ||
|
|
207
|
+
repository.indexFingerprint !== await (0, git_1.comparisonIndexFingerprint)(repositoryRoot, signal) ||
|
|
208
|
+
currentCommit !== (await (0, git_1.runComparisonGit)(repositoryRoot, ['rev-parse', 'HEAD'], signal)).trim()) {
|
|
209
|
+
throw new Error('Working tree changed while Sight captured it; retry when edits settle.');
|
|
210
|
+
}
|
|
211
|
+
verifyCopiedLinks(frozenRoot, files);
|
|
212
|
+
await (0, git_1.runComparisonGit)(repositoryRoot, ['clone', '--mirror', '--no-hardlinks', '--dissociate', '--origin', 'sight-source', '--', repositoryRoot, privateGit], signal);
|
|
213
|
+
// Keep mirrored refs for versioning tools without leaving a build a remote back to the original checkout.
|
|
214
|
+
await (0, git_1.runComparisonGit)(privateGit, ['config', '--local', '--remove-section', 'remote.sight-source'], signal);
|
|
215
|
+
const checkoutSettings = await (0, git_1.runComparisonGit)(repositoryRoot, ['config', '--get-regexp', '^core[.](autocrlf|eol|filemode|symlinks)$'], signal, [0, 1]);
|
|
216
|
+
for (const setting of checkoutSettings.trim().split('\n').filter(Boolean)) {
|
|
217
|
+
const separator = setting.indexOf(' ');
|
|
218
|
+
await (0, git_1.runComparisonGit)(privateGit, ['config', '--local', setting.slice(0, separator), setting.slice(separator + 1)], signal);
|
|
219
|
+
}
|
|
220
|
+
if (await (0, git_1.comparisonRefs)(privateGit, signal) !== repository.refs)
|
|
221
|
+
throw new Error('Git refs changed while Sight captured the repository; retry.');
|
|
222
|
+
await (0, git_1.runComparisonGit)(privateGit, ['cat-file', '-e', `${currentCommit}^{commit}`], signal);
|
|
223
|
+
await (0, git_1.runComparisonGit)(privateGit, ['cat-file', '-e', `${baselineCommit}^{commit}`], signal);
|
|
224
|
+
for (const [root, commit] of [[baselineRoot, baselineCommit], [currentRoot, currentCommit]]) {
|
|
225
|
+
await (0, git_1.runComparisonGit)(privateGit, ['-c', `core.hooksPath=${disabledHooks}`, 'worktree', 'add', '--detach', '--no-checkout', root, commit], signal);
|
|
226
|
+
worktrees.push(root);
|
|
227
|
+
await (0, git_1.runComparisonGit)(root, ['read-tree', commit], signal);
|
|
228
|
+
const tree = parseTree(await (0, git_1.runComparisonGit)(root, ['ls-files', '--stage', '-z'], signal));
|
|
229
|
+
await checkFilters(root, tree.map(entry => entry.name), signal);
|
|
230
|
+
}
|
|
231
|
+
await (0, git_1.runComparisonGit)(baselineRoot, ['checkout-index', '--all', '--force'], signal);
|
|
232
|
+
copyFiles(frozenRoot, includedPaths, baselineRoot, signal);
|
|
233
|
+
for (const entry of baselineTree.filter(item => item.mode === '120000')) {
|
|
234
|
+
const linkPath = path_1.default.join(baselineRoot, entry.name);
|
|
235
|
+
if (!fs_1.default.lstatSync(linkPath).isSymbolicLink())
|
|
236
|
+
continue;
|
|
237
|
+
const link = fs_1.default.readlinkSync(linkPath);
|
|
238
|
+
const target = path_1.default.isAbsolute(link) ? baselineLinkTarget(repositoryRoot, baselineRoot, link) : undefined;
|
|
239
|
+
if (target !== undefined) {
|
|
240
|
+
fs_1.default.unlinkSync(linkPath);
|
|
241
|
+
// Normalize every link before validating their resolved baseline targets,
|
|
242
|
+
// so chains never follow another absolute link into the current checkout.
|
|
243
|
+
fs_1.default.symlinkSync(path_1.default.relative(path_1.default.dirname(linkPath), target), linkPath);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
copyFiles(frozenRoot, files.map(file => file.name), currentRoot, signal);
|
|
247
|
+
const baselineFiles = baselineTree.filter(entry => entry.mode !== '160000' && !forbiddenPath(entry.name)).map(entry => entry.name);
|
|
248
|
+
copyFiles(baselineRoot, baselineFiles, undefined, signal);
|
|
249
|
+
verifyCopiedLinks(baselineRoot, copyFiles(baselineRoot, [...baselineFiles, ...includedPaths], undefined, signal));
|
|
250
|
+
const currentProjectRoot = path_1.default.join(currentRoot, appRelativePath);
|
|
251
|
+
const baselineProjectRoot = path_1.default.join(baselineRoot, appRelativePath);
|
|
252
|
+
if (!fs_1.default.existsSync(path_1.default.join(baselineProjectRoot, 'package.json')))
|
|
253
|
+
throw new Error('The app package.json is missing at the baseline repository-relative path.');
|
|
254
|
+
const assertIdentity = async () => {
|
|
255
|
+
if ((await (0, git_1.runComparisonGit)(currentRoot, ['rev-parse', 'HEAD'], signal)).trim() !== currentCommit ||
|
|
256
|
+
(await (0, git_1.runComparisonGit)(baselineRoot, ['rev-parse', 'HEAD'], signal)).trim() !== baselineCommit ||
|
|
257
|
+
await (0, git_1.comparisonRefs)(privateGit, signal) !== repository.refs) {
|
|
258
|
+
throw new Error('A comparison build changed its Git HEAD or refs; refusing artifacts with altered revision identity.');
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
await assertIdentity();
|
|
262
|
+
return {
|
|
263
|
+
directory, currentRoot, baselineRoot, currentProjectRoot, baselineProjectRoot,
|
|
264
|
+
currentCommit, baselineCommit, currentLabel: repository.currentLabel, baselineLabel: repository.baselineLabel,
|
|
265
|
+
currentBranch: repository.currentBranch, currentDirty: repository.currentDirty,
|
|
266
|
+
baselineInputFingerprint: repository.baselineInputFingerprint, snapshotHash, includedPaths,
|
|
267
|
+
assertIdentity, cleanup,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
try {
|
|
272
|
+
await cleanup();
|
|
273
|
+
}
|
|
274
|
+
catch (cleanupError) {
|
|
275
|
+
throw new Error(`${error.message}\nCould not remove ${directory}: ${cleanupError.message}`);
|
|
276
|
+
}
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
279
|
+
}
|