flows, listing translate, scan 2.2 + --originality, prices export with subscriptions, site sections
- storebound flow list|validate|run: repo-local workflows (store/workflows/*.yml, storebound.workflows.*), writes dry unless --apply, owner steps never run, --from / --resume; init templates for app and game; MCP flow_list + dry flow_run; release-flows skill - storebound listing translate|check|reviewed: per-language listing drafts with store limits and keyword rules, agent or --translate hook, marked until reviewed; MCP listing_translate / listing_check; listing-localization skill - scan: Apple 2.2 beta/demo/test wording rule; scan --originality [--against] - prices export includes subscriptions; prices import skips their rows - site: rejection scan section, Desktop app section with fixture-mode screenshots, Everything else grid, FAQ 4.3 answer - README, CHANGELOG, adapters, API tables
This commit is contained in:
parent
e44897ca4e
commit
526dfd3b09
45 changed files with 2176 additions and 53 deletions
|
|
@ -15,7 +15,7 @@ export function parseArgs(argv: string[], booleans: string[] = []): Args {
|
|||
const repeated = new Map<string, string[]>();
|
||||
const set = (k: string, v: string) => { flags.set(k, v); repeated.set(k, [...(repeated.get(k) ?? []), v]); };
|
||||
const _: string[] = [];
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', ...booleans]);
|
||||
const bool = new Set(['dry', 'yes', 'help', 'json', 'verbose', 'all-pages', 'apply', 'resume', 'force', ...booleans]);
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (!a.startsWith('--')) { _.push(a); continue; }
|
||||
|
|
|
|||
320
cli/lib/flow.ts
Normal file
320
cli/lib/flow.ts
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
// Repo-local workflows (`storebound flow`): named, ordered storebound steps kept in the project, e.g. a release flow
|
||||
// next-build -> build -> upload -> wait -> whats-new apply -> validate -> scan -> plan -> your Submit click. Pure parts:
|
||||
// reading and checking the definitions, classifying each step (read / write / owner / shell / wait), variables, `if`
|
||||
// conditions and the run plan. The runner is cli/flow.ts.
|
||||
//
|
||||
// Where flows live (all are read; a name defined twice is an error):
|
||||
// storebound.workflows.(yml|yaml|json|ts) several flows: { flows: { <name>: Flow } } or { <name>: Flow }
|
||||
// store/workflows/<name>.(yml|yaml|json|ts) one flow per file, named after the file
|
||||
// A flow:
|
||||
// description: text
|
||||
// params: { VERSION: "1.0.0" } defaults; `flow run release VERSION=1.2.0` overrides
|
||||
// before: [steps] steps: [steps] after: [steps] onError: [steps] (hooks: before / after the steps, on a failure)
|
||||
// private: true only usable as a sub-flow (`flow: <name>` step), not listed or run directly
|
||||
// A step (exactly one of run / sh / owner / flow):
|
||||
// id: next-build unique in the flow; `--from <id>` resumes there
|
||||
// run: apple next-build a storebound command line (no "storebound" prefix); ${VAR} substituted
|
||||
// sh: npm run build:web a shell command of yours: only runs with --apply
|
||||
// owner: "App Store Connect: Submit for Review" never run: shown as "your click"
|
||||
// flow: beta the steps of another flow (ids prefixed "beta.")
|
||||
// capture: BUILD the last stdout line becomes ${BUILD} for later steps
|
||||
// if: apple | play | exists <path> | ${VAR} | !${VAR} | ${A} == x | ${A} != x
|
||||
// continueOnError: true a failure is reported and the flow goes on
|
||||
// Safety: write steps run with --dry unless `flow run --apply`; `--yes` is refused in any step (the commands ask the
|
||||
// owner themselves); owner steps (submit, release, rollout, sending replies, price changes, inviting testers, starting
|
||||
// experiments ...) are never executed, also when written as `run:`.
|
||||
|
||||
export type StepKind = 'read' | 'write' | 'wait' | 'owner' | 'shell';
|
||||
|
||||
export interface FlowStep {
|
||||
id: string;
|
||||
run?: string;
|
||||
sh?: string;
|
||||
owner?: string;
|
||||
flow?: string;
|
||||
capture?: string;
|
||||
if?: string;
|
||||
continueOnError?: boolean;
|
||||
/** Free text shown next to the step. */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface Flow {
|
||||
name: string;
|
||||
file: string;
|
||||
description?: string;
|
||||
params: Record<string, string>;
|
||||
before: FlowStep[];
|
||||
steps: FlowStep[];
|
||||
after: FlowStep[];
|
||||
onError: FlowStep[];
|
||||
private: boolean;
|
||||
}
|
||||
|
||||
/** Commands that only read (stores or local files); they run for real in every mode except a --dry plan. */
|
||||
const READ: string[][] = [
|
||||
['check'], ['validate'], ['scan'], ['inspect'], ['doctor'], ['apps'], ['release', 'status'], ['release', 'plan'], ['originality'],
|
||||
['apple', 'next-build'], ['play', 'next-version-code'], ['apple', 'status'], ['play', 'status'], ['health'], ['catalog', 'diff'], ['triage'],
|
||||
['shots', 'check'], ['whats-new', 'check'], ['listing', 'check'], ['apple', 'testflight', 'status'], ['apple', 'testflight', 'groups'],
|
||||
['apple', 'signing', 'status'], ['apple', 'preorder', 'status'], ['apple', 'cpp', 'list'], ['apple', 'events', 'list'], ['ads', 'scan'],
|
||||
['privacy-manifest'], ['apple', 'encryption'], ['ws', 'list'], ['ws', 'status'], ['ws', 'check'], ['ws', 'validate'], ['apple', 'adhoc', 'devices'],
|
||||
['revenuecat', 'diff'], ['ads', 'apple', 'status'], ['ads', 'apple', 'campaigns'], ['ads', 'apple', 'report'], ['analytics', 'compare'],
|
||||
];
|
||||
/** Waits for a store (build processing): with --dry it checks once instead of waiting. */
|
||||
const WAIT: string[][] = [['apple', 'testflight', 'wait']];
|
||||
/** Never executed by a flow: the owner does these (AGENTS.md rule 1). */
|
||||
const OWNER: string[][] = [
|
||||
['apple', 'release'], ['play', 'rollout'], ['reviews', 'send'], ['prices', 'import'], ['apple', 'iap-submit'], ['apple', 'ppo', 'start'], ['apple', 'ppo', 'stop'],
|
||||
['apple', 'cpp', 'submit'], ['apple', 'cpp', 'visible'], ['apple', 'events', 'submit'], ['apple', 'preorder', 'enable'], ['apple', 'preorder', 'end'],
|
||||
['apple', 'testflight', 'testers'], ['apple', 'testflight', 'expire'], ['apple', 'offer-codes'], ['apple', 'win-back'], ['ads', 'apple', 'bid'],
|
||||
['ads', 'apple', 'budget'], ['ads', 'apple', 'pause'], ['apple', 'adhoc', 'register'],
|
||||
];
|
||||
const OWNER_ARGS = ['--submit-review', '--manual-release', '--cancel-submission', '--production', '--phased', 'submit', 'publish', '--remove', '--invite'];
|
||||
/** Never allowed inside a flow step. */
|
||||
const REFUSED_ARGS = ['--yes', '--apply'];
|
||||
|
||||
/** Words of a command line, honouring "double" and 'single' quotes. */
|
||||
export function splitArgs(line: string): string[] {
|
||||
const out: string[] = [];
|
||||
let cur = '', q: string | null = null, any = false;
|
||||
for (const c of line.trim()) {
|
||||
if (q) { if (c === q) q = null; else cur += c; continue; }
|
||||
if (c === '"' || c === '\'') { q = c; any = true; continue; }
|
||||
if (/\s/.test(c)) { if (cur || any) out.push(cur); cur = ''; any = false; continue; }
|
||||
cur += c;
|
||||
}
|
||||
if (q) throw new Error(`unterminated quote in: ${line}`);
|
||||
if (cur || any) out.push(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
const words = (argv: string[]): string[] => { const w: string[] = []; for (const a of argv) { if (a.startsWith('-')) break; w.push(a); } return w; };
|
||||
const starts = (w: string[], p: string[]) => p.length <= w.length && p.every((x, i) => w[i] === x);
|
||||
|
||||
/** What a `run:` step is. */
|
||||
export function classify(argv: string[]): StepKind {
|
||||
const w = words(argv);
|
||||
if (OWNER.some(p => starts(w, p)) || argv.some(a => OWNER_ARGS.includes(a))) return argv.includes('--dry') && !argv.some(a => OWNER_ARGS.includes(a)) ? 'read' : 'owner';
|
||||
if (WAIT.some(p => starts(w, p))) return 'wait';
|
||||
if (READ.some(p => starts(w, p))) return 'read';
|
||||
// `api` reads run, writes stay dry inside the command itself; treat it as a write so it gets --dry
|
||||
return 'write';
|
||||
}
|
||||
|
||||
export const kindOf = (s: FlowStep, argv?: string[]): StepKind =>
|
||||
s.owner !== undefined ? 'owner' : s.sh !== undefined ? 'shell' : classify(argv ?? splitArgs(s.run ?? ''));
|
||||
|
||||
// ---- loading ----
|
||||
|
||||
const ID_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
|
||||
const VAR_RE = /^[A-Z][A-Z0-9_]{0,40}$/;
|
||||
const STEP_KEYS = ['id', 'run', 'sh', 'owner', 'flow', 'capture', 'if', 'continueOnError', 'note'];
|
||||
const FLOW_KEYS = ['description', 'params', 'before', 'steps', 'after', 'onError', 'private'];
|
||||
|
||||
function asSteps(v: unknown, where: string, e: string[]): FlowStep[] {
|
||||
if (v === undefined || v === null) return [];
|
||||
if (!Array.isArray(v)) { e.push(`${where}: must be a list of steps`); return []; }
|
||||
const out: FlowStep[] = [];
|
||||
v.forEach((x, i) => {
|
||||
const at = `${where}[${i}]`;
|
||||
if (typeof x !== 'object' || x === null || Array.isArray(x)) { e.push(`${at}: a step is a map (id, run | sh | owner | flow, ...)`); return; }
|
||||
const o = x as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!STEP_KEYS.includes(k)) e.push(`${at}: unknown key "${k}" (${STEP_KEYS.join(', ')})`);
|
||||
const kinds = ['run', 'sh', 'owner', 'flow'].filter(k => o[k] !== undefined);
|
||||
if (kinds.length !== 1) e.push(`${at}: exactly one of run, sh, owner, flow`);
|
||||
for (const k of ['id', 'run', 'sh', 'owner', 'flow', 'capture', 'if', 'note']) if (o[k] !== undefined && typeof o[k] !== 'string') e.push(`${at}.${k}: must be a string`);
|
||||
const id = typeof o.id === 'string' ? o.id : typeof o.flow === 'string' ? o.flow : '';
|
||||
if (!ID_RE.test(id)) e.push(`${at}.id: "${id}" (lowercase letters, digits, . _ -)`);
|
||||
if (o.capture !== undefined && !VAR_RE.test(String(o.capture))) e.push(`${at}.capture: an UPPER_CASE name`);
|
||||
if (o.continueOnError !== undefined && typeof o.continueOnError !== 'boolean') e.push(`${at}.continueOnError: true or false`);
|
||||
out.push({ ...(o as unknown as FlowStep), id });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One flow definition (already parsed from YAML / JSON / TS) -> Flow, with every problem. */
|
||||
export function toFlow(name: string, file: string, v: unknown): { flow: Flow | null; errors: string[] } {
|
||||
const e: string[] = [];
|
||||
const at = `${file}: ${name}`;
|
||||
if (!ID_RE.test(name)) e.push(`${at}: flow name must be lowercase letters, digits, . _ -`);
|
||||
if (typeof v !== 'object' || v === null || Array.isArray(v)) return { flow: null, errors: [...e, `${at}: a flow is a map (description, params, steps, ...)`] };
|
||||
const o = v as Record<string, unknown>;
|
||||
for (const k of Object.keys(o)) if (!FLOW_KEYS.includes(k)) e.push(`${at}: unknown key "${k}" (${FLOW_KEYS.join(', ')})`);
|
||||
const params: Record<string, string> = {};
|
||||
if (o.params !== undefined) {
|
||||
if (typeof o.params !== 'object' || o.params === null || Array.isArray(o.params)) e.push(`${at}.params: a map of NAME: default`);
|
||||
else for (const [k, val] of Object.entries(o.params)) {
|
||||
if (!VAR_RE.test(k)) e.push(`${at}.params.${k}: UPPER_CASE names`);
|
||||
params[k] = val === null || val === undefined ? '' : String(val);
|
||||
}
|
||||
}
|
||||
const flow: Flow = {
|
||||
name, file, ...(typeof o.description === 'string' ? { description: o.description } : {}), params,
|
||||
before: asSteps(o.before, `${at}.before`, e), steps: asSteps(o.steps, `${at}.steps`, e), after: asSteps(o.after, `${at}.after`, e),
|
||||
onError: asSteps(o.onError, `${at}.onError`, e), private: o.private === true,
|
||||
};
|
||||
if (!flow.steps.length) e.push(`${at}: no steps`);
|
||||
return { flow, errors: e };
|
||||
}
|
||||
|
||||
/** Flows of one file: a single-flow file (store/workflows/<name>.*) or a multi-flow file (storebound.workflows.*). */
|
||||
export function flowsOfFile(file: string, data: unknown, single: string | null): { flows: Flow[]; errors: string[] } {
|
||||
if (single) { const r = toFlow(single, file, data); return { flows: r.flow ? [r.flow] : [], errors: r.errors }; }
|
||||
if (typeof data !== 'object' || data === null || Array.isArray(data)) return { flows: [], errors: [`${file}: expected a map of flows`] };
|
||||
const d = data as Record<string, unknown>;
|
||||
const map = (d.flows && typeof d.flows === 'object' && !Array.isArray(d.flows) ? d.flows : d) as Record<string, unknown>;
|
||||
const flows: Flow[] = [], errors: string[] = [];
|
||||
for (const [n, v] of Object.entries(map)) { const r = toFlow(n, file, v); if (r.flow) flows.push(r.flow); errors.push(...r.errors); }
|
||||
return { flows, errors };
|
||||
}
|
||||
|
||||
/** Steps with `flow:` sub-flows expanded (ids prefixed), with cycle and unknown-flow errors. */
|
||||
export function expand(flow: Flow, all: Map<string, Flow>, part: 'before' | 'steps' | 'after' | 'onError' = 'steps', stack: string[] = []): { steps: FlowStep[]; errors: string[]; params: Record<string, string> } {
|
||||
const errors: string[] = [];
|
||||
const out: FlowStep[] = [];
|
||||
const params: Record<string, string> = {};
|
||||
for (const s of flow[part]) {
|
||||
if (s.flow === undefined) { out.push(s); continue; }
|
||||
const sub = all.get(s.flow);
|
||||
if (!sub) { errors.push(`${flow.name}: step ${s.id}: no flow "${s.flow}"`); continue; }
|
||||
if ([...stack, flow.name].includes(sub.name)) { errors.push(`${flow.name}: cycle ${[...stack, flow.name, sub.name].join(' -> ')}`); continue; }
|
||||
const r = expand(sub, all, 'steps', [...stack, flow.name]);
|
||||
errors.push(...r.errors);
|
||||
for (const [k, v] of Object.entries({ ...sub.params, ...r.params })) if (!(k in params)) params[k] = v;
|
||||
for (const x of r.steps) out.push({ ...x, id: `${s.id}.${x.id}`, ...(s.if && x.if ? { if: `${s.if} && ${x.if}` } : s.if ? { if: s.if } : {}) });
|
||||
}
|
||||
return { steps: out, errors, params };
|
||||
}
|
||||
|
||||
/** Everything wrong with a set of flows: duplicate names and ids, refused args, unknown commands and variables. */
|
||||
export function validateFlows(flows: Flow[], o: { commands?: Set<string> } = {}): string[] {
|
||||
const e: string[] = [];
|
||||
const all = new Map<string, Flow>();
|
||||
for (const f of flows) { if (all.has(f.name)) e.push(`flow "${f.name}" is defined in ${all.get(f.name)!.file} and ${f.file}`); else all.set(f.name, f); }
|
||||
for (const f of all.values()) {
|
||||
const vars = new Set(Object.keys(f.params));
|
||||
for (const part of ['before', 'steps', 'after', 'onError'] as const) {
|
||||
const r = expand(f, all, part);
|
||||
e.push(...r.errors);
|
||||
for (const k of Object.keys(r.params)) vars.add(k);
|
||||
const ids = new Set<string>();
|
||||
for (const s of r.steps) {
|
||||
const at = `${f.name}: ${part === 'steps' ? '' : `${part} `}step ${s.id}`;
|
||||
if (ids.has(s.id)) e.push(`${at}: id used twice`);
|
||||
ids.add(s.id);
|
||||
for (const t of [s.run, s.sh, s.owner, s.if].filter((x): x is string => typeof x === 'string'))
|
||||
for (const m of t.matchAll(/\$\{([^}]*)\}/g)) if (!vars.has(m[1]!) && !/^env\.[A-Z0-9_]+$/.test(m[1]!)) e.push(`${at}: \${${m[1]}} is not a param or an earlier capture`);
|
||||
if (s.capture) vars.add(s.capture);
|
||||
if (s.run !== undefined) {
|
||||
let argv: string[] = [];
|
||||
try { argv = splitArgs(s.run); } catch (x) { e.push(`${at}: ${(x as Error).message}`); continue; }
|
||||
if (!argv.length) { e.push(`${at}: empty run`); continue; }
|
||||
if (argv[0] === 'storebound') e.push(`${at}: write the command without "storebound" (run: ${argv.slice(1).join(' ')})`);
|
||||
if (argv[0] === 'flow') e.push(`${at}: use a "flow: <name>" step instead of run: flow ...`);
|
||||
const bad = argv.find(a => REFUSED_ARGS.includes(a.split('=')[0]!));
|
||||
if (bad) e.push(`${at}: ${bad} is not allowed in a flow (writes are confirmed by the owner, --apply is for flow run)`);
|
||||
if (o.commands) {
|
||||
const w = words(argv);
|
||||
const known = o.commands.has(`${w[0]} ${w[1]}`) || o.commands.has(`${w[0]} ${w[1]} ${w[2]}`) || o.commands.has(w[0] ?? '');
|
||||
if (!known && argv[0] !== 'storebound' && argv[0] !== 'flow') e.push(`${at}: "${w.slice(0, 2).join(' ')}" is not a storebound command`);
|
||||
}
|
||||
}
|
||||
if (s.if !== undefined && !/\S/.test(s.if)) e.push(`${at}: empty if`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return e;
|
||||
}
|
||||
|
||||
// ---- variables, conditions ----
|
||||
|
||||
/** ${VAR} and ${env.NAME} substituted; unknown ones stay as written (the plan shows them). */
|
||||
export function substitute(text: string, vars: Record<string, string>, env: Record<string, string | undefined> = {}): string {
|
||||
return text.replace(/\$\{([^}]*)\}/g, (m, k: string) => (k.startsWith('env.') ? env[k.slice(4)] ?? m : vars[k] ?? m));
|
||||
}
|
||||
|
||||
export interface CondCtx { apple: boolean; play: boolean; exists(path: string): boolean }
|
||||
|
||||
/** `if:` after substitution: apple | play | exists <path> | !x | a == b | a != b | x (non-empty, not false / 0); && joins. */
|
||||
export function evalIf(expr: string, c: CondCtx): boolean {
|
||||
return expr.split('&&').every(part => {
|
||||
const s = part.trim();
|
||||
if (s.startsWith('!')) return !evalIf(s.slice(1), c);
|
||||
if (s === 'apple') return c.apple;
|
||||
if (s === 'play') return c.play;
|
||||
const ex = /^exists\s+(.+)$/.exec(s);
|
||||
if (ex) return c.exists(ex[1]!.trim());
|
||||
const cmp = /^(.*?)\s*(==|!=)\s*(.*)$/.exec(s);
|
||||
if (cmp) { const eq = cmp[1]!.trim() === cmp[3]!.trim(); return cmp[2] === '==' ? eq : !eq; }
|
||||
return s !== '' && s !== 'false' && s !== '0' && !/^\$\{[^}]*\}$/.test(s);
|
||||
});
|
||||
}
|
||||
|
||||
/** `KEY=value` positionals of `flow run <name> KEY=value ...`. */
|
||||
export function parseParams(args: string[]): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const a of args) {
|
||||
const i = a.indexOf('=');
|
||||
if (i < 1 || !VAR_RE.test(a.slice(0, i))) throw new Error(`"${a}": parameters are NAME=value (UPPER_CASE name)`);
|
||||
out[a.slice(0, i)] = a.slice(i + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- the plan ----
|
||||
|
||||
export type Mode = 'plan' | 'dry' | 'apply';
|
||||
|
||||
export interface PlannedStep {
|
||||
id: string;
|
||||
part: 'before' | 'steps' | 'after' | 'onError';
|
||||
kind: StepKind;
|
||||
/** What runs: storebound argv (run steps), the shell line (sh), the owner's click text (owner). */
|
||||
argv?: string[];
|
||||
shell?: string;
|
||||
owner?: string;
|
||||
/** Not run in this mode, and why. */
|
||||
skip?: string;
|
||||
/** --dry was added (write steps without --apply, wait steps without --apply). */
|
||||
dryAdded: boolean;
|
||||
capture?: string;
|
||||
continueOnError: boolean;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
/** How one step runs in a mode, with the variables known so far. Pure. */
|
||||
export function planStep(s: FlowStep, part: PlannedStep['part'], mode: Mode, vars: Record<string, string>, c: CondCtx, env: Record<string, string | undefined> = {}): PlannedStep {
|
||||
const base = { id: s.id, part, continueOnError: !!s.continueOnError, ...(s.capture ? { capture: s.capture } : {}), ...(s.note ? { note: s.note } : {}) };
|
||||
if (s.if !== undefined && !evalIf(substitute(s.if, vars, env), c)) {
|
||||
const what = s.owner !== undefined ? { owner: substitute(s.owner, vars, env) } : s.sh !== undefined ? { shell: substitute(s.sh, vars, env) } : { argv: splitArgs(substitute(s.run ?? '', vars, env)) };
|
||||
return { ...base, ...what, kind: kindOf(s), dryAdded: false, skip: `if ${s.if}: false` };
|
||||
}
|
||||
if (s.owner !== undefined) return { ...base, kind: 'owner', owner: substitute(s.owner, vars, env), dryAdded: false, skip: 'your click' };
|
||||
if (s.sh !== undefined) {
|
||||
const shell = substitute(s.sh, vars, env);
|
||||
return { ...base, kind: 'shell', shell, dryAdded: false, ...(mode === 'apply' ? {} : { skip: 'shell step: runs with --apply' }) };
|
||||
}
|
||||
const argv = splitArgs(substitute(s.run ?? '', vars, env));
|
||||
const kind = classify(argv);
|
||||
if (kind === 'owner') return { ...base, kind, owner: `storebound ${argv.join(' ')}`, dryAdded: false, skip: 'your click (owner step: run it yourself after checking)' };
|
||||
const addDry = (kind === 'write' || kind === 'wait') && mode !== 'apply' && !argv.includes('--dry');
|
||||
return { ...base, kind, argv: addDry ? [...argv, '--dry'] : argv, dryAdded: addDry, ...(mode === 'plan' ? { skip: 'plan only' } : {}) };
|
||||
}
|
||||
|
||||
/** Index of the step to start from: --from <id> (exact, or the first id under a sub-flow prefix). */
|
||||
export function startIndex(steps: FlowStep[], from: string | undefined): number {
|
||||
if (!from) return 0;
|
||||
const i = steps.findIndex(s => s.id === from || s.id.startsWith(`${from}.`));
|
||||
if (i < 0) throw new Error(`--from ${from}: no such step (${steps.map(s => s.id).join(', ')})`);
|
||||
return i;
|
||||
}
|
||||
|
||||
export interface StepResult { id: string; part: PlannedStep['part']; kind: StepKind; status: 'ok' | 'failed' | 'skipped' | 'owner' | 'planned'; exitCode?: number; ms?: number; detail?: string; command?: string }
|
||||
export interface RunState { flow: string; mode: Mode; startedAt: string; finishedAt?: string; vars: Record<string, string>; results: StepResult[]; ok: boolean }
|
||||
|
||||
/** First step of the last run that did not finish (failed, or never reached): where `--resume` starts. */
|
||||
export function resumePoint(steps: FlowStep[], last: RunState | null): string | undefined {
|
||||
if (!last) return undefined;
|
||||
const done = new Set(last.results.filter(r => r.part === 'steps' && (r.status === 'ok' || r.status === 'skipped' || r.status === 'owner')).map(r => r.id));
|
||||
return steps.find(s => !done.has(s.id))?.id;
|
||||
}
|
||||
158
cli/lib/listing-translate.ts
Normal file
158
cli/lib/listing-translate.ts
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
// Listing localization: per-language sections of the two listing files (store/appstore.md, store/listing.md) as
|
||||
// translation drafts. Pure. The CLI never calls a translation service: your agent translates the status=translate
|
||||
// sections (listing-localization skill), or `storebound listing translate --translate "<command>"` runs a command of
|
||||
// yours once per field. Every generated section carries a marker line until a human reviewed it:
|
||||
// <!-- storebound-translation from=en-US status=translate --> source text copied in, still to translate
|
||||
// <!-- storebound-translation from=en-US status=draft --> machine-translated: review, then `listing reviewed`
|
||||
// Limits per store field (characters; App Store keywords also 100 bytes, as the existing listing check counts them):
|
||||
// App Store (appStoreVersionLocalizations / appInfoLocalizations): name 30, subtitle 30, promotionalText 170,
|
||||
// keywords 100, description 4000. https://developer.apple.com/help/app-store-connect/reference/app-information
|
||||
// Google Play (edits.listings): title 30, shortDescription 80, fullDescription 4000.
|
||||
// https://support.google.com/googleplay/android-developer/answer/9859152
|
||||
// Keyword rules (App Store): comma separated, no spaces around commas, no duplicates, no words already in the name or
|
||||
// subtitle (they are indexed anyway), whole keywords cut at the limit.
|
||||
import { APPLE_LIMITS, len, PLAY_LIMITS } from './copy';
|
||||
|
||||
export type TStatus = 'translate' | 'draft';
|
||||
export const MARK_RE = /^<!--\s*storebound-translation\s+from=(\S+)\s+status=(translate|draft)\s*-->\s*$/m;
|
||||
export const mark = (from: string, status: TStatus): string => `<!-- storebound-translation from=${from} status=${status} -->`;
|
||||
|
||||
export const APPLE_FIELDS = ['name', 'subtitle', 'promotionalText', 'keywords', 'description'] as const;
|
||||
export type AppleTField = typeof APPLE_FIELDS[number];
|
||||
export const PLAY_FIELDS = ['title', 'short', 'full'] as const;
|
||||
export type PlayTField = typeof PLAY_FIELDS[number];
|
||||
export const FIELD_LIMITS = {
|
||||
apple: Object.fromEntries(APPLE_FIELDS.map(f => [f, APPLE_LIMITS[f]])) as Record<AppleTField, number>,
|
||||
play: { title: PLAY_LIMITS.title, short: PLAY_LIMITS.short, full: PLAY_LIMITS.full } as Record<PlayTField, number>,
|
||||
};
|
||||
|
||||
const fence = (t: string) => '```\n' + t + '\n```';
|
||||
|
||||
/** "## " sections of a listing file (index 0 = the preamble). */
|
||||
export const sections = (md: string): string[] => md.split(/^(?=## )/m);
|
||||
|
||||
/** "### heading" -> first fenced block text, in order. */
|
||||
export function blocksOf(sec: string): { heading: string; text: string }[] {
|
||||
const out: { heading: string; text: string }[] = [];
|
||||
for (const part of sec.split(/^### /m).slice(1)) {
|
||||
const heading = part.split('\n')[0]!.trim();
|
||||
const m = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(part);
|
||||
if (m) out.push({ heading, text: m[1]!.trim() });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const appleLocaleOf = (sec: string): string | null => {
|
||||
if (!sec.startsWith('## ')) return null;
|
||||
const l = sec.slice(3).split(/[\s·]/)[0]!.trim();
|
||||
return /^[a-z]{2,3}(-[A-Za-z]{2,4})?$/.test(l) ? l : null;
|
||||
};
|
||||
export const playCodesOf = (sec: string): string[] => {
|
||||
const m = /^<!--\s*play:\s*([^>]+?)\s*-->$/m.exec(sec);
|
||||
return m ? m[1]!.split(',').map(s => s.trim()).filter(Boolean) : [];
|
||||
};
|
||||
export function markerOf(sec: string): { from: string; status: TStatus } | null {
|
||||
const m = MARK_RE.exec(sec);
|
||||
return m ? { from: m[1]!, status: m[2] as TStatus } : null;
|
||||
}
|
||||
|
||||
export function appleFields(sec: string): Partial<Record<AppleTField | 'whatsNew', string>> {
|
||||
const out: Partial<Record<AppleTField | 'whatsNew', string>> = {};
|
||||
for (const b of blocksOf(sec)) if ((APPLE_FIELDS as readonly string[]).includes(b.heading) || b.heading === 'whatsNew') out[b.heading as AppleTField] = b.text;
|
||||
return out;
|
||||
}
|
||||
|
||||
export function playFields(sec: string): Partial<Record<PlayTField | 'whatsNew', string>> {
|
||||
const out: Partial<Record<PlayTField | 'whatsNew', string>> = {};
|
||||
for (const b of blocksOf(sec)) {
|
||||
const k = /what'?s new|release notes/i.test(b.heading) ? 'whatsNew' : /\btitle\b/i.test(b.heading) ? 'title' : /\bshort\b/i.test(b.heading) ? 'short' : /\bfull\b/i.test(b.heading) ? 'full' : null;
|
||||
if (k && out[k] === undefined) out[k] = b.text;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const findAppleSection = (md: string, locale: string): string | undefined => sections(md).find(s => appleLocaleOf(s) === locale);
|
||||
export const findPlaySection = (md: string, codes: string[]): string | undefined => sections(md).find(s => playCodesOf(s).some(c => codes.includes(c)));
|
||||
|
||||
export function appleSectionText(locale: string, label: string, f: Partial<Record<AppleTField | 'whatsNew', string>>, marker: string | null): string {
|
||||
const parts = [`## ${locale}${label ? ` · ${label}` : ''}`, ...(marker ? [marker] : []), ''];
|
||||
for (const k of [...APPLE_FIELDS, 'whatsNew'] as const) if (f[k] !== undefined && f[k] !== '') parts.push(`### ${k}`, fence(f[k]!), '');
|
||||
return parts.join('\n') + '\n';
|
||||
}
|
||||
|
||||
const PLAY_HEAD: Record<PlayTField | 'whatsNew', string> = { title: 'Play title (max 30)', short: 'Play short description (max 80)', full: 'Play full description (max 4000)', whatsNew: 'What\'s new (max 500)' };
|
||||
export function playSectionText(codes: string[], label: string, f: Partial<Record<PlayTField | 'whatsNew', string>>, marker: string | null): string {
|
||||
const parts = [`## ${label || codes[0]} (${codes.join(', ')})`, `<!-- play: ${codes.join(', ')} -->`, ...(marker ? [marker] : []), ''];
|
||||
for (const k of [...PLAY_FIELDS, 'whatsNew'] as const) if (f[k] !== undefined && f[k] !== '') parts.push(`### ${PLAY_HEAD[k]}`, fence(f[k]!), '');
|
||||
return parts.join('\n') + '\n';
|
||||
}
|
||||
|
||||
/** Replaces the section `old` (exact text) with `text`, or appends `text` at the end. */
|
||||
export function putSection(md: string, old: string | undefined, text: string): string {
|
||||
if (old !== undefined) {
|
||||
const parts = sections(md);
|
||||
const i = parts.indexOf(old);
|
||||
// keep what ended the old section (blank lines, a --- rule)
|
||||
let body = old.replace(/\s+$/, '');
|
||||
while (/\n---$/.test(body)) body = body.slice(0, -4).replace(/\s+$/, '');
|
||||
const tail = old.slice(body.length);
|
||||
parts[i] = text.replace(/\s+$/, '') + (tail || '\n');
|
||||
return parts.join('');
|
||||
}
|
||||
return md.replace(/\s*$/, '') + '\n\n' + text;
|
||||
}
|
||||
|
||||
/** Removes the translation marker of one section (after review). */
|
||||
export const unmark = (sec: string): string => sec.replace(/^<!--\s*storebound-translation[^>]*-->[ \t]*\n/m, '');
|
||||
|
||||
// ---- keyword rules ----
|
||||
|
||||
/** App Store keywords: split on commas (also 、,،), trimmed, deduplicated (case-insensitive), words of the name /
|
||||
* subtitle dropped, joined with "," and cut at whole keywords to fit 100 characters and 100 bytes. Pure. */
|
||||
export function normalizeKeywords(text: string, o: { name?: string; subtitle?: string; limit?: number } = {}): { text: string; dropped: { kw: string; why: string }[] } {
|
||||
const limit = o.limit ?? APPLE_LIMITS.keywords;
|
||||
const taken = new Set(`${o.name ?? ''} ${o.subtitle ?? ''}`.toLocaleLowerCase().split(/[\s,.:;!?·|/–-]+/).filter(w => w.length > 1));
|
||||
const seen = new Set<string>();
|
||||
const dropped: { kw: string; why: string }[] = [];
|
||||
const kept: string[] = [];
|
||||
for (const raw of text.split(/[,、,،;\n]/)) {
|
||||
const kw = raw.trim().replace(/\s+/g, ' ');
|
||||
if (!kw) continue;
|
||||
const key = kw.toLocaleLowerCase();
|
||||
if (seen.has(key)) { dropped.push({ kw, why: 'duplicate' }); continue; }
|
||||
seen.add(key);
|
||||
if (taken.has(key)) { dropped.push({ kw, why: 'already in the name or subtitle' }); continue; }
|
||||
const next = [...kept, kw].join(',');
|
||||
if (len(next) > limit || Buffer.byteLength(next) > limit) { dropped.push({ kw, why: `over ${limit}` }); continue; }
|
||||
kept.push(kw);
|
||||
}
|
||||
return { text: kept.join(','), dropped };
|
||||
}
|
||||
|
||||
export interface FieldCheck { store: 'apple' | 'play'; field: string; chars: number; limit: number; problems: string[] }
|
||||
|
||||
/** Limits and rules of one translated section. `source` = the source language's fields (identical text is flagged). */
|
||||
export function checkFields(store: 'apple' | 'play', f: Record<string, string | undefined>, source: Record<string, string | undefined> = {}, status?: TStatus): FieldCheck[] {
|
||||
const fields = store === 'apple' ? APPLE_FIELDS : PLAY_FIELDS;
|
||||
const out: FieldCheck[] = [];
|
||||
for (const k of fields) {
|
||||
const v = f[k];
|
||||
if (v === undefined) continue;
|
||||
const limit = (FIELD_LIMITS[store] as Record<string, number>)[k]!;
|
||||
const c: FieldCheck = { store, field: k, chars: len(v), limit, problems: [] };
|
||||
if (len(v) > limit) c.problems.push(`${len(v)} > ${limit} characters`);
|
||||
if (store === 'apple' && k === 'keywords') {
|
||||
if (Buffer.byteLength(v) > limit) c.problems.push(`${Buffer.byteLength(v)} bytes > ${limit}`);
|
||||
if (/,\s|\s,/.test(v)) c.problems.push('spaces around commas');
|
||||
const words = v.split(',').map(w => w.trim().toLocaleLowerCase()).filter(Boolean);
|
||||
const dup = words.filter((w, i) => words.indexOf(w) !== i);
|
||||
if (dup.length) c.problems.push(`duplicates: ${[...new Set(dup)].join(', ')}`);
|
||||
if (/,,|^,|,$/.test(v)) c.problems.push('empty keyword');
|
||||
}
|
||||
if (!v.trim() && k !== 'title' && k !== 'name') c.problems.push('empty');
|
||||
if (status === 'translate') c.problems.push('not translated yet (status=translate)');
|
||||
else if (source[k] !== undefined && v.trim() === source[k]!.trim() && v.trim().length > 12) c.problems.push('identical to the source language');
|
||||
out.push(c);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -6,7 +6,8 @@ import { CONFIG_NAMES, loadConfig, type ShipConfig } from '../config';
|
|||
import { reviewDemoAccount } from '../credentials';
|
||||
import { proposeDeclarations, type Proposal } from './declare';
|
||||
import { detectProject, ECO_LABEL, type ProjectFacts, type Stack, where } from './project';
|
||||
import { type ScanFinding, scanRules, type Severity } from './rules';
|
||||
import type { OriginalityReport } from '../originality';
|
||||
import { APPLE_GUIDELINES, type ScanFinding, scanRules, type Severity, sortScan } from './rules';
|
||||
import type { SdkCategory } from './sdks';
|
||||
|
||||
export interface ScanReport {
|
||||
|
|
@ -23,6 +24,8 @@ export interface ScanReport {
|
|||
declarations: Proposal;
|
||||
scanned: number;
|
||||
notes: string[];
|
||||
/** `scan --originality`: the 4.3 / repetitive content comparison with the owner's other apps. */
|
||||
originality?: { compared: number; flagged: number; threshold: number; pairs: { app: string; folder: string; overall: number; flagged: boolean }[] } | { error: string };
|
||||
}
|
||||
|
||||
export interface ScanRun { report: ScanReport; facts: ProjectFacts; config: ShipConfig | null; configPath: string | null }
|
||||
|
|
@ -122,7 +125,34 @@ export function formatScan(r: ScanReport, o: { declarations?: boolean } = {}): s
|
|||
if (d.appPrivacyChange) L.push(` ~ appPrivacy.tracking: ${d.appPrivacyChange.from ?? 'unset'} -> ${d.appPrivacyChange.to}`);
|
||||
} else if (r.config) L.push('', ` No changes to ${r.config}: the dataSafety / appPrivacy blocks already cover what was detected.`);
|
||||
}
|
||||
if (r.originality) {
|
||||
if ('error' in r.originality) L.push('', `Originality (4.3): not run: ${r.originality.error}`);
|
||||
else L.push('', `Originality (4.3 / Play repetitive content): ${r.originality.compared} app(s) compared, ${r.originality.flagged} near-duplicate(s) at ${r.originality.threshold}${r.originality.pairs.length ? ` · ${r.originality.pairs.map(p => `${p.app} ${Math.round(p.overall * 100)}%`).join(', ')}` : ''}`);
|
||||
}
|
||||
if (r.notes.length) L.push('', ...r.notes.map(n => `note: ${n}`));
|
||||
L.push('', 'Checked at review, not by scan: crashes and bugs on the reviewer\'s device, broken links (storebound validate checks the URLs), screenshots that do not match the app, minimum functionality and spam judgement (4.2, 4.3), local law (5.2). See the review-rejections skill.');
|
||||
L.push('', 'Checked at review, not by scan: crashes and bugs on the reviewer\'s device, broken links (storebound validate checks the URLs), screenshots that do not match the app, minimum functionality and spam judgement (4.2, 4.3: scan --originality compares your own apps), local law (5.2). See the review-rejections skill.');
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* `scan --originality`: the near-duplicates of an originality report as scan findings (App Store 4.3 spam, Google
|
||||
* Play repetitive content), owner-accepted through `scan.ignore` like every rule (rule id "originality"). Pure.
|
||||
*/
|
||||
export function addOriginality(r: ScanReport, o: OriginalityReport, stores: { apple: boolean; play: boolean }, config: ShipConfig | null, rel: (p: string) => string): void {
|
||||
const ignore = config?.scan?.ignore ?? [];
|
||||
for (const p of o.pairs.filter(x => x.flagged)) {
|
||||
const evidence = [{ file: rel(p.other.dir) || '.', line: 1, text: `${p.other.name}: ${Math.round(p.overall * 100)}% overall (${p.reasons.slice(0, 2).join('; ')})` }];
|
||||
const fix = `${p.suggestions.slice(0, 2).join(' ') || 'Make the app different in mechanic, content and listing.'} Run storebound originality --against ${rel(p.other.dir) || '.'} for every axis; the portfolio-originality skill has the checklist.`;
|
||||
const base = { rule: 'originality', severity: 'high' as const, title: `Near-duplicate of your app ${p.other.name} (${Math.round(p.overall * 100)}% similar)`, evidence, fix, skill: 'portfolio-originality' };
|
||||
if (stores.apple) r.findings.push({ ...base, guideline: '4.3', store: 'apple', ref: APPLE_GUIDELINES });
|
||||
if (stores.play) r.findings.push({ ...base, guideline: 'Play: Repetitive content', store: 'play', ref: 'https://support.google.com/googleplay/android-developer/answer/9898783' });
|
||||
}
|
||||
for (const f of r.findings) if (f.rule === 'originality' && !f.accepted) {
|
||||
const hit = ignore.find(i => i.rule === f.rule && (!i.store || i.store === f.store));
|
||||
if (hit) f.accepted = hit.reason;
|
||||
}
|
||||
r.findings = sortScan(r.findings);
|
||||
r.counts = { blocker: 0, high: 0, medium: 0, low: 0, accepted: 0 };
|
||||
for (const f of r.findings) { if (f.accepted) r.counts.accepted++; else r.counts[f.severity]++; }
|
||||
r.originality = { compared: o.pairs.length, flagged: o.flagged, threshold: o.threshold, pairs: o.pairs.map(p => ({ app: p.other.name, folder: rel(p.other.dir) || '.', overall: Math.round(p.overall * 1000) / 1000, flagged: p.flagged })) };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
//
|
||||
// Sources, checked 2026-10-11:
|
||||
// - Apple App Review Guidelines: https://developer.apple.com/app-store/review/guidelines/
|
||||
// 2.1(a) app completeness (demo account, placeholder text), 2.3.7 metadata (names, keywords, no prices or other
|
||||
// 2.1(a) app completeness (demo account, placeholder text), 2.2 betas, demos and trial versions (TestFlight), 2.3.7 metadata (names, keywords, no prices or other
|
||||
// apps' names), 2.3.8 ("For Kids" is reserved for the Kids Category), 2.3.10 other mobile platforms, 2.5.1 public
|
||||
// APIs, 2.5.5 IPv6-only networks, 3.1.1 restore mechanism, 3.1.2(c) subscription information (+ Schedule 2 of the
|
||||
// Developer Program License Agreement: Terms of Use and privacy policy links), 4.2 minimum functionality
|
||||
|
|
@ -324,6 +324,19 @@ export function scanRules(inp: ScanInput): ScanFinding[] {
|
|||
const stuffed = listingHits(inp.listings.apple, /^([^,|]{1,24}[,|]){5,}/, { field: /^(name|subtitle)$/ });
|
||||
if (stuffed.length)
|
||||
add({ rule: 'metadata-keywords', guideline: '2.3.7', store: 'apple', severity: 'medium', title: 'Keyword list in the name or subtitle', evidence: stuffed.slice(0, 2), fix: 'Name and subtitle are a short phrase; keywords belong in the keywords field.', skill: 'aso-basics' });
|
||||
// 2.2: demos, betas and trial versions belong on TestFlight, not on the App Store (the name and the listing say so)
|
||||
const BETA = /\b(beta|demo|trial version|test (version|build|app)|testing build|early access|prototype|preview (build|version)|alpha (build|version))\b/i;
|
||||
const betaName: Hit[] = [];
|
||||
if (c?.app?.name && BETA.test(c.app.name)) betaName.push(...cfg(c.app.name, `app.name: ${c.app.name}`));
|
||||
for (const k of ['CFBundleDisplayName', 'CFBundleName']) {
|
||||
const v = plistVal(k);
|
||||
if (typeof v?.value === 'string' && BETA.test(v.value) && !/\$\(/.test(v.value)) betaName.push({ ...v.at, text: `${k}: ${v.value}` });
|
||||
}
|
||||
const betaText = listingHits(inp.listings.apple, BETA, { field: /^(name|subtitle|promotionalText|keywords|description)$/ })
|
||||
.filter(h => !/\bdemo account\b|\bdemo (video|mode)\b/i.test(h.text));
|
||||
if (betaName.length || betaText.length)
|
||||
add({ rule: 'beta-wording', guideline: '2.2', store: 'apple', severity: betaName.length ? 'high' : 'medium', title: '"Beta", "demo", "trial" or "test" wording in the app name or App Store text', evidence: [...betaName, ...betaText].slice(0, 4),
|
||||
fix: 'Apple 2.2: demos, betas and trial versions do not belong on the App Store (use TestFlight). Remove the word from the name, subtitle, keywords and description; a free tier or a trial of a subscription is fine when it is described as such ("free trial of Pro").', skill: 'review-rejections' });
|
||||
const kids = [...listingHits(inp.listings.apple, /\bfor (kids|children|toddlers)\b/i), ...listingHits(inp.listings.captions, /\bfor (kids|children|toddlers)\b/i, { fenced: false })];
|
||||
const kidsBand = c?.apple?.info?.ageRating?.kidsAgeBand;
|
||||
if (kids.length && !kidsBand)
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@
|
|||
import type { IntroOffer, Language, OfferCodeDef, PriceOverride, Subscription, SubscriptionGroup, SubscriptionOfferDef, SubscriptionPeriod } from './config';
|
||||
import { playCodes } from './config';
|
||||
import { ALPHA3, fromMoney, type Money, toMoney } from './money';
|
||||
import type { PriceRow } from './prices';
|
||||
import { alpha2, type PriceRow } from './prices';
|
||||
|
||||
// ---- mappings ----
|
||||
|
||||
|
|
@ -505,3 +505,16 @@ export function pickPoint(points: ApplePoint[], territory: string, price: number
|
|||
const near = [...inT].sort((a, b) => Math.abs(a.price - price) - Math.abs(b.price - price)).slice(0, 3).map(p => p.price);
|
||||
throw new Error(`${territory} has no subscription price point ${price}${near.length ? ` (nearest ${near.join(', ')})` : ''}`);
|
||||
}
|
||||
|
||||
// ---- the prices sheet (storebound prices export) ----
|
||||
|
||||
/** App Store prices of one subscription (in effect today + scheduled) as price sheet rows. Pure. */
|
||||
export function appleSubPriceRows(product: string, resp: JsonApi, today?: string): PriceRow[] {
|
||||
return appleSubPrices(resp, today).map(p => ({ product, store: 'apple' as const, region: alpha2(p.territory), territory: p.territory, currency: p.currency ?? '', price: p.price, ...(p.startDate ? { startDate: p.startDate } : {}) }));
|
||||
}
|
||||
|
||||
/** Google Play regional prices of one subscription's base plan as price sheet rows. Pure. */
|
||||
export function playSubPriceRows(sub: PlaySubscription, basePlan: string): PriceRow[] {
|
||||
const bp = sub.basePlans?.find(b => b.basePlanId === basePlan) ?? sub.basePlans?.[0];
|
||||
return (bp?.regionalConfigs ?? []).filter(r => r.price).map(r => ({ product: sub.productId, store: 'play' as const, region: r.regionCode, currency: r.price!.currencyCode, price: fromMoney(r.price!) }));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,10 @@ import t21 from '../../templates/testers.csv' with { type: 'text' };
|
|||
import tWebAppstore from '../../templates/web/appstore.svg' with { type: 'text' };
|
||||
import tWebGoogleplay from '../../templates/web/googleplay.svg' with { type: 'text' };
|
||||
import tWebLanding from '../../templates/web/landing.html' with { type: 'text' };
|
||||
import tWfAppRelease from '../../templates/profiles/app/workflows/release.yml' with { type: 'text' };
|
||||
import tWfAppBeta from '../../templates/profiles/app/workflows/beta.yml' with { type: 'text' };
|
||||
import tWfRelease from '../../templates/workflows/release.yml' with { type: 'text' };
|
||||
import tWfBeta from '../../templates/workflows/beta.yml' with { type: 'text' };
|
||||
|
||||
/** Template text by its path under templates/ (forward slashes). */
|
||||
export const TEMPLATE_TEXT: Record<string, string> = {
|
||||
|
|
@ -54,4 +58,8 @@ export const TEMPLATE_TEXT: Record<string, string> = {
|
|||
'web/appstore.svg': tWebAppstore as unknown as string,
|
||||
'web/googleplay.svg': tWebGoogleplay as unknown as string,
|
||||
'web/landing.html': tWebLanding as unknown as string,
|
||||
'profiles/app/workflows/release.yml': tWfAppRelease as unknown as string,
|
||||
'profiles/app/workflows/beta.yml': tWfAppBeta as unknown as string,
|
||||
'workflows/release.yml': tWfRelease as unknown as string,
|
||||
'workflows/beta.yml': tWfBeta as unknown as string,
|
||||
};
|
||||
|
|
|
|||
171
cli/lib/yaml.ts
Normal file
171
cli/lib/yaml.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
// A small YAML subset reader for repo-local files (store/workflows/*.yml), so storebound stays at zero runtime
|
||||
// dependencies. Pure. Supported: block maps (`key: value`), block lists (`- item`, `- key: value` with the rest of the
|
||||
// map indented below), nested by indentation (spaces only), plain / 'single' / "double" quoted scalars, inline lists
|
||||
// `[a, b]`, `#` comments, `|` and `>` block scalars, true / false / null / numbers. Not supported (an error names the
|
||||
// line): anchors, aliases, tags, multi-document files, inline maps `{...}`, tabs for indentation.
|
||||
|
||||
export type YamlValue = string | number | boolean | null | YamlValue[] | { [k: string]: YamlValue };
|
||||
|
||||
interface Line { n: number; indent: number; text: string }
|
||||
|
||||
function stripComment(s: string): string {
|
||||
let q: string | null = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i]!;
|
||||
if (q) { if (c === q && !(q === '"' && s[i - 1] === '\\')) q = null; continue; }
|
||||
if (c === '"' || c === '\'') { if (i === 0 || /[\s:[,-]/.test(s[i - 1]!)) q = c; continue; }
|
||||
if (c === '#' && (i === 0 || /\s/.test(s[i - 1]!))) return s.slice(0, i).trimEnd();
|
||||
}
|
||||
return s.trimEnd();
|
||||
}
|
||||
|
||||
function scalar(raw: string, n: number): YamlValue {
|
||||
const s = raw.trim();
|
||||
if (s === '' || s === '~' || s === 'null') return s === '' ? '' : null;
|
||||
if (s.startsWith('"')) {
|
||||
if (!s.endsWith('"') || s.length < 2) throw new Error(`line ${n}: unterminated "string"`);
|
||||
try { return JSON.parse(s) as string; } catch { throw new Error(`line ${n}: bad "string"`); }
|
||||
}
|
||||
if (s.startsWith('\'')) {
|
||||
if (!s.endsWith('\'') || s.length < 2) throw new Error(`line ${n}: unterminated 'string'`);
|
||||
return s.slice(1, -1).replace(/''/g, '\'');
|
||||
}
|
||||
if (s.startsWith('[')) {
|
||||
if (!s.endsWith(']')) throw new Error(`line ${n}: unterminated [list]`);
|
||||
const inner = s.slice(1, -1).trim();
|
||||
if (!inner) return [];
|
||||
const parts: string[] = [];
|
||||
let q: string | null = null, cur = '';
|
||||
for (const c of inner) {
|
||||
if (q) { cur += c; if (c === q) q = null; continue; }
|
||||
if (c === '"' || c === '\'') { q = c; cur += c; continue; }
|
||||
if (c === ',') { parts.push(cur); cur = ''; continue; }
|
||||
cur += c;
|
||||
}
|
||||
parts.push(cur);
|
||||
return parts.map(p => scalar(p, n));
|
||||
}
|
||||
if (s.startsWith('{')) throw new Error(`line ${n}: inline maps {...} are not supported; use one key per line`);
|
||||
if (/^[&*!]/.test(s)) throw new Error(`line ${n}: anchors, aliases and tags are not supported`);
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (/^-?\d+(\.\d+)?$/.test(s) && !/^0\d/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Index of the `:` that separates a map key from its value (outside quotes), or -1. */
|
||||
function keyColon(s: string): number {
|
||||
let q: string | null = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const c = s[i]!;
|
||||
if (q) { if (c === q) q = null; continue; }
|
||||
if ((c === '"' || c === '\'') && i === 0) { q = c; continue; }
|
||||
if (c === ':' && (i === s.length - 1 || s[i + 1] === ' ')) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function parseYaml(text: string): YamlValue {
|
||||
const lines: Line[] = [];
|
||||
const raw = text.replace(/\r\n?/g, '\n').split('\n');
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const l = raw[i]!;
|
||||
if (/^\t/.test(l) || /^ *\t/.test(l)) throw new Error(`line ${i + 1}: tabs are not allowed for indentation`);
|
||||
if (/^(---|\.\.\.)\s*$/.test(l)) { if (lines.length) throw new Error(`line ${i + 1}: one document per file`); continue; }
|
||||
lines.push({ n: i + 1, indent: l.length - l.trimStart().length, text: l.trim() });
|
||||
}
|
||||
let pos = 0;
|
||||
const content = (l: Line) => l.text !== '' && !l.text.startsWith('#');
|
||||
const skip = () => { while (pos < lines.length && !content(lines[pos]!)) pos++; };
|
||||
|
||||
/** Block scalar (| or >) below a key at `parentIndent`. */
|
||||
function block(style: string, parentIndent: number): string {
|
||||
const out: string[] = [];
|
||||
let ind = -1;
|
||||
while (pos < lines.length) {
|
||||
const l = lines[pos]!;
|
||||
const rawLine = raw[l.n - 1]!;
|
||||
if (l.text === '') { out.push(''); pos++; continue; }
|
||||
if (l.indent <= parentIndent) break;
|
||||
if (ind < 0) ind = l.indent;
|
||||
out.push(rawLine.slice(Math.min(ind, l.indent)));
|
||||
pos++;
|
||||
}
|
||||
while (out.length && out[out.length - 1] === '') out.pop();
|
||||
const keep = style.endsWith('-') ? '' : '\n';
|
||||
return (style.startsWith('>') ? out.join('\n').replace(/([^\n])\n(?=[^\n])/g, '$1 ') : out.join('\n')) + (out.length ? keep : '');
|
||||
}
|
||||
|
||||
function value(indent: number): YamlValue {
|
||||
skip();
|
||||
if (pos >= lines.length) return null;
|
||||
const first = lines[pos]!;
|
||||
if (first.indent < indent) return null;
|
||||
return first.text.startsWith('- ') || first.text === '-' ? list(first.indent) : map(first.indent);
|
||||
}
|
||||
|
||||
function entry(rest: string, n: number, ownIndent: number): [string, YamlValue] {
|
||||
const c = keyColon(rest);
|
||||
if (c < 0) throw new Error(`line ${n}: expected "key: value"`);
|
||||
const key = String(scalar(rest.slice(0, c), n));
|
||||
const v = stripComment(rest.slice(c + 1)).trim();
|
||||
if (v === '') {
|
||||
skip();
|
||||
const next = lines[pos];
|
||||
// a list may sit at the key's own indentation ("steps:\n- id: a")
|
||||
if (next && next.indent === ownIndent && (next.text.startsWith('- ') || next.text === '-')) return [key, list(ownIndent)];
|
||||
return [key, value(ownIndent + 1) ?? null];
|
||||
}
|
||||
if (/^[|>][+-]?$/.test(v)) return [key, block(v, ownIndent)];
|
||||
return [key, scalar(v, n)];
|
||||
}
|
||||
|
||||
function map(indent: number): { [k: string]: YamlValue } {
|
||||
const out: { [k: string]: YamlValue } = {};
|
||||
for (;;) {
|
||||
skip();
|
||||
if (pos >= lines.length) break;
|
||||
const l = lines[pos]!;
|
||||
if (l.indent < indent) break;
|
||||
if (l.indent > indent) throw new Error(`line ${l.n}: unexpected indentation`);
|
||||
if (l.text.startsWith('- ')) throw new Error(`line ${l.n}: a list item where a "key: value" was expected`);
|
||||
pos++;
|
||||
const [k, v] = entry(stripComment(l.text), l.n, indent);
|
||||
if (k in out) throw new Error(`line ${l.n}: "${k}" twice`);
|
||||
out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function list(indent: number): YamlValue[] {
|
||||
const out: YamlValue[] = [];
|
||||
for (;;) {
|
||||
skip();
|
||||
if (pos >= lines.length) break;
|
||||
const l = lines[pos]!;
|
||||
if (l.indent < indent) break;
|
||||
if (l.indent > indent) throw new Error(`line ${l.n}: expected a list item "- ..."`);
|
||||
if (!(l.text.startsWith('- ') || l.text === '-')) break;
|
||||
pos++;
|
||||
const rest = stripComment(l.text.slice(1)).trim();
|
||||
if (rest === '') { out.push(value(indent + 1)); continue; }
|
||||
const itemIndent = indent + (l.text.length - l.text.slice(1).trimStart().length);
|
||||
if (keyColon(rest) >= 0 && !/^["'[]/.test(rest)) {
|
||||
// "- key: value" starts a map whose other keys are indented to the item's text column
|
||||
const [k, v] = entry(rest, l.n, itemIndent);
|
||||
const m: { [k: string]: YamlValue } = { [k]: v };
|
||||
skip();
|
||||
if (pos < lines.length && lines[pos]!.indent === itemIndent && !lines[pos]!.text.startsWith('- ')) {
|
||||
for (const [k2, v2] of Object.entries(map(itemIndent))) { if (k2 in m) throw new Error(`line ${l.n}: "${k2}" twice`); m[k2] = v2; }
|
||||
}
|
||||
out.push(m);
|
||||
} else out.push(scalar(rest, l.n));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const v = value(0);
|
||||
skip();
|
||||
if (pos < lines.length) throw new Error(`line ${lines[pos]!.n}: unexpected content`);
|
||||
return v;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue