@funnelsgrove/cli 0.1.67 → 0.1.71
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 +6 -3
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +150 -4
- package/dist/localSync.d.ts +37 -0
- package/dist/localSync.js +130 -0
- package/dist/sourceRebase.d.ts +2 -0
- package/dist/sourceRebase.js +66 -0
- package/funnel-contract-compatibility.json +46 -46
- package/package.json +4 -4
- package/template_docs/.funnelsgrove-docs.json +9 -9
- package/template_docs/docs/funnelsgrove/contracts/analytics-events.md +2 -1
- package/template_docs/docs/funnelsgrove/contracts/payments.md +6 -1
- package/template_docs/docs/funnelsgrove/migrations/step-contract-v3.md +1 -1
- package/template_docs/docs/funnelsgrove/qa/analytics.md +4 -0
- package/template_docs/docs/funnelsgrove/qa/paywall-checkout.md +3 -0
- package/template_docs/docs/funnelsgrove/steps/paywall_offer.md +4 -2
- package/template_docs/docs/funnelsgrove/steps/upsell_offer.md +3 -2
- package/template_docs/funnel-docs.config.json +1 -1
- package/template_scaffold/.funnelsgrove-docs.json +9 -9
- package/template_scaffold/.funnelsgrove-scaffold.json +16 -16
- package/template_scaffold/docs/funnelsgrove/contracts/analytics-events.md +2 -1
- package/template_scaffold/docs/funnelsgrove/contracts/payments.md +6 -1
- package/template_scaffold/docs/funnelsgrove/migrations/step-contract-v3.md +1 -1
- package/template_scaffold/docs/funnelsgrove/qa/analytics.md +4 -0
- package/template_scaffold/docs/funnelsgrove/qa/paywall-checkout.md +3 -0
- package/template_scaffold/docs/funnelsgrove/steps/paywall_offer.md +4 -2
- package/template_scaffold/docs/funnelsgrove/steps/upsell_offer.md +3 -2
- package/template_scaffold/funnel-docs.config.json +1 -1
- package/template_scaffold/package-lock.json +15 -15
- package/template_scaffold/package.json +3 -3
- package/template_scaffold/src/steps/step-32-paywall.tsx +89 -106
- package/template_scaffold/tests/funnel-agent-docs.test.ts +1 -1
- package/template_scaffold/tests/src/steps/step-32-paywall.test.ts +37 -51
package/README.md
CHANGED
|
@@ -30,9 +30,12 @@ fgrove publish --env preview
|
|
|
30
30
|
Inside a synced folder, `fgrove` reads `.funnelsgrove-sync.json` first, so you do not need to run `fgrove use` when switching between local funnel directories. Use `fgrove use` only when you want a global fallback context for commands outside a synced folder.
|
|
31
31
|
|
|
32
32
|
`fgrove sync down` refuses to overwrite local changes in an existing synced
|
|
33
|
-
folder
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
folder. If `fgrove sync up` says the remote draft changed since your local sync,
|
|
34
|
+
run `fgrove sync rebase`: it performs a three-way merge from the recorded base,
|
|
35
|
+
preserves CLI-managed files, and leaves the working tree untouched when it finds
|
|
36
|
+
conflicts. Review the merged diff, rerun `fgrove validate`, then sync up again.
|
|
37
|
+
`sync down --force` is the explicit discard path and writes an automatic source
|
|
38
|
+
backup under `.funnelsgrove/rebase-backups/` before replacing hosted paths.
|
|
36
39
|
|
|
37
40
|
`fgrove sync up` is for funnels without GitHub source sync. When GitHub is
|
|
38
41
|
connected, commit and push source changes with normal git, then run `fgrove
|
package/dist/cli.d.ts
CHANGED
|
@@ -151,7 +151,7 @@ type SyncTargetIdInput = {
|
|
|
151
151
|
};
|
|
152
152
|
type GeneratedConfigKind = 'offerSets' | 'experiments';
|
|
153
153
|
export declare const SYNC_DOWN_GENERATED_CONFIG_KINDS: GeneratedConfigKind[];
|
|
154
|
-
export declare const EXPERIMENT_TRANSACTION_RECOVERY_COMMANDS: readonly ["sync down", "sync up", "experiments sync", "offer-sets sync"];
|
|
154
|
+
export declare const EXPERIMENT_TRANSACTION_RECOVERY_COMMANDS: readonly ["sync down", "sync rebase", "sync up", "experiments sync", "offer-sets sync"];
|
|
155
155
|
export declare function resolveSyncTargetIds(input: SyncTargetIdInput): {
|
|
156
156
|
workspaceId: string;
|
|
157
157
|
funnelId?: string;
|
package/dist/cli.js
CHANGED
|
@@ -11,7 +11,8 @@ import { CURRENT_STEP_CONTRACT_VERSION, FUNNEL_CONTRACT_DIAGNOSTIC_CODES, PREVIO
|
|
|
11
11
|
import { abortFunnelSourceCandidate, beginFunnelSourceCandidate, callTrpcProcedure, createFunnelExperimentFromSpec, finalizeFunnelSourceCandidate, stageFunnelSourceCandidate, } from './apiClient.js';
|
|
12
12
|
import { cliReleaseIdentity } from './cliIdentity.js';
|
|
13
13
|
import { clearActiveContext, getDefaultAuthConfigPath, loadActiveContext, loadAuthToken, saveActiveContext, saveAuthToken, } from './authStore.js';
|
|
14
|
-
import { buildCommittedSyncManifest, buildDownloadedSyncManifest, buildSourceCandidateOperations, collectChangedSourceFiles, collectSourceSnapshot, ensureGitignore, formatSyncUploadSummary, hasLocalSourceChanges, readSyncManifest, runSyncDownLocalLifecycle, runSourceCandidateSync, writeLocalEnvFile, writeSourceFiles, writeSyncManifest, } from './localSync.js';
|
|
14
|
+
import { buildCommittedSyncManifest, buildDownloadedSyncManifest, buildSourceCandidateOperations, collectChangedSourceFiles, collectSourceFiles, collectSourceSnapshot, ensureGitignore, formatSyncUploadSummary, hasLocalSourceChanges, rebaseSourceFiles, readSyncManifest, replaceSourceFiles, runSyncDownLocalLifecycle, runSourceCandidateSync, writeLocalEnvFile, writeSourceFiles, writeSourceRebaseBackup, writeSyncManifest, } from './localSync.js';
|
|
15
|
+
import { mergeTextSourceWithGit } from './sourceRebase.js';
|
|
15
16
|
import { executeExperimentCreate, formatExperimentCreateSuccess, recoverExperimentCreateTransaction, } from './experimentCreate.js';
|
|
16
17
|
import { pullEnvFile } from './envSync.js';
|
|
17
18
|
import { formatGitHubConnectRows, formatGitHubJobRows, formatGitHubStatusRows, } from './githubOutput.js';
|
|
@@ -532,6 +533,16 @@ export const repairDownloadedManagedFiles = async (targetDir, options = {}) => {
|
|
|
532
533
|
await resolveTemplateDocsConflict(bundle, targetDir, conflict.path);
|
|
533
534
|
}
|
|
534
535
|
};
|
|
536
|
+
const loadManagedSyncPaths = async () => {
|
|
537
|
+
const docsBundle = await loadBundledDocs(resolveTemplateDocsPath());
|
|
538
|
+
const validationManifest = parseContractToolsManifest(await readFile(path.join(resolveTemplateValidationPath(), CONTRACT_TOOLS_MANIFEST_PATH)), 'FG-DOC-001');
|
|
539
|
+
return new Set([
|
|
540
|
+
'.funnelsgrove-docs.json',
|
|
541
|
+
CONTRACT_TOOLS_MANIFEST_PATH,
|
|
542
|
+
...docsBundle.files.keys(),
|
|
543
|
+
...validationManifest.managedFiles.map((file) => file.path),
|
|
544
|
+
]);
|
|
545
|
+
};
|
|
535
546
|
const MANAGED_VALIDATOR_SCRIPT = 'vite-node --config src/contract/funnel-validator.vite.config.ts src/contract/validate-funnel.cli.ts';
|
|
536
547
|
const ensureManagedValidatorPackage = async (targetDir) => {
|
|
537
548
|
const packagePath = path.join(targetDir, 'package.json');
|
|
@@ -1060,6 +1071,7 @@ const GENERATED_CONFIG_PATH_BY_KIND = {
|
|
|
1060
1071
|
export const SYNC_DOWN_GENERATED_CONFIG_KINDS = ['offerSets'];
|
|
1061
1072
|
export const EXPERIMENT_TRANSACTION_RECOVERY_COMMANDS = [
|
|
1062
1073
|
'sync down',
|
|
1074
|
+
'sync rebase',
|
|
1063
1075
|
'sync up',
|
|
1064
1076
|
'experiments sync',
|
|
1065
1077
|
'offer-sets sync',
|
|
@@ -2124,15 +2136,27 @@ addExamples(analyticsCommand
|
|
|
2124
2136
|
});
|
|
2125
2137
|
const syncCommand = addExamples(program.command('sync').description('Sync funnel source'), [
|
|
2126
2138
|
'fgrove sync down --funnel claimbee-ios --dir ./claimbee-ios',
|
|
2139
|
+
'fgrove sync rebase --dir ./claimbee-ios',
|
|
2127
2140
|
'fgrove sync up --message "Update copy"',
|
|
2128
2141
|
]);
|
|
2142
|
+
const assertHistoricalSyncBaseline = (input) => {
|
|
2143
|
+
const historical = buildDownloadedSyncManifest({
|
|
2144
|
+
workspaceId: input.manifest.workspaceId,
|
|
2145
|
+
funnelId: input.manifest.funnelId,
|
|
2146
|
+
draftVersionId: input.manifest.draftVersionId,
|
|
2147
|
+
files: input.files,
|
|
2148
|
+
});
|
|
2149
|
+
if (JSON.stringify(historical.files) !== JSON.stringify(input.manifest.files)) {
|
|
2150
|
+
throw Object.assign(new Error('The historical hosted draft no longer matches this local sync baseline. The rebase was not applied; preserve the local directory and contact FunnelsGrove support.'), { code: 'FG-SYNC-REBASE-BASE' });
|
|
2151
|
+
}
|
|
2152
|
+
};
|
|
2129
2153
|
addExamples(syncCommand
|
|
2130
2154
|
.command('down')
|
|
2131
2155
|
.description('Download funnel draft source to a local directory')
|
|
2132
2156
|
.option('--workspace <id-or-slug-or-name>', 'Workspace id, slug, or name')
|
|
2133
2157
|
.option('--funnel <id-or-slug>', 'Funnel id or slug')
|
|
2134
2158
|
.requiredOption('--dir <path>', 'Local target directory')
|
|
2135
|
-
.option('--force', '
|
|
2159
|
+
.option('--force', 'Replace hosted source paths after saving an automatic local source backup'), [
|
|
2136
2160
|
'fgrove sync down --funnel claimbee-ios --dir ./claimbee-ios',
|
|
2137
2161
|
])
|
|
2138
2162
|
.action(async (options) => {
|
|
@@ -2143,8 +2167,11 @@ addExamples(syncCommand
|
|
|
2143
2167
|
funnel: options.funnel,
|
|
2144
2168
|
dir: options.dir,
|
|
2145
2169
|
});
|
|
2146
|
-
|
|
2147
|
-
|
|
2170
|
+
const hasLocalChanges = target.manifest
|
|
2171
|
+
? await hasLocalSourceChanges(target.sourceDir, target.manifest)
|
|
2172
|
+
: false;
|
|
2173
|
+
if (!options.force && hasLocalChanges) {
|
|
2174
|
+
throw new Error('Local sync directory has unuploaded changes. Run `fgrove sync rebase --dir <path>` to preserve them, or pass `--force` only if replacing hosted source paths is intentional; force creates an automatic backup.');
|
|
2148
2175
|
}
|
|
2149
2176
|
const result = await callApi({
|
|
2150
2177
|
path: 'funnels.exportSource',
|
|
@@ -2161,6 +2188,16 @@ addExamples(syncCommand
|
|
|
2161
2188
|
draftVersionId: result.draftVersionId,
|
|
2162
2189
|
files: result.files,
|
|
2163
2190
|
});
|
|
2191
|
+
if (options.force && target.manifest && hasLocalChanges) {
|
|
2192
|
+
const localFiles = await collectSourceFiles(target.sourceDir);
|
|
2193
|
+
const backupPath = await writeSourceRebaseBackup({
|
|
2194
|
+
rootDir: target.sourceDir,
|
|
2195
|
+
files: localFiles,
|
|
2196
|
+
manifest: target.manifest,
|
|
2197
|
+
remoteDraftVersionId: result.draftVersionId,
|
|
2198
|
+
});
|
|
2199
|
+
console.log(`Saved the pre-force source backup to ${path.join(target.sourceDir, backupPath)}`);
|
|
2200
|
+
}
|
|
2164
2201
|
await mkdir(target.sourceDir, { recursive: true });
|
|
2165
2202
|
await writeSourceFiles(target.sourceDir, result.files);
|
|
2166
2203
|
const generatedFiles = await syncGeneratedConfigFilesForCli({
|
|
@@ -2189,6 +2226,115 @@ addExamples(syncCommand
|
|
|
2189
2226
|
console.log(`Synced ${result.files.length} files to ${target.sourceDir}`);
|
|
2190
2227
|
console.log(`Wrote ${formatGeneratedFileCount(generatedFiles.length)}`);
|
|
2191
2228
|
});
|
|
2229
|
+
addExamples(syncCommand
|
|
2230
|
+
.command('rebase')
|
|
2231
|
+
.description('Merge local source changes onto the latest hosted draft without discarding them')
|
|
2232
|
+
.option('--workspace <id-or-slug-or-name>', 'Workspace id, slug, or name')
|
|
2233
|
+
.option('--funnel <id-or-slug>', 'Funnel id or slug')
|
|
2234
|
+
.option('--dir <path>', 'Local funnel directory', '.'), [
|
|
2235
|
+
'fgrove sync rebase',
|
|
2236
|
+
'fgrove sync rebase --dir ./claimbee-ios',
|
|
2237
|
+
])
|
|
2238
|
+
.action(async (options) => {
|
|
2239
|
+
const token = await readAuthToken();
|
|
2240
|
+
const target = await resolveSyncTarget({
|
|
2241
|
+
token,
|
|
2242
|
+
workspace: options.workspace,
|
|
2243
|
+
funnel: options.funnel,
|
|
2244
|
+
dir: options.dir,
|
|
2245
|
+
});
|
|
2246
|
+
if (!target.manifest) {
|
|
2247
|
+
throw Object.assign(new Error('No local sync baseline found. Run `fgrove sync down` into a new directory before rebasing.'), { code: 'FG-SYNC-REBASE-BASE' });
|
|
2248
|
+
}
|
|
2249
|
+
const remote = await callApi({
|
|
2250
|
+
path: 'funnels.exportSource',
|
|
2251
|
+
type: 'query',
|
|
2252
|
+
token,
|
|
2253
|
+
data: {
|
|
2254
|
+
workspaceId: target.workspaceId,
|
|
2255
|
+
funnelId: target.funnelId,
|
|
2256
|
+
},
|
|
2257
|
+
});
|
|
2258
|
+
if (remote.draftVersionId === target.manifest.draftVersionId) {
|
|
2259
|
+
console.log(`Local source is already based on hosted draft ${remote.draftVersionId}; no rebase is needed.`);
|
|
2260
|
+
return;
|
|
2261
|
+
}
|
|
2262
|
+
const base = await callApi({
|
|
2263
|
+
path: 'funnels.exportSource',
|
|
2264
|
+
type: 'query',
|
|
2265
|
+
token,
|
|
2266
|
+
data: {
|
|
2267
|
+
workspaceId: target.workspaceId,
|
|
2268
|
+
funnelId: target.funnelId,
|
|
2269
|
+
versionId: target.manifest.draftVersionId,
|
|
2270
|
+
},
|
|
2271
|
+
});
|
|
2272
|
+
if (base.draftVersionId !== target.manifest.draftVersionId) {
|
|
2273
|
+
throw Object.assign(new Error('The hosted historical export returned the wrong sync baseline. The rebase was not applied.'), { code: 'FG-SYNC-REBASE-BASE' });
|
|
2274
|
+
}
|
|
2275
|
+
assertHistoricalSyncBaseline({ manifest: target.manifest, files: base.files });
|
|
2276
|
+
const localFiles = await collectSourceFiles(target.sourceDir);
|
|
2277
|
+
const merged = await rebaseSourceFiles({
|
|
2278
|
+
baseFiles: base.files,
|
|
2279
|
+
localFiles,
|
|
2280
|
+
remoteFiles: remote.files,
|
|
2281
|
+
remoteOwnedPaths: await loadManagedSyncPaths(),
|
|
2282
|
+
mergeText: mergeTextSourceWithGit,
|
|
2283
|
+
});
|
|
2284
|
+
if (merged.conflicts.length > 0) {
|
|
2285
|
+
const conflictLines = merged.conflicts.map((conflict) => ` ${conflict.kind.padEnd(15)} ${conflict.path}`);
|
|
2286
|
+
throw Object.assign(new Error([
|
|
2287
|
+
`Rebase found ${merged.conflicts.length} conflicting ${merged.conflicts.length === 1 ? 'path' : 'paths'}; no local files were changed.`,
|
|
2288
|
+
...conflictLines,
|
|
2289
|
+
'Resolve these paths against a fresh sync directory, or commit the local work and retry after reconciling the overlapping edits.',
|
|
2290
|
+
].join('\n')), { code: 'FG-SYNC-REBASE-CONFLICT' });
|
|
2291
|
+
}
|
|
2292
|
+
const backupPath = await writeSourceRebaseBackup({
|
|
2293
|
+
rootDir: target.sourceDir,
|
|
2294
|
+
files: localFiles,
|
|
2295
|
+
manifest: target.manifest,
|
|
2296
|
+
remoteDraftVersionId: remote.draftVersionId,
|
|
2297
|
+
});
|
|
2298
|
+
console.log(`Saved the pre-rebase source backup to ${path.join(target.sourceDir, backupPath)}`);
|
|
2299
|
+
const downloadedSyncManifest = buildDownloadedSyncManifest({
|
|
2300
|
+
workspaceId: target.workspaceId,
|
|
2301
|
+
funnelId: target.funnelId,
|
|
2302
|
+
draftVersionId: remote.draftVersionId,
|
|
2303
|
+
files: remote.files,
|
|
2304
|
+
});
|
|
2305
|
+
await replaceSourceFiles({
|
|
2306
|
+
rootDir: target.sourceDir,
|
|
2307
|
+
currentFiles: localFiles,
|
|
2308
|
+
nextFiles: merged.files,
|
|
2309
|
+
});
|
|
2310
|
+
const generatedFiles = await syncGeneratedConfigFilesForCli({
|
|
2311
|
+
token,
|
|
2312
|
+
target,
|
|
2313
|
+
kinds: SYNC_DOWN_GENERATED_CONFIG_KINDS,
|
|
2314
|
+
});
|
|
2315
|
+
await writeLocalEnvFile(target.sourceDir, remote.envFile);
|
|
2316
|
+
await ensureGitignore(target.sourceDir);
|
|
2317
|
+
await runSyncDownLocalLifecycle({
|
|
2318
|
+
recoverMigration: async () => recoverStepContractV2Migration(target.sourceDir),
|
|
2319
|
+
recoverDocs: async () => repairDownloadedManagedFiles(target.sourceDir),
|
|
2320
|
+
refreshDocs: async () => {
|
|
2321
|
+
const docs = await executeDocsCommand({
|
|
2322
|
+
targetDir: target.sourceDir,
|
|
2323
|
+
options: { json: true },
|
|
2324
|
+
});
|
|
2325
|
+
if (docs.exitCode !== 0) {
|
|
2326
|
+
const output = JSON.parse(docs.output);
|
|
2327
|
+
const diagnostic = output.diagnostics?.[0];
|
|
2328
|
+
throw new CliContractError(diagnostic?.code ?? 'FG-DOC-001', diagnostic?.message ?? 'Managed documentation refresh failed after sync rebase.');
|
|
2329
|
+
}
|
|
2330
|
+
},
|
|
2331
|
+
writeSyncState: async () => writeSyncManifest(target.sourceDir, downloadedSyncManifest),
|
|
2332
|
+
});
|
|
2333
|
+
const localChanges = await collectChangedSourceFiles(target.sourceDir, downloadedSyncManifest);
|
|
2334
|
+
console.log(`Rebased ${localChanges.files.length + localChanges.deletedPaths.length} local changes onto hosted draft ${remote.draftVersionId}.`);
|
|
2335
|
+
console.log(`Wrote ${formatGeneratedFileCount(generatedFiles.length)}`);
|
|
2336
|
+
console.log('Run `fgrove validate`, review the diff, then run `fgrove sync up`.');
|
|
2337
|
+
});
|
|
2192
2338
|
const envCommand = addExamples(program.command('env').description('Manage local funnel environment files'), [
|
|
2193
2339
|
'fgrove env pull --dir ./claimbee-ios',
|
|
2194
2340
|
]);
|
package/dist/localSync.d.ts
CHANGED
|
@@ -30,6 +30,24 @@ export type SourceFilePatchBatch = {
|
|
|
30
30
|
deletedPaths: string[];
|
|
31
31
|
files: SourceFile[];
|
|
32
32
|
};
|
|
33
|
+
export type SourceRebaseConflictKind = 'add-add' | 'delete-modify' | 'modify-delete' | 'modify-modify';
|
|
34
|
+
export type SourceRebaseConflict = {
|
|
35
|
+
path: string;
|
|
36
|
+
kind: SourceRebaseConflictKind;
|
|
37
|
+
};
|
|
38
|
+
export type SourceTextMerge = (input: {
|
|
39
|
+
path: string;
|
|
40
|
+
base: string;
|
|
41
|
+
local: string;
|
|
42
|
+
remote: string;
|
|
43
|
+
}) => Promise<{
|
|
44
|
+
content: string;
|
|
45
|
+
clean: boolean;
|
|
46
|
+
}>;
|
|
47
|
+
export type SourceRebaseResult = {
|
|
48
|
+
files: SourceFile[];
|
|
49
|
+
conflicts: SourceRebaseConflict[];
|
|
50
|
+
};
|
|
33
51
|
export type SourceCandidateOperation = {
|
|
34
52
|
type: 'create' | 'modify';
|
|
35
53
|
path: string;
|
|
@@ -86,6 +104,7 @@ export type SyncDownLocalLifecycle = {
|
|
|
86
104
|
export declare function runSyncDownLocalLifecycle(lifecycle: SyncDownLocalLifecycle): Promise<void>;
|
|
87
105
|
export declare const assertSafeRootFileWriteTarget: (rootDir: string, relativePath: string) => Promise<void>;
|
|
88
106
|
export declare const readSafeRootFile: (rootDir: string, relativePath: string) => Promise<Buffer>;
|
|
107
|
+
export declare const removeSafeRootFile: (rootDir: string, relativePath: string) => Promise<void>;
|
|
89
108
|
export declare const writeSafeRootFile: (rootDir: string, relativePath: string, content: string | Buffer, hooks?: SafeRootWriteHooks) => Promise<void>;
|
|
90
109
|
export declare function normalizeSyncPath(filePath: string): string;
|
|
91
110
|
export declare function assertSafeSyncPath(filePath: string): string;
|
|
@@ -109,6 +128,24 @@ export declare function collectSourceSnapshot(rootDir: string): Promise<{
|
|
|
109
128
|
sourceFiles: SourceFile[];
|
|
110
129
|
}>;
|
|
111
130
|
export declare function collectSourceFiles(rootDir: string): Promise<SourceFile[]>;
|
|
131
|
+
export declare function rebaseSourceFiles(input: {
|
|
132
|
+
baseFiles: readonly SourceFile[];
|
|
133
|
+
localFiles: readonly SourceFile[];
|
|
134
|
+
remoteFiles: readonly SourceFile[];
|
|
135
|
+
remoteOwnedPaths?: ReadonlySet<string>;
|
|
136
|
+
mergeText?: SourceTextMerge;
|
|
137
|
+
}): Promise<SourceRebaseResult>;
|
|
138
|
+
export declare function replaceSourceFiles(input: {
|
|
139
|
+
rootDir: string;
|
|
140
|
+
currentFiles: readonly SourceFile[];
|
|
141
|
+
nextFiles: readonly SourceFile[];
|
|
142
|
+
}): Promise<void>;
|
|
143
|
+
export declare function writeSourceRebaseBackup(input: {
|
|
144
|
+
rootDir: string;
|
|
145
|
+
files: readonly SourceFile[];
|
|
146
|
+
manifest: SyncManifest;
|
|
147
|
+
remoteDraftVersionId: string;
|
|
148
|
+
}): Promise<string>;
|
|
112
149
|
export declare function collectChangedSourceFiles(rootDir: string, previousManifest: SyncManifest): Promise<ChangedSourceFiles>;
|
|
113
150
|
export declare function hasLocalSourceChanges(rootDir: string, previousManifest: SyncManifest): Promise<boolean>;
|
|
114
151
|
export declare function chunkChangedSourceFiles(changes: Pick<ChangedSourceFiles, 'deletedPaths' | 'files'>, maxContentChars?: number): SourceFilePatchBatch[];
|
package/dist/localSync.js
CHANGED
|
@@ -186,6 +186,23 @@ export const readSafeRootFile = async (rootDir, relativePath) => {
|
|
|
186
186
|
await handle.close();
|
|
187
187
|
}
|
|
188
188
|
};
|
|
189
|
+
export const removeSafeRootFile = async (rootDir, relativePath) => {
|
|
190
|
+
const resolvedRoot = await resolveSafeRoot(rootDir, false);
|
|
191
|
+
const absolutePath = await assertSafeExistingPath(resolvedRoot, relativePath, false, true);
|
|
192
|
+
try {
|
|
193
|
+
const metadata = await lstat(absolutePath);
|
|
194
|
+
if (metadata.isSymbolicLink() || !metadata.isFile()) {
|
|
195
|
+
throw sourceCandidateInvariantError(`Local sync path is not a regular file: ${relativePath}`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
if (isErrno(error, 'ENOENT'))
|
|
200
|
+
return;
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
await rm(absolutePath);
|
|
204
|
+
await syncDirectory(path.dirname(absolutePath));
|
|
205
|
+
};
|
|
189
206
|
export const writeSafeRootFile = async (rootDir, relativePath, content, hooks = {}) => {
|
|
190
207
|
const resolvedRoot = await resolveSafeRoot(rootDir, true);
|
|
191
208
|
const absolutePath = await assertSafeExistingPath(resolvedRoot, relativePath, true, false, hooks);
|
|
@@ -365,6 +382,119 @@ export async function collectSourceSnapshot(rootDir) {
|
|
|
365
382
|
export async function collectSourceFiles(rootDir) {
|
|
366
383
|
return (await collectSourceSnapshot(rootDir)).sourceFiles;
|
|
367
384
|
}
|
|
385
|
+
const sourceFileBytes = (file) => (decodeBinarySourceContent(file) ?? Buffer.from(file.content, 'utf8'));
|
|
386
|
+
const sourceFilesEqual = (left, right) => {
|
|
387
|
+
if (!left || !right)
|
|
388
|
+
return left === right;
|
|
389
|
+
return sourceFileBytes(left).equals(sourceFileBytes(right));
|
|
390
|
+
};
|
|
391
|
+
const mapSourceFiles = (files, label) => {
|
|
392
|
+
const output = new Map();
|
|
393
|
+
const pathByFolded = new Map();
|
|
394
|
+
for (const file of files) {
|
|
395
|
+
const filePath = assertSafeSyncTargetPath(file.path);
|
|
396
|
+
const folded = filePath.toLocaleLowerCase('en-US');
|
|
397
|
+
const previousPath = pathByFolded.get(folded);
|
|
398
|
+
if (previousPath) {
|
|
399
|
+
throw sourceCandidateInvariantError(`${label} source repeats or case-collides at: ${previousPath}, ${filePath}`);
|
|
400
|
+
}
|
|
401
|
+
pathByFolded.set(folded, filePath);
|
|
402
|
+
output.set(filePath, file);
|
|
403
|
+
}
|
|
404
|
+
return output;
|
|
405
|
+
};
|
|
406
|
+
const isTextSourceFile = (file) => (decodeBinarySourceContent(file) === null && !Buffer.from(file.content, 'utf8').includes(0));
|
|
407
|
+
export async function rebaseSourceFiles(input) {
|
|
408
|
+
const base = mapSourceFiles(input.baseFiles, 'Base');
|
|
409
|
+
const local = mapSourceFiles(input.localFiles, 'Local');
|
|
410
|
+
const remote = mapSourceFiles(input.remoteFiles, 'Remote');
|
|
411
|
+
const paths = Array.from(new Set([...base.keys(), ...local.keys(), ...remote.keys()]))
|
|
412
|
+
.sort((left, right) => left.localeCompare(right));
|
|
413
|
+
const files = [];
|
|
414
|
+
const conflicts = [];
|
|
415
|
+
for (const filePath of paths) {
|
|
416
|
+
const baseFile = base.get(filePath);
|
|
417
|
+
const localFile = local.get(filePath);
|
|
418
|
+
const remoteFile = remote.get(filePath);
|
|
419
|
+
if (input.remoteOwnedPaths?.has(filePath)) {
|
|
420
|
+
if (remoteFile)
|
|
421
|
+
files.push(remoteFile);
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (sourceFilesEqual(localFile, remoteFile)) {
|
|
425
|
+
if (localFile)
|
|
426
|
+
files.push(localFile);
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (sourceFilesEqual(localFile, baseFile)) {
|
|
430
|
+
if (remoteFile)
|
|
431
|
+
files.push(remoteFile);
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (sourceFilesEqual(remoteFile, baseFile)) {
|
|
435
|
+
if (localFile)
|
|
436
|
+
files.push(localFile);
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (!baseFile) {
|
|
440
|
+
conflicts.push({ path: filePath, kind: 'add-add' });
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
if (!localFile) {
|
|
444
|
+
conflicts.push({ path: filePath, kind: 'delete-modify' });
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
447
|
+
if (!remoteFile) {
|
|
448
|
+
conflicts.push({ path: filePath, kind: 'modify-delete' });
|
|
449
|
+
continue;
|
|
450
|
+
}
|
|
451
|
+
if (input.mergeText
|
|
452
|
+
&& isTextSourceFile(baseFile)
|
|
453
|
+
&& isTextSourceFile(localFile)
|
|
454
|
+
&& isTextSourceFile(remoteFile)) {
|
|
455
|
+
const merged = await input.mergeText({
|
|
456
|
+
path: filePath,
|
|
457
|
+
base: sourceFileBytes(baseFile).toString('utf8'),
|
|
458
|
+
local: sourceFileBytes(localFile).toString('utf8'),
|
|
459
|
+
remote: sourceFileBytes(remoteFile).toString('utf8'),
|
|
460
|
+
});
|
|
461
|
+
if (merged.clean) {
|
|
462
|
+
files.push({ path: filePath, content: merged.content, contentType: 'text/plain' });
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
conflicts.push({ path: filePath, kind: 'modify-modify' });
|
|
467
|
+
}
|
|
468
|
+
return { files, conflicts };
|
|
469
|
+
}
|
|
470
|
+
export async function replaceSourceFiles(input) {
|
|
471
|
+
const current = mapSourceFiles(input.currentFiles, 'Current');
|
|
472
|
+
const next = mapSourceFiles(input.nextFiles, 'Next');
|
|
473
|
+
const deletedPaths = Array.from(current.keys())
|
|
474
|
+
.filter((filePath) => !next.has(filePath))
|
|
475
|
+
.sort((left, right) => left.localeCompare(right));
|
|
476
|
+
for (const filePath of deletedPaths) {
|
|
477
|
+
await removeSafeRootFile(input.rootDir, filePath);
|
|
478
|
+
}
|
|
479
|
+
await writeSourceFiles(input.rootDir, Array.from(next.values()));
|
|
480
|
+
}
|
|
481
|
+
export async function writeSourceRebaseBackup(input) {
|
|
482
|
+
mapSourceFiles(input.files, 'Backup');
|
|
483
|
+
const backupId = `${new Date().toISOString().replace(/[:.]/g, '-')}-${randomUUID()}`;
|
|
484
|
+
const backupRoot = `.funnelsgrove/rebase-backups/${backupId}`;
|
|
485
|
+
for (const file of input.files) {
|
|
486
|
+
await writeSafeRootFile(input.rootDir, `${backupRoot}/source/${file.path}`, sourceFileBytes(file));
|
|
487
|
+
}
|
|
488
|
+
await writeSafeRootFile(input.rootDir, `${backupRoot}/metadata.json`, `${JSON.stringify({
|
|
489
|
+
schemaVersion: 1,
|
|
490
|
+
createdAt: new Date().toISOString(),
|
|
491
|
+
baseDraftVersionId: input.manifest.draftVersionId,
|
|
492
|
+
remoteDraftVersionId: input.remoteDraftVersionId,
|
|
493
|
+
sourcePaths: input.files.map((file) => file.path).sort((left, right) => left.localeCompare(right)),
|
|
494
|
+
syncManifest: input.manifest,
|
|
495
|
+
}, null, 2)}\n`);
|
|
496
|
+
return backupRoot;
|
|
497
|
+
}
|
|
368
498
|
export async function collectChangedSourceFiles(rootDir, previousManifest) {
|
|
369
499
|
const currentManifest = await buildSyncManifest(rootDir, {
|
|
370
500
|
workspaceId: previousManifest.workspaceId,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
const MAX_MERGE_OUTPUT_BYTES = 15 * 1024 * 1024;
|
|
6
|
+
const runGitMergeFile = async (input) => new Promise((resolve, reject) => {
|
|
7
|
+
const child = spawn('git', [
|
|
8
|
+
'merge-file',
|
|
9
|
+
'--stdout',
|
|
10
|
+
'--diff3',
|
|
11
|
+
'-L', 'LOCAL',
|
|
12
|
+
'-L', 'BASE',
|
|
13
|
+
'-L', 'REMOTE',
|
|
14
|
+
input.localPath,
|
|
15
|
+
input.basePath,
|
|
16
|
+
input.remotePath,
|
|
17
|
+
], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
18
|
+
const stdout = [];
|
|
19
|
+
const stderr = [];
|
|
20
|
+
let outputBytes = 0;
|
|
21
|
+
child.stdout.on('data', (chunk) => {
|
|
22
|
+
outputBytes += chunk.length;
|
|
23
|
+
if (outputBytes > MAX_MERGE_OUTPUT_BYTES) {
|
|
24
|
+
child.kill('SIGKILL');
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
stdout.push(chunk);
|
|
28
|
+
});
|
|
29
|
+
child.stderr.on('data', (chunk) => stderr.push(chunk));
|
|
30
|
+
child.once('error', (error) => {
|
|
31
|
+
reject(new Error(error.code === 'ENOENT'
|
|
32
|
+
? 'fgrove sync rebase requires Git for overlapping text-file changes.'
|
|
33
|
+
: `Unable to run git merge-file: ${error.message}`));
|
|
34
|
+
});
|
|
35
|
+
child.once('close', (code) => {
|
|
36
|
+
if (outputBytes > MAX_MERGE_OUTPUT_BYTES) {
|
|
37
|
+
reject(new Error('Merged file exceeds the 15 MiB safety limit.'));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (code !== 0 && code !== 1) {
|
|
41
|
+
reject(new Error(`git merge-file failed${stderr.length > 0 ? `: ${Buffer.concat(stderr).toString('utf8').trim()}` : '.'}`));
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
resolve({
|
|
45
|
+
content: Buffer.concat(stdout).toString('utf8'),
|
|
46
|
+
clean: code === 0,
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
export const mergeTextSourceWithGit = async (input) => {
|
|
51
|
+
const tempDir = await mkdtemp(path.join(os.tmpdir(), 'fgrove-rebase-'));
|
|
52
|
+
const localPath = path.join(tempDir, 'local');
|
|
53
|
+
const basePath = path.join(tempDir, 'base');
|
|
54
|
+
const remotePath = path.join(tempDir, 'remote');
|
|
55
|
+
try {
|
|
56
|
+
await Promise.all([
|
|
57
|
+
writeFile(localPath, input.local),
|
|
58
|
+
writeFile(basePath, input.base),
|
|
59
|
+
writeFile(remotePath, input.remote),
|
|
60
|
+
]);
|
|
61
|
+
return await runGitMergeFile({ localPath, basePath, remotePath });
|
|
62
|
+
}
|
|
63
|
+
finally {
|
|
64
|
+
await rm(tempDir, { recursive: true, force: true });
|
|
65
|
+
}
|
|
66
|
+
};
|