@timekast/factory 1.1.0 → 1.3.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.
- package/dist/commands/publish.js +181 -0
- package/dist/commands/unpublish.js +81 -0
- package/dist/commands/update.js +58 -17
- package/dist/index.js +12 -0
- package/dist/lib/constants.js +27 -0
- package/dist/lib/gitattributes.js +101 -0
- package/dist/lib/publish-core.js +122 -0
- package/dist/lib/publish-engine.js +133 -0
- package/package.json +1 -1
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `factory publish <proposal|mockup|both>` — publish a derived project's static
|
|
3
|
+
* deliverable(s) to the `TimeKast/proposals` hub (plan v4.1).
|
|
4
|
+
*
|
|
5
|
+
* Security model is honest: link-no-adivinable + noindex only (no password yet).
|
|
6
|
+
* Identity = repo name (unique in the org) + unguessable token; both sticky in
|
|
7
|
+
* `project/.publish.json`. The CLI pushes to the hub but NEVER commits the derived
|
|
8
|
+
* repo — that's the workflow's job (the `--commit` opt-in is for standalone use).
|
|
9
|
+
*
|
|
10
|
+
* Expected failures throw `CLIError`; the top-level handler prints + exits.
|
|
11
|
+
*/
|
|
12
|
+
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
|
|
13
|
+
import { tmpdir } from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { execa } from 'execa';
|
|
16
|
+
import { CLIError } from '../lib/cli-error.js';
|
|
17
|
+
import { PROPOSALS_HUB_REPO } from '../lib/constants.js';
|
|
18
|
+
import { buildUrl, DELIVERABLE_DIR, deliverableExists, findExistingToken, findHtmlEntry, generateToken, hasNoindexMeta, parseRepoSlug, proposalFolder, readPublishState, slugify, writePublishState, } from '../lib/publish-core.js';
|
|
19
|
+
import { cloneHubShallow, commitAndPush, copyDeliverable, gitRemoteUrl, listHubFolders, resolveAuthToken, } from '../lib/publish-engine.js';
|
|
20
|
+
import { detectRepo } from '../lib/repo-detection.js';
|
|
21
|
+
/** Parse `publish`'s argv: a mandatory `<proposal|mockup|both>` + flags. */
|
|
22
|
+
export function parsePublishArgs(argv) {
|
|
23
|
+
const positional = argv.find((a) => !a.startsWith('-'));
|
|
24
|
+
if (!positional) {
|
|
25
|
+
throw new CLIError('Falta el argumento. Uso: `factory publish <proposal|mockup|both>` ' +
|
|
26
|
+
'(explícito a propósito — no se publica "lo que haya").');
|
|
27
|
+
}
|
|
28
|
+
let targets;
|
|
29
|
+
if (positional === 'both')
|
|
30
|
+
targets = ['proposal', 'mockup'];
|
|
31
|
+
else if (positional === 'proposal' || positional === 'mockup')
|
|
32
|
+
targets = [positional];
|
|
33
|
+
else {
|
|
34
|
+
throw new CLIError(`Argumento inválido: \`${positional}\`. Usa \`proposal\`, \`mockup\` o \`both\`.`);
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
targets,
|
|
38
|
+
flags: {
|
|
39
|
+
opaqueUrl: argv.includes('--opaque-url'),
|
|
40
|
+
changeUrl: argv.includes('--change-url'),
|
|
41
|
+
commit: argv.includes('--commit'),
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export async function runPublish(parsed) {
|
|
46
|
+
const cwd = process.cwd();
|
|
47
|
+
const { hasRepo, repoRoot } = detectRepo(cwd);
|
|
48
|
+
if (!hasRepo) {
|
|
49
|
+
throw new CLIError('No hay repositorio git aquí. `factory publish` corre dentro de un derivado.');
|
|
50
|
+
}
|
|
51
|
+
const root = repoRoot ?? cwd;
|
|
52
|
+
// Only publish requested deliverables that actually exist.
|
|
53
|
+
const present = parsed.targets.filter((t) => deliverableExists(root, t));
|
|
54
|
+
if (present.length === 0) {
|
|
55
|
+
throw new CLIError(`No encontré ${parsed.targets.join('/')} en este repo. ` +
|
|
56
|
+
'Corre `/proposal` o `/mockup` primero para generar el entregable.');
|
|
57
|
+
}
|
|
58
|
+
// Auth (dual): env token (headless) or gh + org membership (dev local).
|
|
59
|
+
const token = await resolveAuthToken();
|
|
60
|
+
// Identity: repo name from the git remote (unique in the org). Fallback to dir.
|
|
61
|
+
const remoteUrl = await gitRemoteUrl(root);
|
|
62
|
+
const repo = (remoteUrl && parseRepoSlug(remoteUrl)) || slugify(path.basename(root));
|
|
63
|
+
if (!remoteUrl) {
|
|
64
|
+
console.warn(`Aviso: este repo no tiene remote \`origin\`; uso el nombre del directorio (\`${repo}\`) como identidad.`);
|
|
65
|
+
}
|
|
66
|
+
const existing = readPublishState(root);
|
|
67
|
+
// Shallow-clone the hub into an ephemeral tmpdir.
|
|
68
|
+
const tmp = mkdtempSync(path.join(tmpdir(), 'tk-publish-'));
|
|
69
|
+
const cleanup = () => {
|
|
70
|
+
try {
|
|
71
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
/* best effort */
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const onSignal = () => {
|
|
78
|
+
cleanup();
|
|
79
|
+
process.exit(130);
|
|
80
|
+
};
|
|
81
|
+
process.once('SIGINT', onSignal);
|
|
82
|
+
process.once('SIGTERM', onSignal);
|
|
83
|
+
try {
|
|
84
|
+
const hubDir = path.join(tmp, 'hub');
|
|
85
|
+
await cloneHubShallow(token, hubDir);
|
|
86
|
+
// Resolve token + urlShape (sticky in .publish.json; hub-query as fallback).
|
|
87
|
+
const { proposalToken, urlShape } = resolveTokenAndShape(existing, parsed.flags, repo, hubDir);
|
|
88
|
+
const folder = proposalFolder(repo, proposalToken, urlShape);
|
|
89
|
+
const urls = { ...(existing?.urls ?? {}) };
|
|
90
|
+
const publishedFolders = new Set();
|
|
91
|
+
for (const type of present) {
|
|
92
|
+
const srcDir = path.join(root, DELIVERABLE_DIR[type]);
|
|
93
|
+
const files = readdirSync(srcDir);
|
|
94
|
+
const htmlEntry = findHtmlEntry(files);
|
|
95
|
+
if (!htmlEntry) {
|
|
96
|
+
throw new CLIError(`No encontré un HTML en \`${DELIVERABLE_DIR[type]}\`. ¿Se generó el entregable?`);
|
|
97
|
+
}
|
|
98
|
+
const indexPath = copyDeliverable(srcDir, hubDir, folder, type, htmlEntry);
|
|
99
|
+
// Verify (not inject) the noindex meta — the template owns the HTML.
|
|
100
|
+
const html = readFileSync(indexPath, 'utf8');
|
|
101
|
+
if (!hasNoindexMeta(html)) {
|
|
102
|
+
throw new CLIError(`El entregable \`${type}\` no trae \`<meta name="robots" content="noindex,nofollow">\`. ` +
|
|
103
|
+
'El template debe emitirlo; no se publica sin él (no lo inyecto).');
|
|
104
|
+
}
|
|
105
|
+
urls[type] = buildUrl(folder, type);
|
|
106
|
+
publishedFolders.add(folder);
|
|
107
|
+
}
|
|
108
|
+
await commitAndPush(hubDir, `publish: ${repo} (${present.join(', ')})`, [...publishedFolders]);
|
|
109
|
+
// Persist sticky state in the derived repo working tree (NO commit here).
|
|
110
|
+
writePublishState(root, {
|
|
111
|
+
repo,
|
|
112
|
+
token: proposalToken,
|
|
113
|
+
urlShape,
|
|
114
|
+
urls,
|
|
115
|
+
publishedAt: new Date().toISOString(),
|
|
116
|
+
});
|
|
117
|
+
if (parsed.flags.commit) {
|
|
118
|
+
await commitDerivedRepo(root, present, repo);
|
|
119
|
+
}
|
|
120
|
+
reportSuccess(present, urls, parsed.flags.commit);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
process.removeListener('SIGINT', onSignal);
|
|
124
|
+
process.removeListener('SIGTERM', onSignal);
|
|
125
|
+
cleanup();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Resolve the sticky token + urlShape, honoring `.publish.json` then the hub. */
|
|
129
|
+
function resolveTokenAndShape(existing, flags, repo, hubDir) {
|
|
130
|
+
if (existing) {
|
|
131
|
+
const wantsOpaque = flags.opaqueUrl;
|
|
132
|
+
const isOpaque = existing.urlShape === 'opaque';
|
|
133
|
+
if (wantsOpaque !== isOpaque && !flags.changeUrl) {
|
|
134
|
+
throw new CLIError(`Esta propuesta ya se publicó como \`${existing.urlShape}\`. Cambiar la forma de URL ` +
|
|
135
|
+
'rompería el link que el cliente ya tiene. Si es a propósito, pasa `--change-url` ' +
|
|
136
|
+
'(la ruta vieja queda huérfana — bájala con `factory unpublish`).');
|
|
137
|
+
}
|
|
138
|
+
const urlShape = flags.changeUrl
|
|
139
|
+
? flags.opaqueUrl
|
|
140
|
+
? 'opaque'
|
|
141
|
+
: 'named'
|
|
142
|
+
: existing.urlShape;
|
|
143
|
+
if (flags.changeUrl && urlShape !== existing.urlShape) {
|
|
144
|
+
console.warn('Aviso: cambiaste la forma de URL. La ruta anterior queda huérfana en el hub ' +
|
|
145
|
+
'(bájala con `factory unpublish` si ya no la quieres).');
|
|
146
|
+
}
|
|
147
|
+
return { proposalToken: existing.token, urlShape };
|
|
148
|
+
}
|
|
149
|
+
// First publish: named → reuse a hub folder if one exists (uniqueness = ownership).
|
|
150
|
+
const urlShape = flags.opaqueUrl ? 'opaque' : 'named';
|
|
151
|
+
if (urlShape === 'named') {
|
|
152
|
+
const hit = findExistingToken(repo, listHubFolders(hubDir));
|
|
153
|
+
if (hit && 'ambiguous' in hit) {
|
|
154
|
+
throw new CLIError(`Hay más de una carpeta \`${repo}-*\` en el hub y no hay \`.publish.json\` local para desambiguar. ` +
|
|
155
|
+
'No adivino cuál es tuya — resuélvelo a mano en el hub o restaura tu `.publish.json`.');
|
|
156
|
+
}
|
|
157
|
+
if (hit)
|
|
158
|
+
return { proposalToken: hit.token, urlShape };
|
|
159
|
+
}
|
|
160
|
+
return { proposalToken: generateToken(), urlShape };
|
|
161
|
+
}
|
|
162
|
+
/** `--commit` opt-in: commit the deliverable + state in the derived repo (pathspec-scoped). */
|
|
163
|
+
async function commitDerivedRepo(root, types, repo) {
|
|
164
|
+
const paths = [...types.map((t) => DELIVERABLE_DIR[t]), path.join('project', '.publish.json')];
|
|
165
|
+
await execa('git', ['add', '--', ...paths], { cwd: root, reject: false });
|
|
166
|
+
const res = await execa('git', ['commit', '-m', `chore: publish ${repo} → ${PROPOSALS_HUB_REPO}`, '--', ...paths], { cwd: root, reject: false });
|
|
167
|
+
if (res.exitCode === 0) {
|
|
168
|
+
console.log('• Commit del entregable + .publish.json hecho en el repo derivado (--commit).');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
function reportSuccess(types, urls, committed) {
|
|
172
|
+
console.log(`\n✔ Publicado en ${PROPOSALS_HUB_REPO} (Vercel redeploya solo).`);
|
|
173
|
+
for (const t of types) {
|
|
174
|
+
if (urls[t])
|
|
175
|
+
console.log(` ${t}: ${urls[t]}`);
|
|
176
|
+
}
|
|
177
|
+
if (!committed) {
|
|
178
|
+
console.log('\nℹ El entregable + `project/.publish.json` quedaron escritos pero SIN commitear. ' +
|
|
179
|
+
'El workflow los commitea al cerrar; en uso suelto, commitéalos tú (o usa `--commit`).');
|
|
180
|
+
}
|
|
181
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `factory unpublish [proposal|mockup|both]` — take a published deliverable down
|
|
3
|
+
* from the hub (plan v4.1). The recourse against a leaked link in the static,
|
|
4
|
+
* password-less model: it mata el link (cuts future access via the hub), but is
|
|
5
|
+
* contención, NOT recall — anything already fetched by an unfurler lives in third
|
|
6
|
+
* party caches outside our control.
|
|
7
|
+
*
|
|
8
|
+
* Same machinery as publish (auth → shallow clone → mutate → rebase-retry push);
|
|
9
|
+
* no new infra. Keeps the token sticky in `.publish.json` so a later re-publish
|
|
10
|
+
* reuses the same URL.
|
|
11
|
+
*/
|
|
12
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
13
|
+
import { tmpdir } from 'node:os';
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { CLIError } from '../lib/cli-error.js';
|
|
16
|
+
import { PROPOSALS_HUB_REPO } from '../lib/constants.js';
|
|
17
|
+
import { proposalFolder, readPublishState, writePublishState, } from '../lib/publish-core.js';
|
|
18
|
+
import { cloneHubShallow, commitAndPush, removeDeliverable, resolveAuthToken, } from '../lib/publish-engine.js';
|
|
19
|
+
import { detectRepo } from '../lib/repo-detection.js';
|
|
20
|
+
/** Parse the optional `<proposal|mockup|both>` arg (default: both). */
|
|
21
|
+
export function parseUnpublishTargets(argv) {
|
|
22
|
+
const positional = argv.find((a) => !a.startsWith('-'));
|
|
23
|
+
if (!positional || positional === 'both')
|
|
24
|
+
return ['proposal', 'mockup'];
|
|
25
|
+
if (positional === 'proposal' || positional === 'mockup')
|
|
26
|
+
return [positional];
|
|
27
|
+
throw new CLIError(`Argumento inválido: \`${positional}\`. Usa \`proposal\`, \`mockup\` o \`both\`.`);
|
|
28
|
+
}
|
|
29
|
+
export async function runUnpublish(targets) {
|
|
30
|
+
const cwd = process.cwd();
|
|
31
|
+
const { hasRepo, repoRoot } = detectRepo(cwd);
|
|
32
|
+
if (!hasRepo) {
|
|
33
|
+
throw new CLIError('No hay repositorio git aquí. `factory unpublish` corre dentro de un derivado.');
|
|
34
|
+
}
|
|
35
|
+
const root = repoRoot ?? cwd;
|
|
36
|
+
const state = readPublishState(root);
|
|
37
|
+
if (!state) {
|
|
38
|
+
throw new CLIError('No hay `project/.publish.json` en este repo — no sé qué bajar. ' +
|
|
39
|
+
'Esta propuesta no fue publicada desde aquí (o el estado se perdió).');
|
|
40
|
+
}
|
|
41
|
+
const token = await resolveAuthToken();
|
|
42
|
+
const folder = proposalFolder(state.repo, state.token, state.urlShape);
|
|
43
|
+
const tmp = mkdtempSync(path.join(tmpdir(), 'tk-unpublish-'));
|
|
44
|
+
const cleanup = () => {
|
|
45
|
+
try {
|
|
46
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
/* best effort */
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
process.once('SIGINT', cleanup);
|
|
53
|
+
process.once('SIGTERM', cleanup);
|
|
54
|
+
try {
|
|
55
|
+
const hubDir = path.join(tmp, 'hub');
|
|
56
|
+
await cloneHubShallow(token, hubDir);
|
|
57
|
+
const removed = [];
|
|
58
|
+
for (const type of targets) {
|
|
59
|
+
if (removeDeliverable(hubDir, folder, type))
|
|
60
|
+
removed.push(type);
|
|
61
|
+
}
|
|
62
|
+
if (removed.length === 0) {
|
|
63
|
+
console.log('No había nada que bajar en el hub para esta propuesta. Nada que hacer.');
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
await commitAndPush(hubDir, `unpublish: ${state.repo} (${removed.join(', ')})`, [folder]);
|
|
67
|
+
// Drop the removed URLs from the sticky state (keep the token for re-publish).
|
|
68
|
+
const urls = { ...state.urls };
|
|
69
|
+
for (const type of removed)
|
|
70
|
+
delete urls[type];
|
|
71
|
+
writePublishState(root, { ...state, urls, publishedAt: new Date().toISOString() });
|
|
72
|
+
console.log(`\n✔ Bajado de ${PROPOSALS_HUB_REPO}: ${removed.join(', ')}.`);
|
|
73
|
+
console.log('ℹ Esto corta el acceso futuro vía el hub, pero NO recupera lo ya filtrado ' +
|
|
74
|
+
'(un link reenviado pudo quedar cacheado por terceros).');
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
process.removeListener('SIGINT', cleanup);
|
|
78
|
+
process.removeListener('SIGTERM', cleanup);
|
|
79
|
+
cleanup();
|
|
80
|
+
}
|
|
81
|
+
}
|
package/dist/commands/update.js
CHANGED
|
@@ -40,7 +40,8 @@ import prompts from 'prompts';
|
|
|
40
40
|
import { applyPlan, clearUpdateState, defaultBackupDir, hasUpdateState, readUpdateState, validateStagedManifest, writeUpdateState, } from '../lib/atomic-swap.js';
|
|
41
41
|
import { collectClaudePaths } from '../lib/claude-paths.js';
|
|
42
42
|
import { CLIError } from '../lib/cli-error.js';
|
|
43
|
-
import { CLAUDE_MD_FILE, PROFILES } from '../lib/constants.js';
|
|
43
|
+
import { CLAUDE_MD_FILE, GITATTRIBUTES_FILE, PROFILES, } from '../lib/constants.js';
|
|
44
|
+
import { extractManagedBlock, syncManagedBlock } from '../lib/gitattributes.js';
|
|
44
45
|
import { diffLockfiles, hasLockfile, normalizeThenHash, planAutoRegister, readLockfile, writeLockfile, } from '../lib/lockfile.js';
|
|
45
46
|
import { detectProfile, insertFactoryUpdateScript, setAgentKitVersion, } from '../lib/package-json.js';
|
|
46
47
|
import { runPreflight } from '../lib/preflight.js';
|
|
@@ -168,9 +169,8 @@ function runResume(rootDir) {
|
|
|
168
169
|
applyPlan(rootDir, state.stagedDir, state.plan, state.backupDir);
|
|
169
170
|
writeLockfile(rootDir, newLock);
|
|
170
171
|
clearUpdateState(rootDir);
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
maintainDerivedPkg(pkgPath, newLock.version);
|
|
172
|
+
// Maintain dotfiles BEFORE removing the staged dir (the .gitattributes source).
|
|
173
|
+
maintainDerivedDotfiles(rootDir, state.stagedDir, newLock.version);
|
|
174
174
|
rmSync(state.stagedDir, { recursive: true, force: true });
|
|
175
175
|
console.log('✔ `update` retomado y completado.');
|
|
176
176
|
}
|
|
@@ -191,15 +191,31 @@ function warnOnScriptConflict(action, _pkgPath) {
|
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
193
|
/**
|
|
194
|
-
* After a sync, maintain the derived project's package.json
|
|
195
|
-
* `
|
|
196
|
-
*
|
|
197
|
-
*
|
|
198
|
-
*
|
|
194
|
+
* After a sync, maintain the derived project's co-owned dotfiles — `package.json`
|
|
195
|
+
* AND `.gitattributes` — in one place. Centralized (not scattered per command) so
|
|
196
|
+
* all THREE update paths (main, legacy auto-register, resume) are covered by
|
|
197
|
+
* construction: a per-command call already regressed once (legacy + resume were
|
|
198
|
+
* missed). `stagedDir` is the freshly-unpacked tarball, the source of the
|
|
199
|
+
* `.gitattributes` managed block.
|
|
200
|
+
*/
|
|
201
|
+
function maintainDerivedDotfiles(rootDir, stagedDir, agentKitVersion) {
|
|
202
|
+
maintainDerivedPkg(rootDir, agentKitVersion);
|
|
203
|
+
syncDerivedGitattributes(rootDir, stagedDir);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Maintain the derived project's package.json: ensure the `factory:*` scripts
|
|
207
|
+
* (warn on a divergent `factory:update`) and set `agentKitVersion` to the
|
|
208
|
+
* just-installed brain version, mirroring the lockfile's `version`. Run on every
|
|
209
|
+
* update, so the field tracks each `factory:update` (and a derivative whose field
|
|
210
|
+
* was missing or stale gets reconciled — same shape as the Factory's own
|
|
199
211
|
* package.json). `factoryVersion` (the frozen birth stamp) and `version` (the app
|
|
200
|
-
* semver) are untouched.
|
|
212
|
+
* semver) are untouched. No-op (not an error) when the repo has no package.json
|
|
213
|
+
* (a non-Node derivative).
|
|
201
214
|
*/
|
|
202
|
-
function maintainDerivedPkg(
|
|
215
|
+
function maintainDerivedPkg(rootDir, agentKitVersion) {
|
|
216
|
+
const pkgPath = path.join(rootDir, 'package.json');
|
|
217
|
+
if (!existsSync(pkgPath))
|
|
218
|
+
return;
|
|
203
219
|
// Tolerant (mirrors `add`): a malformed package.json must NOT throw AFTER the
|
|
204
220
|
// brain was already applied + the lockfile written — the install succeeded; the
|
|
205
221
|
// script/version mirror is best-effort. Warn and move on.
|
|
@@ -212,6 +228,35 @@ function maintainDerivedPkg(pkgPath, agentKitVersion) {
|
|
|
212
228
|
'Corrige package.json y vuelve a correr `factory update` para sincronizar agentKitVersion.');
|
|
213
229
|
}
|
|
214
230
|
}
|
|
231
|
+
/**
|
|
232
|
+
* Sync the Factory's managed `.gitattributes` block (the EOL/binary rules that
|
|
233
|
+
* keep the kit's committed binaries from being corrupted by CRLF→LF normalization)
|
|
234
|
+
* into the derived repo, preserving the dev's own rules. The canonical block is
|
|
235
|
+
* READ from the staged tarball (single SSOT), so the rules are never duplicated in
|
|
236
|
+
* the CLI. Runs even without package.json (a non-Node derivative needs the rules
|
|
237
|
+
* too). Best-effort like the package.json mirror: a tarball that predates the
|
|
238
|
+
* managed block (no markers → no block) is a silent no-op, and a write failure
|
|
239
|
+
* never fails an already-applied update.
|
|
240
|
+
*/
|
|
241
|
+
function syncDerivedGitattributes(rootDir, stagedDir) {
|
|
242
|
+
try {
|
|
243
|
+
const srcPath = path.join(stagedDir, GITATTRIBUTES_FILE);
|
|
244
|
+
if (!existsSync(srcPath))
|
|
245
|
+
return;
|
|
246
|
+
const block = extractManagedBlock(readFileSync(srcPath, 'utf8'));
|
|
247
|
+
if (!block)
|
|
248
|
+
return;
|
|
249
|
+
const { action } = syncManagedBlock(rootDir, block);
|
|
250
|
+
if (action === 'unchanged')
|
|
251
|
+
return;
|
|
252
|
+
console.log(action === 'created'
|
|
253
|
+
? '✔ `.gitattributes` creado con las reglas de normalización del kit.'
|
|
254
|
+
: '✔ `.gitattributes`: bloque de reglas del kit sincronizado.');
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
console.warn('Aviso: no se pudo sincronizar `.gitattributes`; el cerebro se instaló igual.');
|
|
258
|
+
}
|
|
259
|
+
}
|
|
215
260
|
/** Print the deletes + kept-retired (design §7.6 — visible) + a one-line summary. */
|
|
216
261
|
function reportSummary(diff, manifest) {
|
|
217
262
|
if (diff.deleteSilent.length > 0) {
|
|
@@ -335,9 +380,7 @@ export async function runUpdate(flags, deps = {}) {
|
|
|
335
380
|
// (agentKitVersion advances; factoryVersion stays frozen).
|
|
336
381
|
writeLockfile(rootDir, stampBirth(oldLock, manifest));
|
|
337
382
|
clearUpdateState(rootDir);
|
|
338
|
-
|
|
339
|
-
if (existsSync(pkgPath))
|
|
340
|
-
maintainDerivedPkg(pkgPath, manifest.version);
|
|
383
|
+
maintainDerivedDotfiles(rootDir, stagedDir, manifest.version);
|
|
341
384
|
reportSummary(diff, manifest);
|
|
342
385
|
}
|
|
343
386
|
finally {
|
|
@@ -394,9 +437,7 @@ async function applyLegacy(rootDir, stagedDir, manifest) {
|
|
|
394
437
|
// the just-installed files) PLUS the birth stamp. A legacy auto-register is the
|
|
395
438
|
// first sync this repo records, so the birth seal = the manifest's version.
|
|
396
439
|
writeLockfile(rootDir, { ...manifest, factoryVersion: manifest.version });
|
|
397
|
-
|
|
398
|
-
if (existsSync(pkgPath))
|
|
399
|
-
maintainDerivedPkg(pkgPath, manifest.version);
|
|
440
|
+
maintainDerivedDotfiles(rootDir, stagedDir, manifest.version);
|
|
400
441
|
if (claudeMdExists) {
|
|
401
442
|
console.log('\nConservé tu `CLAUDE.md` (no se sobrescribió). Verifica que importe las rules del kit ' +
|
|
402
443
|
'(`@.claude/rules/*`); corre `factory doctor` para detectar rules sin importar.');
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,9 @@ import { CLIError } from './lib/cli-error.js';
|
|
|
13
13
|
import { parseAddFlags, runAdd } from './commands/add.js';
|
|
14
14
|
import { runDoctor } from './commands/doctor.js';
|
|
15
15
|
import { runNew } from './commands/new.js';
|
|
16
|
+
import { parsePublishArgs, runPublish } from './commands/publish.js';
|
|
16
17
|
import { runStatus } from './commands/status.js';
|
|
18
|
+
import { parseUnpublishTargets, runUnpublish } from './commands/unpublish.js';
|
|
17
19
|
import { parseUpdateFlags, runUpdate } from './commands/update.js';
|
|
18
20
|
const HELP = `
|
|
19
21
|
@timekast/factory — bootstrap y mantenimiento de proyectos derivados del Factory.
|
|
@@ -27,6 +29,8 @@ Comandos:
|
|
|
27
29
|
update Actualiza el cerebro al día sin pisar tu trabajo local
|
|
28
30
|
status Reporta la versión instalada vs. la última disponible
|
|
29
31
|
doctor Detecta huérfanos, conflictos y rules sin importar + aviso de seguridad
|
|
32
|
+
publish <qué> Publica el entregable (proposal|mockup|both) a proposals.timekast.mx
|
|
33
|
+
unpublish [qué] Baja del hub un entregable publicado (proposal|mockup|both; default both)
|
|
30
34
|
|
|
31
35
|
Sobre \`add\`:
|
|
32
36
|
Requiere estar dentro de un repo git (al menos \`git init\`). Por default instala
|
|
@@ -107,6 +111,14 @@ async function main(argv) {
|
|
|
107
111
|
runDoctor();
|
|
108
112
|
return;
|
|
109
113
|
}
|
|
114
|
+
case 'publish': {
|
|
115
|
+
await runPublish(parsePublishArgs(rest));
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
case 'unpublish': {
|
|
119
|
+
await runUnpublish(parseUnpublishTargets(rest));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
110
122
|
default:
|
|
111
123
|
throw new CLIError(`Comando desconocido: \`${command}\`.\nEjecuta \`factory --help\` para ver los comandos disponibles.`);
|
|
112
124
|
}
|
package/dist/lib/constants.js
CHANGED
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
export const FACTORY_ORG = 'TimeKast';
|
|
8
8
|
/** The Factory monorepo, source of the distribution releases. */
|
|
9
9
|
export const FACTORY_REPO = 'TimeKast/TimeKast-Factory';
|
|
10
|
+
/** The static hub repo that hosts published proposals/mockups (`factory publish`). */
|
|
11
|
+
export const PROPOSALS_HUB_REPO = `${FACTORY_ORG}/proposals`;
|
|
12
|
+
/** HTTPS git URL of the hub (token is injected by the publish command). */
|
|
13
|
+
export const PROPOSALS_HUB_GIT = `https://github.com/${FACTORY_ORG}/proposals.git`;
|
|
10
14
|
/** Distribution profiles selectable in `new`. */
|
|
11
15
|
export const PROFILES = {
|
|
12
16
|
full: 'full',
|
|
@@ -26,6 +30,23 @@ export const LOCKFILE_FILE = 'lockfile.json';
|
|
|
26
30
|
* exists on disk (path-match path). See `diffLockfiles` + the install commands.
|
|
27
31
|
*/
|
|
28
32
|
export const CLAUDE_MD_FILE = 'CLAUDE.md';
|
|
33
|
+
/**
|
|
34
|
+
* Repo-root `.gitattributes`. NOT a tracked manifest file (absent from `track`),
|
|
35
|
+
* so it never flows through the diff/lockfile engine — a derived repo's own rules
|
|
36
|
+
* would otherwise read as "locally edited" and conflict on every update. Instead a
|
|
37
|
+
* delimited managed block (markers below) is synced surgically post-apply, like
|
|
38
|
+
* `package.json` scripts: the block is replaced verbatim, everything outside it is
|
|
39
|
+
* preserved byte-for-byte. See `syncManagedBlock` in `lib/gitattributes.ts`.
|
|
40
|
+
*/
|
|
41
|
+
export const GITATTRIBUTES_FILE = '.gitattributes';
|
|
42
|
+
/**
|
|
43
|
+
* Managed-block sentinels. These are PREFIXES (the live source lines carry extra
|
|
44
|
+
* descriptive text + trailing `>>>`/`<<<`), matched with `startsWith` so detection
|
|
45
|
+
* survives edits to the comment copy. Do not change without a migration: a derived
|
|
46
|
+
* repo's existing block is located by these prefixes.
|
|
47
|
+
*/
|
|
48
|
+
export const MANAGED_BLOCK_START = '# >>> timekast-factory managed';
|
|
49
|
+
export const MANAGED_BLOCK_END = '# <<< timekast-factory managed';
|
|
29
50
|
/** The scripts the CLI injects into a derived project's package.json. */
|
|
30
51
|
export const UPDATE_SCRIPT_NAME = 'factory:update';
|
|
31
52
|
// `npx` so the script resolves in a fresh derived repo where @timekast/factory
|
|
@@ -36,6 +57,10 @@ export const DOCTOR_SCRIPT_NAME = 'factory:doctor';
|
|
|
36
57
|
export const DOCTOR_SCRIPT_CMD = 'npx @timekast/factory doctor';
|
|
37
58
|
export const STATUS_SCRIPT_NAME = 'factory:status';
|
|
38
59
|
export const STATUS_SCRIPT_CMD = 'npx @timekast/factory status';
|
|
60
|
+
export const PUBLISH_SCRIPT_NAME = 'factory:publish';
|
|
61
|
+
export const PUBLISH_SCRIPT_CMD = 'npx @timekast/factory publish';
|
|
62
|
+
export const UNPUBLISH_SCRIPT_NAME = 'factory:unpublish';
|
|
63
|
+
export const UNPUBLISH_SCRIPT_CMD = 'npx @timekast/factory unpublish';
|
|
39
64
|
/**
|
|
40
65
|
* All convenience scripts the installer ensures in a Node derivative's
|
|
41
66
|
* package.json (each: add if missing, never overwrite a divergent value). Keyed
|
|
@@ -46,4 +71,6 @@ export const FACTORY_SCRIPTS = {
|
|
|
46
71
|
[UPDATE_SCRIPT_NAME]: UPDATE_SCRIPT_CMD,
|
|
47
72
|
[DOCTOR_SCRIPT_NAME]: DOCTOR_SCRIPT_CMD,
|
|
48
73
|
[STATUS_SCRIPT_NAME]: STATUS_SCRIPT_CMD,
|
|
74
|
+
[PUBLISH_SCRIPT_NAME]: PUBLISH_SCRIPT_CMD,
|
|
75
|
+
[UNPUBLISH_SCRIPT_NAME]: UNPUBLISH_SCRIPT_CMD,
|
|
49
76
|
};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Surgical sync of the Factory's managed `.gitattributes` block into a derived
|
|
3
|
+
* project, mirroring the `package.json` script-insertion pattern (`package-json.ts`):
|
|
4
|
+
* the delimited block is replaced verbatim, everything outside it is preserved.
|
|
5
|
+
*
|
|
6
|
+
* Why not the lockfile/`track` engine: `.gitattributes` is dual-owned at the
|
|
7
|
+
* intra-file level (the Factory block + the dev's own rules share one file). The
|
|
8
|
+
* lockfile hashes whole files, so tracking it would read the dev's rules as a
|
|
9
|
+
* local edit and conflict on every update. Instead the block is synced as an
|
|
10
|
+
* idempotent post-apply step, outside `diffLockfiles`/`applyPlan`.
|
|
11
|
+
*
|
|
12
|
+
* The canonical block is the single SSOT: it is READ from the `.gitattributes`
|
|
13
|
+
* that ships in the staged tarball (see `extractManagedBlock`), never duplicated
|
|
14
|
+
* as a CLI constant. A derived repo's existing block is located by the
|
|
15
|
+
* `MANAGED_BLOCK_START` / `_END` sentinels (prefix match), so the descriptive
|
|
16
|
+
* comment copy can evolve without breaking detection.
|
|
17
|
+
*/
|
|
18
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { GITATTRIBUTES_FILE, MANAGED_BLOCK_END, MANAGED_BLOCK_START } from './constants.js';
|
|
21
|
+
const isStart = (line) => line.trimStart().startsWith(MANAGED_BLOCK_START);
|
|
22
|
+
const isEnd = (line) => line.trimStart().startsWith(MANAGED_BLOCK_END);
|
|
23
|
+
/** Drop trailing all-whitespace lines (so appends don't pile up blank lines). */
|
|
24
|
+
function stripTrailingEmpty(lines) {
|
|
25
|
+
const out = [...lines];
|
|
26
|
+
while (out.length > 0 && out[out.length - 1].trim() === '')
|
|
27
|
+
out.pop();
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Extract the managed block (markers inclusive) from a `.gitattributes` content,
|
|
32
|
+
* or `null` if no start marker is present. Used on the well-formed staged source
|
|
33
|
+
* to obtain the canonical block to sync. If a start marker is found with no end
|
|
34
|
+
* marker, returns from start to EOF (defensive — the source is well-formed).
|
|
35
|
+
*/
|
|
36
|
+
export function extractManagedBlock(content) {
|
|
37
|
+
const lines = content.replace(/\r\n/g, '\n').split('\n');
|
|
38
|
+
const start = lines.findIndex(isStart);
|
|
39
|
+
if (start === -1)
|
|
40
|
+
return null;
|
|
41
|
+
let end = -1;
|
|
42
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
43
|
+
if (isEnd(lines[i])) {
|
|
44
|
+
end = i;
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const slice = end === -1 ? lines.slice(start) : lines.slice(start, end + 1);
|
|
49
|
+
return slice.join('\n');
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Sync `sourceBlock` (markers inclusive) into `<rootDir>/.gitattributes`,
|
|
53
|
+
* preserving every rule outside the managed block. The whole file is normalized
|
|
54
|
+
* to LF (it lives at repo root, outside `.claude/** text eol=lf`, so a source
|
|
55
|
+
* packed with CRLF on an autocrlf machine is normalized here). Idempotent:
|
|
56
|
+
* writes only when the bytes actually change.
|
|
57
|
+
*
|
|
58
|
+
* - no file / empty file → `created` (block only)
|
|
59
|
+
* - file without a start marker → `inserted` (block appended after a blank line)
|
|
60
|
+
* - start + end markers → `updated` (content between markers replaced)
|
|
61
|
+
* - start without end (dev clobbered half a line) → `updated`, regenerated
|
|
62
|
+
* cleanly from start to EOF (NOT appended — avoids a dangling start marker)
|
|
63
|
+
*/
|
|
64
|
+
export function syncManagedBlock(rootDir, sourceBlock) {
|
|
65
|
+
const filePath = path.join(rootDir, GITATTRIBUTES_FILE);
|
|
66
|
+
const raw = existsSync(filePath) ? readFileSync(filePath, 'utf8') : '';
|
|
67
|
+
const block = sourceBlock.replace(/\r\n/g, '\n').replace(/\n+$/, '');
|
|
68
|
+
let result;
|
|
69
|
+
let action;
|
|
70
|
+
if (raw.trim() === '') {
|
|
71
|
+
result = `${block}\n`;
|
|
72
|
+
action = 'created';
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
const lines = raw.replace(/\r\n/g, '\n').split('\n');
|
|
76
|
+
const start = lines.findIndex(isStart);
|
|
77
|
+
if (start === -1) {
|
|
78
|
+
const before = stripTrailingEmpty(lines);
|
|
79
|
+
result = `${before.join('\n')}\n\n${block}\n`;
|
|
80
|
+
action = 'inserted';
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
// Replace from start to the end marker, or to EOF when the end marker is
|
|
84
|
+
// missing (malformed block → regenerate clean rather than append).
|
|
85
|
+
let end = lines.length - 1;
|
|
86
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
87
|
+
if (isEnd(lines[i])) {
|
|
88
|
+
end = i;
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const merged = [...lines.slice(0, start), ...block.split('\n'), ...lines.slice(end + 1)];
|
|
93
|
+
result = `${stripTrailingEmpty(merged).join('\n')}\n`;
|
|
94
|
+
action = 'updated';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (result === raw)
|
|
98
|
+
return { action: 'unchanged' };
|
|
99
|
+
writeFileSync(filePath, result, 'utf8');
|
|
100
|
+
return { action };
|
|
101
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure helpers for `factory publish` / `factory unpublish` (kept side-effect-free
|
|
3
|
+
* where possible so they unit-test without mocks). The git/gh/network seams live
|
|
4
|
+
* in the commands; everything here is deterministic given its inputs.
|
|
5
|
+
*
|
|
6
|
+
* Identity model (plan v4.1): a proposal's hub folder is `{repo}-{token}` where
|
|
7
|
+
* `repo` is the derived project's repo name (unique within the org → ownership is
|
|
8
|
+
* free) and `token` is an unguessable suffix. `--opaque-url` drops the repo name
|
|
9
|
+
* (`p-{token}`) for clients whose name must not travel in the link.
|
|
10
|
+
*/
|
|
11
|
+
import { randomBytes } from 'node:crypto';
|
|
12
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
/** Source dir (relative to repo root) for each deliverable. */
|
|
15
|
+
export const DELIVERABLE_DIR = {
|
|
16
|
+
proposal: path.join('project', 'presentation'),
|
|
17
|
+
mockup: path.join('project', 'mockup'),
|
|
18
|
+
};
|
|
19
|
+
/** The public domain the hub serves under. */
|
|
20
|
+
export const PROPOSALS_DOMAIN = 'proposals.timekast.mx';
|
|
21
|
+
/** Relative path (from repo root) to the persisted publish state. */
|
|
22
|
+
export const PUBLISH_STATE_FILE = path.join('project', '.publish.json');
|
|
23
|
+
const TOKEN_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'; // base36 — URL-safe, case-insensitive
|
|
24
|
+
const TOKEN_LENGTH = 16;
|
|
25
|
+
/**
|
|
26
|
+
* Generate an unguessable token (16 base36 chars ≈ 82 bits). Not a secret in the
|
|
27
|
+
* access-control sense — it makes the URL non-guessable and prevents enumeration.
|
|
28
|
+
*/
|
|
29
|
+
export function generateToken() {
|
|
30
|
+
const bytes = randomBytes(TOKEN_LENGTH);
|
|
31
|
+
let out = '';
|
|
32
|
+
for (let i = 0; i < TOKEN_LENGTH; i++) {
|
|
33
|
+
out += TOKEN_ALPHABET[bytes[i] % TOKEN_ALPHABET.length];
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parse the repo name from a git remote URL (ssh or https forms), e.g.
|
|
39
|
+
* `git@github.com:TimeKast/fimubac.git` / `https://github.com/TimeKast/fimubac` → `fimubac`.
|
|
40
|
+
* Returns null when the URL has no recognizable `…/repo` tail.
|
|
41
|
+
*/
|
|
42
|
+
export function parseRepoSlug(remoteUrl) {
|
|
43
|
+
const trimmed = remoteUrl.trim().replace(/\.git$/, '');
|
|
44
|
+
// Last path segment after `/` or `:` (ssh scp-like form uses `:`).
|
|
45
|
+
const match = trimmed.match(/[/:]([^/:]+)$/);
|
|
46
|
+
const name = match?.[1];
|
|
47
|
+
if (!name)
|
|
48
|
+
return null;
|
|
49
|
+
const slug = slugify(name);
|
|
50
|
+
return slug || null;
|
|
51
|
+
}
|
|
52
|
+
/** Lowercase + collapse non-alphanumerics to single dashes; trim dashes. */
|
|
53
|
+
export function slugify(input) {
|
|
54
|
+
return input
|
|
55
|
+
.toLowerCase()
|
|
56
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
57
|
+
.replace(/^-+|-+$/g, '');
|
|
58
|
+
}
|
|
59
|
+
/** The hub folder name for a proposal, given its identity + URL shape. */
|
|
60
|
+
export function proposalFolder(repo, token, shape) {
|
|
61
|
+
return shape === 'opaque' ? `p-${token}` : `${repo}-${token}`;
|
|
62
|
+
}
|
|
63
|
+
/** The public URL for a published deliverable (trailing slash → relative assets resolve). */
|
|
64
|
+
export function buildUrl(folder, type) {
|
|
65
|
+
return `https://${PROPOSALS_DOMAIN}/${folder}/${type}/`;
|
|
66
|
+
}
|
|
67
|
+
/** True when the HTML carries a `<meta name="robots" … noindex …>` (order-tolerant). */
|
|
68
|
+
export function hasNoindexMeta(html) {
|
|
69
|
+
const nameThenContent = /<meta[^>]+name=["']robots["'][^>]*content=["'][^"']*noindex[^"']*["']/i;
|
|
70
|
+
const contentThenName = /<meta[^>]+content=["'][^"']*noindex[^"']*["'][^>]*name=["']robots["']/i;
|
|
71
|
+
return nameThenContent.test(html) || contentThenName.test(html);
|
|
72
|
+
}
|
|
73
|
+
/** True when the deliverable's source dir exists in the derived repo. */
|
|
74
|
+
export function deliverableExists(root, type) {
|
|
75
|
+
return existsSync(path.join(root, DELIVERABLE_DIR[type]));
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Resolve the HTML entry filename inside a deliverable source dir. Mockups ship
|
|
79
|
+
* `index.html`; proposals ship `{slug}-proposal.html`. Returns the filename to
|
|
80
|
+
* rename to `index.html` in the hub, or null when no HTML entry is found.
|
|
81
|
+
*/
|
|
82
|
+
export function findHtmlEntry(files) {
|
|
83
|
+
if (files.includes('index.html'))
|
|
84
|
+
return 'index.html';
|
|
85
|
+
const proposal = files.find((f) => /-proposal\.html$/.test(f));
|
|
86
|
+
if (proposal)
|
|
87
|
+
return proposal;
|
|
88
|
+
const anyHtml = files.find((f) => f.endsWith('.html'));
|
|
89
|
+
return anyHtml ?? null;
|
|
90
|
+
}
|
|
91
|
+
/** Read the persisted publish state, or null when absent / unparseable. */
|
|
92
|
+
export function readPublishState(root) {
|
|
93
|
+
const file = path.join(root, PUBLISH_STATE_FILE);
|
|
94
|
+
if (!existsSync(file))
|
|
95
|
+
return null;
|
|
96
|
+
try {
|
|
97
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Write the persisted publish state (pretty-printed, trailing newline). */
|
|
104
|
+
export function writePublishState(root, state) {
|
|
105
|
+
const file = path.join(root, PUBLISH_STATE_FILE);
|
|
106
|
+
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Find an existing folder for `repo` among the hub's top-level entries (named
|
|
110
|
+
* shape only — opaque folders carry no repo name, so they rely on local state).
|
|
111
|
+
* Because the repo name is unique in the org, any `{repo}-*` match is ours.
|
|
112
|
+
* Returns the token, or null when none / ambiguous (>1 → caller confirms).
|
|
113
|
+
*/
|
|
114
|
+
export function findExistingToken(repo, hubEntries) {
|
|
115
|
+
const prefix = `${repo}-`;
|
|
116
|
+
const matches = hubEntries.filter((e) => e.startsWith(prefix));
|
|
117
|
+
if (matches.length === 0)
|
|
118
|
+
return null;
|
|
119
|
+
if (matches.length > 1)
|
|
120
|
+
return { ambiguous: true };
|
|
121
|
+
return { token: matches[0].slice(prefix.length) };
|
|
122
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* I/O seams for `factory publish` / `factory unpublish`: git + gh + filesystem.
|
|
3
|
+
* Kept apart from the pure helpers (`publish-core.ts`) and the orchestration
|
|
4
|
+
* (`commands/*.ts`) so the concurrency-sensitive bits (auth, shallow clone,
|
|
5
|
+
* rebase-retry push) test against an injectable git runner.
|
|
6
|
+
*/
|
|
7
|
+
import { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { execa } from 'execa';
|
|
10
|
+
import { CLIError } from './cli-error.js';
|
|
11
|
+
import { FACTORY_ORG } from './constants.js';
|
|
12
|
+
import { runPreflight } from './preflight.js';
|
|
13
|
+
/** Default git runner (never throws on non-zero — callers inspect `exitCode`). */
|
|
14
|
+
export const realGit = async (args, opts) => {
|
|
15
|
+
const res = await execa('git', args, { cwd: opts?.cwd, reject: false });
|
|
16
|
+
return { stdout: res.stdout ?? '', exitCode: res.exitCode ?? 1 };
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Resolve a token with push access to the hub. Dual auth (plan B-1):
|
|
20
|
+
* - `TIMEKAST_PUBLISH_TOKEN` in env → headless (Agent Server, infra TimeKast).
|
|
21
|
+
* - else → dev local: full preflight (gh + org member) then `gh auth token`.
|
|
22
|
+
* Never reads a token from a derived repo.
|
|
23
|
+
*/
|
|
24
|
+
export async function resolveAuthToken() {
|
|
25
|
+
const envToken = process.env.TIMEKAST_PUBLISH_TOKEN?.trim();
|
|
26
|
+
if (envToken)
|
|
27
|
+
return envToken;
|
|
28
|
+
await runPreflight();
|
|
29
|
+
const res = await execa('gh', ['auth', 'token'], { reject: false });
|
|
30
|
+
const token = (res.stdout ?? '').trim();
|
|
31
|
+
if (res.exitCode !== 0 || !token) {
|
|
32
|
+
throw new CLIError('No se pudo obtener un token de GitHub con `gh auth token`. Verifica `gh auth status`.');
|
|
33
|
+
}
|
|
34
|
+
return token;
|
|
35
|
+
}
|
|
36
|
+
/** The hub clone URL with an embedded token (lives only in the ephemeral tmpdir). */
|
|
37
|
+
function hubCloneUrl(token) {
|
|
38
|
+
return `https://x-access-token:${token}@github.com/${FACTORY_ORG}/proposals.git`;
|
|
39
|
+
}
|
|
40
|
+
/** Shallow-clone the hub into `destDir` (no history, no other proposals' assets). */
|
|
41
|
+
export async function cloneHubShallow(token, destDir) {
|
|
42
|
+
const res = await execa('git', ['clone', '--depth', '1', hubCloneUrl(token), destDir], {
|
|
43
|
+
reject: false,
|
|
44
|
+
});
|
|
45
|
+
if (res.exitCode !== 0) {
|
|
46
|
+
throw new CLIError(`No se pudo clonar el hub \`${FACTORY_ORG}/proposals\`. ` +
|
|
47
|
+
'Verifica que el repo exista y que tengas acceso de escritura.\n' +
|
|
48
|
+
(res.stderr ?? ''));
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** List the hub's top-level proposal folders (excludes files + `.git`). */
|
|
52
|
+
export function listHubFolders(cloneDir) {
|
|
53
|
+
return readdirSync(cloneDir)
|
|
54
|
+
.filter((e) => e !== '.git')
|
|
55
|
+
.filter((e) => {
|
|
56
|
+
try {
|
|
57
|
+
return statSync(path.join(cloneDir, e)).isDirectory();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Copy a deliverable source dir into the hub clone at `{folder}/{type}`, replacing
|
|
66
|
+
* any prior content (kills orphans), and rename the HTML entry to `index.html`.
|
|
67
|
+
* Returns the absolute path of the copied `index.html`.
|
|
68
|
+
*/
|
|
69
|
+
export function copyDeliverable(srcDir, cloneDir, folder, type, htmlEntry) {
|
|
70
|
+
const destDir = path.join(cloneDir, folder, type);
|
|
71
|
+
rmSync(destDir, { recursive: true, force: true });
|
|
72
|
+
mkdirSync(destDir, { recursive: true });
|
|
73
|
+
cpSync(srcDir, destDir, { recursive: true });
|
|
74
|
+
const indexPath = path.join(destDir, 'index.html');
|
|
75
|
+
if (htmlEntry !== 'index.html') {
|
|
76
|
+
renameSync(path.join(destDir, htmlEntry), indexPath);
|
|
77
|
+
}
|
|
78
|
+
return indexPath;
|
|
79
|
+
}
|
|
80
|
+
/** Remove a deliverable folder/type from the hub clone (for `unpublish`). */
|
|
81
|
+
export function removeDeliverable(cloneDir, folder, type) {
|
|
82
|
+
const target = path.join(cloneDir, folder, type);
|
|
83
|
+
if (!existsSync(target))
|
|
84
|
+
return false;
|
|
85
|
+
rmSync(target, { recursive: true, force: true });
|
|
86
|
+
// Prune the now-empty parent folder if no sibling deliverable remains.
|
|
87
|
+
const parent = path.join(cloneDir, folder);
|
|
88
|
+
try {
|
|
89
|
+
if (readdirSync(parent).length === 0)
|
|
90
|
+
rmSync(parent, { recursive: true, force: true });
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
/* best effort */
|
|
94
|
+
}
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
const MAX_PUSH_ATTEMPTS = 3;
|
|
98
|
+
/**
|
|
99
|
+
* Stage the given paths, commit, and push — with bounded rebase-retry to survive
|
|
100
|
+
* concurrent publishes (a second push racing the first gets `non-fast-forward`;
|
|
101
|
+
* we `pull --rebase` and retry). Uses an explicit pathspec on `add` so a dev's
|
|
102
|
+
* unrelated staged work is never swept in. No-op when nothing changed.
|
|
103
|
+
*/
|
|
104
|
+
export async function commitAndPush(cloneDir, message, paths, git = realGit) {
|
|
105
|
+
await git(['add', '--', ...paths], { cwd: cloneDir });
|
|
106
|
+
const status = await git(['status', '--porcelain'], { cwd: cloneDir });
|
|
107
|
+
if (!status.stdout.trim())
|
|
108
|
+
return; // nothing to publish — content identical
|
|
109
|
+
const commit = await git(['commit', '-m', message], { cwd: cloneDir });
|
|
110
|
+
if (commit.exitCode !== 0) {
|
|
111
|
+
throw new CLIError(`No se pudo crear el commit en el hub.\n${commit.stdout}`);
|
|
112
|
+
}
|
|
113
|
+
for (let attempt = 1; attempt <= MAX_PUSH_ATTEMPTS; attempt++) {
|
|
114
|
+
const push = await git(['push'], { cwd: cloneDir });
|
|
115
|
+
if (push.exitCode === 0)
|
|
116
|
+
return;
|
|
117
|
+
if (attempt === MAX_PUSH_ATTEMPTS)
|
|
118
|
+
break;
|
|
119
|
+
const rebase = await git(['pull', '--rebase'], { cwd: cloneDir });
|
|
120
|
+
if (rebase.exitCode !== 0) {
|
|
121
|
+
throw new CLIError('No se pudo rebasar sobre el hub remoto (conflicto inesperado). ' +
|
|
122
|
+
'Reintenta `factory publish`; si persiste, revisa el repo del hub.');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
throw new CLIError(`No se pudo pushear al hub tras ${MAX_PUSH_ATTEMPTS} intentos (mucha concurrencia). Reintenta.`);
|
|
126
|
+
}
|
|
127
|
+
/** Resolve the `origin` remote URL of a repo, or null when there is no remote. */
|
|
128
|
+
export async function gitRemoteUrl(root) {
|
|
129
|
+
const res = await execa('git', ['remote', 'get-url', 'origin'], { cwd: root, reject: false });
|
|
130
|
+
if (res.exitCode !== 0)
|
|
131
|
+
return null;
|
|
132
|
+
return res.stdout.trim() || null;
|
|
133
|
+
}
|