mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-03 09:56:57 +02:00
* refactor(resolvers): split review.ts into MECE resolver modules (pure move) Move every function from scripts/resolvers/review.ts, unchanged, into: - review-dashboard.ts: review dashboard, plan-file review report - plan-gates.ts: approval check, exit-plan-mode gate, plan-file discovery, plan-completion audit/gate (ship + review), plan verification exec - spec-review.ts: both spec review loops, benefits-from, anti-shortcut clause - outside-voice-steps.ts: Codex second opinion, adversarial step, Codex plan review, Codex doc review, disabled-outside record - review-scope.ts: scope drift, cross-review dedup, shared-code reuse review.ts is deleted; index.ts imports the new modules. gen-skill-docs output is byte-identical for every host (--host all). Test imports and source-path references are re-pointed; the two source-text report/gate tests in gen-skill-docs.test.ts become behavioral renders across every consuming skill and host. All 46 touchfile entries that named review.ts now name all five modules, guarded by a recorded selection golden. * test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. * refactor(shard-engine): move scripts/test-strict-output.ts to scripts/lib/shard-engine.ts The shared shard engine grows from the existing strict-output module (runShardChild, killProcessGroup, signal forwarding, strict classifier). scripts/test-strict-output.ts stays as a re-export so existing importers, mock.module paths and the strict-output/run-shard-child tests are unchanged. The engine inherits the global touchfile entry; the free runner's CLI-routing fixture copies the new module. * refactor(resolvers): decompose the three >150-line review resolvers (output-neutral) Split generateAdversarialStep, generateCodexPlanReview and generatePlanCompletionAuditInner into per-section helpers whose template literals are copied verbatim, so every function in the new modules is at or under 150 lines. gen-skill-docs output is byte-identical for every host (--host all, compared against96764e80with a fixed --link-root). * refactor(resolvers): one outside-voice failure policy (deliberate prose unification) outsideVoiceFailurePolicy(ctx, opts) in outside-voice.ts now renders the auth / timeout / empty-response bullets for all four call sites that hand-typed them (Codex second opinion, adversarial step, Codex plan review, design outside voices). Options are explicit per site (timeoutMinutes, onTimeout, stderrOnEmpty, fallback, escape) with no defaults. Deliberate generated-prose changes (every host): - office-hours: 'Fall back to <native> subagent.' becomes 'Fall back to the <native> subagent below.' - plan-devex-review: the plain 'Auth failure (stderr contains ...)' bullets become the canonical bold bullets; auth also triggers on 'API key'; 'auth failed' becomes 'authentication failed'. - review/ship adversarial: 'exceeded 9 minutes and was terminated' becomes 'timed out after 9 minutes and was terminated'; the timeout is still MISSING COVERAGE. - design outside voices: unchanged. Adds ratchet (d) (test/outside-voice-failure-policy.test.ts) with a reasoned allowlist for /codex's own CLI errors, the MISSING COVERAGE retention test, refreshed codex/factory ship goldens, and outside-voice.ts in every touchfile entry of review.ts and design.ts (selection golden extended). * test(pty): fake PTY session driver with an injectable clock through the runner launch seam The three plan-skill runners take an optional PtyDriver (launch, now, monotonic, sleep); omitted, they use the real launcher and clocks exactly as before. test/helpers/pty/fake-session.ts feeds scripted frames through that seam, and claude-pty-runner.runners.unit.test.ts runs observation, counting and floor for success, deadline timeout, permission prompt and plan-ready outcomes with no CLI or real timers. These cases must stay green unchanged through the W4 split and the runPtySession extraction. Touchfiles: every entry that lists claude-pty-runner.ts or pty-screen.ts now also lists test/helpers/pty/**. * refactor(shard-engine): run both lanes on the shared engine; lane policy injected Engine (scripts/lib/shard-engine.ts) gains the W2 primitives: per-shard tmp/Chromium sandbox + async cleanup backstop, log-path allocation and full-stream log capture, one duration-seed reader/writer with a lane predicate, LanePolicy (seed predicate + zero-execution verdict), strictShardStatus, and the shared CLI flag loop. runShardChild takes an optional companion (signal/settle) and waits a bounded 250ms to reap a wall-killed child. Free lane stops spawning shards itself: runFreeShard uses runShardChild with trackShardBrowser as the companion (win32 path unchanged: no process group, no negative-pid kill). Its sync state-dir removal stays lane policy. Paid lane uses the sandbox, log, seed, verdict and flag primitives; the hollow-shard guard applies PAID_LANE_POLICY. Lane outcomes are unchanged (free keeps >= 0 seeds and file-count zero-exec rule; paid keeps > 0 seeds, warning under selection and passed-empty under EVALS_ALL). paid-free-boundary's closure assertion now names the engine module, where the strict classifier lives. * test(shard-engine): engine unit tests, fixture-corpus equivalence, per-lane CLI parity - test/shard-engine.test.ts: failing/unhandled/module-load output fails both lanes, per-lane zero-execution and seed rules, whole-group kill on a wall timeout (both lanes), mocked-win32 path with no negative-pid kill, companion settle order, log capture, sandbox isolation, flag loop. - test/shard-engine-equivalence.test.ts + test/fixtures/shard-equivalence: seven outcome fixtures plus one real shard, run through both lanes and compared with classifications recorded from the base runners (96764e80). - test/shard-cli-parity.test.ts + test/fixtures/shard-cli-parity: flag set, defaults, validation errors and the Unknown argument error per lane match the base runners. * refactor(shard-engine): decompose runFreeShard and runPaidShard to <= 150 lines Output-neutral extraction under the fixture-corpus equivalence and runner tests: captureFreeStream, explainFreeVerdict and logFreeRecovery (free); paidShardCommand, settleShardSpool, settleBootstrapRetention and printLogTail (paid). The bootstrap scope-creation block that bootstrap-retention.test.ts evaluates stays verbatim. * refactor(pty): split claude-pty-runner.ts into test/helpers/pty/* behind a barrel Pure move: every line of the former 5,047-line runner lands verbatim in one module (four private helpers gain `export` for cross-module use): binary, screen (absorbs test/helpers/pty-screen.ts, which now re-exports it), launch, session (PtyDriver), judge, classify, auq, plan-native, boundaries, runners/{observation,counting,floor}. claude-pty-runner.ts re-exports the original public surface by name; pty/ modules import siblings directly. Tests that read the runner's source text: - rewritten as behavioral: the unit test's model-pin tripwire (fake CLI argv: fallback chain, --model before extraArgs, hermetic --strict-mcp-config), pty-skill-seeding-wiring (runners through the fake driver; launcher through a fake CLI reporting CLAUDE_CONFIG_DIR). The "three wrappers forward model" grep is replaced by the runners' fake-driver launch assertions. - pty-screen-session / pty-screen-supervision: stop copying runner source; they mock.module the real pty/screen.ts (and the fixture cleanup) instead. - re-pointed to the owning module (they execute a sliced runner body with injected boundaries; no seam exists for those boundaries yet): eng-seeded-completion-ai, plan-floor-permission, plan-create-prepublication, plan-count-completion; hermetic-wiring's source guard now reads pty/launch.ts and scans every pty/ module for raw process.env spreads. - plan-count-timeout and pty-output-wake mock the viewport at pty/screen.ts. * test(ratchet-c): enforcing module/function size ratchet and moved-code touchfile coverage Ratchet (c) ships enforcing: test/helpers/module-size.ts counts file and top-level function lengths by brace matching over masked source (strings, comments, regex literals and template text masked; ${} expressions kept), covering function declarations, arrow functions assigned to consts and route-table handler properties, with no parser dependency. Its self-test uses template literals and code-fence braces copied from scripts/resolvers/review.ts and design.ts. test/fixtures/module-size-ratchet.json binds scripts/lib/shard-engine.ts (<= 800 lines, <= 150 per function) and records the residual runner sizes (free 2352, paid 1921) as non-growth caps; allowlist entries are keyed on file plus matched text and need a reason. Failure output lists file:line, the rule, Fix: and the allowlist path. touchfiles.test.ts gains the moved-code superset check over test/fixtures/touchfile-move-goldens/ (W2 golden recorded at96764e80: test-strict-output.ts and test-paid-shards.ts global, test-free-shards.ts none). * refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. * test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. * test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. * test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at96764e80(17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. * test(shard-engine): give non-timeout corpus fixtures CI headroom; keep the POSIX golden off the Windows lane Only the wall-timeout fixture keeps a 3s wall; the rest get 60s so a loaded host cannot turn a pass into a timeout. Base and branch runners still agree on every classification under the new walls. The Windows exclusion entry moves the free runner's ratchet (c) residual cap to 2356 lines. * refactor(pty): one runPtySession loop drives observation, counting and floor test/helpers/pty/session.ts owns launch -> start -> (poll -> tick)* -> timeout and the failure contract the three runners each hand-rolled: the run's own error wins over capture and close errors, close always runs, owned fixture cleanup runs last (also when launch fails). Each runner now supplies a PtySessionPlan: its boot/command step, poll cadence (2s observation/floor sleep; counting's output wake + 250ms coalesce), tick policy (permission handling, native identity, terminal rules stay per runner because they differ) and capture hooks. The runner bodies are decomposed into top-level steps so no function exceeds 150 lines; behavior is unchanged and the fake-driver cases from the first W4 commit pass unmodified. The counting capture step and the native completion-summary predicate are now named functions (countingCapture, isNativeCompletionSummary), so plan-create-prepublication and plan-count-completion call them directly instead of executing sliced source. The two harnesses that still execute a sliced runner body with injected boundaries (eng-seeded-completion-ai, plan-floor-permission) pass the PtyDriver seam instead of overriding Date/Bun.sleep. * test(ratchet-c): register route modules, review resolver modules and server.ts residual cap * refactor(pty): decompose launchClaudePty and engNumberedFindingAUQ under 150 lines launchClaudePty (349 lines) becomes launch preparation (args, hermetic child env, owned state roots), recorder creation, spawn, the trust-dialog watcher, close, and the session handle over one PtyProcess state object. The failure order is unchanged: abort the viewport, dispose any recorders created so far, dispose the viewport, rethrow. The --model / --strict-mcp-config ordering and seedSkills wiring stay pinned by the behavioral fake-CLI tests. engNumberedFindingAUQ (345 lines) keeps its guards and dispatch; each self-contained issue family (declared cache, library retry hooks, cache owner, injected singleton, shared writers, injected export) moves verbatim into its own function. Every pty/ module is now <= 800 lines and every top-level function <= 150 lines. * test(pty): split claude-pty-runner.unit.test.ts along the pty/ module seams The 188 unit tests move verbatim into claude-pty-runner.{screen,classify, auq,launch,plan-native,boundaries}.unit.test.ts (test names unchanged; each file imports only what it uses from the barrel). The five files that no longer read a SKILL.md template join the test-of-test ratchet baseline with a reason. * test(touchfiles): moved PTY modules keep their paid-eval selection test/fixtures/touchfile-selection/w4-pty.json records, at96764e8, the paid evals selected by touching test/helpers/claude-pty-runner.ts (20) and test/helpers/pty-screen.ts (20). touchfiles.test.ts now asserts every .ts file under test/helpers/pty/ (and pty/screen.ts for both sources) selects a superset, reading every golden in that directory so later moves can add one; a planted-violation case pins the report and its Fix line. * fix(browse): unexchanged pair setup keys no longer authenticate bearer requests validateToken accepted a gsk_setup_ key as a bearer on /command, /batch and /file (found while building the W3 auth matrix). A setup key now only authenticates the /connect exchange. * W1: one state-root owner (lib/state-root.ts + bin/gstack-state-root.sh), gstack-paths --explain and fail-stop, parity tests * W1: guarded migration of every executable state-root site; uninstall deletes only ~/.gstack Bins, careful/freeze hooks, setup, upgrade migrations, browse/src, design, ios-qa daemon, lib and scripts resolve the state root through bin/gstack-state-root.sh (bash) or lib/state-root.ts (TS). Bins source the twin and stop with a reinstall message when it is missing; hooks source it and never spawn gstack-paths. browse/src/config.ts and lib/cso/state.ts delegate to resolveStateRoot. Analytics writers and readers move together so the usage log stays one file. gstack-uninstall deletes state only at ~/.gstack, refuses (exit 2) when it resolves to /, $HOME or an ancestor, the checkout or the git root, and leaves any other resolved root in place with the removal command. Fixtures that copy single bins now copy the twin. * W1: privacy keys and trust-policy deny tiers merge across state roots; gstack-config reporting; test hermeticity readConfigKey / gstack_read_config_key return the most restrictive telemetry, memorable_recall, codex_reviews and update_check across the resolved root and ~/.gstack; other keys read the resolved root only. gstack-config set reports an overriding root with the exact override command, list shows the winning root and a root-variable disagreement line. gstack-gbrain-repo-policy get merges deny/read-only tiers. gstack-egress reads through readConfigKey. test-setup.ts strips inherited GSTACK_STATE_ROOT/GSTACK_STATE_DIR and redirects the legacy root. * W1: shared hook logging helper (hosts/claude/hooks/hook-log.ts) One hook-errors.log writer: root from resolveStateRoot, 0600 on every append, opt-in rate limit used only by memorable-user-prompt. The five hooks route through it. * W1: docs/state-root.md and README troubleshooting pointer Precedence table, a real --explain example, the move-your-state recipe, merged privacy keys, the uninstall rule, the resolver-failure fix, and the plugin-mode note (evidence gate: no official plugin distribution). * W1b: template and resolver prose resolve state through guarded gstack-paths; ratchet (a) Every gstack-paths eval in templates and resolvers carries the fail-stop guard; executable ~/.gstack paths in bash blocks (context recovery preamble, eureka log, analytics, project artifacts, upgrade snooze, setup-gbrain lock, retro snapshots, ship consent marker) use $GSTACK_STATE_ROOT, and the writer prose that pairs with them points at the printed PROJECT_DIR / RETRO_FILE. ship drops export GSTACK_STATE_ROOT. SKILL.md regenerated (claude + codex), ship goldens re-pinned, parity and context-budget caps raised to the measured sizes with notes. test/state-root-ratchet.test.ts enforces the rule with a reasoned allowlist; W1 touchfile entries plus a superset golden. * refactor: apply W1 state-root edits in W2/W3/W5-owned files; one moved-code touchfile golden for all workstreams * test: fold the moved-code touchfile golden into touchfiles.test.ts; fix integration fixture closure and caps * v1.91.11.0: CHANGELOG, TODOS, docs and conventions for the refactor wave * test: re-measure plan-ceo/design-consultation caps and ship goldens after the guarded plan-discovery and spec-review blocks; add the state-root twin to the workflow-boundaries fixture * fix(windows): migrations resolve their directory with either path separator; state-root parity compares under the HOME Git Bash actually sees * fix(review,ship): state plan-check timing after smoke expiry and test_stub Skip semantics (review workflow judge clarity) * test(qa-eval): webhook fix eval asks for the fix loop's post-repair probes; eight-scenario coverage stays in the report-only case and the harness recheck * test(qa-eval): re-pin the webhook prompt contract to the fix-loop stage; R29 coverage omissions stay bound by the report-only case * fix(review,ship): plan checks publish a checkpoint before each probe; only the smoke expiry stop is skipped * fix(qa): carry #2999's checkpoint receipt link, report-template line and full-revision placeholder (identical hunks) * test(qa-callers): disable git auto maintenance in the caller fixture Git 2.47+ runs auto maintenance detached after commit; on the CI runner's git 2.55 it rewrote .git/objects fan-out directories while the write observer was running, which surfaced as unauthorized mutations. Same gc.auto=0 / maintenance.auto=false guard the shared-libs fixture already uses. * test(plan-mode-no-op): require prose evidence for the prose-fallback members so a spinner-frame judge verdict cannot end the run as asked * test(ship-docsync): carry #2999's seeded-attempt docsync harness (identical files) The doc-sync fault cases replayed attempt 1 before reaching their gate and ran out of their 285s budget. The fixture now seeds attempt 1 and the parent starts at the gate under test. Taken byte-identical from origin/capy/audit-fix-wave (fb526898,e6ac813d,6ce10ff7,d0c53577,77cce3be). Local: stale-before, recovery and late-result 6/6 PASS (97-164s); the whole file 12/12 PASS.
881 lines
32 KiB
TypeScript
881 lines
32 KiB
TypeScript
#!/usr/bin/env bun
|
|
//
|
|
// gen-accessors (TS port). Mirrors the SwiftPM tool's logic for the cases
|
|
// where a user doesn't want to wait 2-5min for swift-syntax to build the
|
|
// first time. Also exercised by tests so we can verify the cache + parse
|
|
// behavior without a Swift toolchain.
|
|
//
|
|
// The TS fast path uses a lightweight Swift lexical scanner — it understands:
|
|
// - @Observable class declarations
|
|
// - `// @Snapshotable` property markers (only marked fields are exported)
|
|
// - Legacy @Snapshotable attributes for existing integrations
|
|
// - Multi-line type signatures (collapses whitespace before matching)
|
|
// - JSON-native generic arrays and String-keyed dictionaries
|
|
//
|
|
// Invalid marked declarations (computed/immutable/inaccessible/untyped,
|
|
// nested, duplicate-keyed, or non-JSON) fail generation instead of producing
|
|
// Swift that only fails later in xcodebuild or at snapshot time.
|
|
//
|
|
// Composite cache key (codex-flagged): swift_version || tool_git_rev ||
|
|
// platform_triple || source_content_hash. Source-only hash misses generator
|
|
// logic changes.
|
|
|
|
import { readFileSync, readdirSync, statSync, writeFileSync, mkdirSync, existsSync, copyFileSync, rmSync } from 'fs';
|
|
import { join, resolve, dirname } from 'path';
|
|
import { createHash } from 'crypto';
|
|
import { execSync } from 'child_process';
|
|
import { resolveStateRoot } from '../../lib/state-root';
|
|
|
|
export interface AccessorField {
|
|
name: string;
|
|
typeText: string;
|
|
}
|
|
|
|
export interface AccessorSpec {
|
|
className: string;
|
|
fields: AccessorField[];
|
|
}
|
|
|
|
export class AccessorGenerationError extends Error {
|
|
readonly diagnostics: string[];
|
|
|
|
constructor(diagnostics: string[]) {
|
|
super(`gen-accessors: invalid @Snapshotable declaration(s):\n${diagnostics.map(d => ` - ${d}`).join('\n')}`);
|
|
this.name = 'AccessorGenerationError';
|
|
this.diagnostics = diagnostics;
|
|
}
|
|
}
|
|
|
|
export interface GenInputs {
|
|
inputDir: string;
|
|
outputDir?: string;
|
|
buildId?: string;
|
|
cacheRoot?: string;
|
|
swiftVersion?: string;
|
|
toolGitRev?: string;
|
|
platformTriple?: string;
|
|
}
|
|
|
|
export interface GenResult {
|
|
outputPath: string;
|
|
cacheKey: string;
|
|
accessorHash: string;
|
|
specs: AccessorSpec[];
|
|
cacheHit: boolean;
|
|
}
|
|
|
|
const FALLBACK_PLATFORM = process.platform === 'darwin' ? 'darwin-arm64' : `${process.platform}-${process.arch}`;
|
|
const GENERATOR_FORMAT_VERSION = 'accessor-generator-v5';
|
|
|
|
const JSON_SCALAR_TYPES = new Set([
|
|
'String',
|
|
'Bool',
|
|
'Int', 'Int8', 'Int16', 'Int32', 'Int64',
|
|
'UInt', 'UInt8', 'UInt16', 'UInt32', 'UInt64',
|
|
'Float', 'Double', 'CGFloat',
|
|
]);
|
|
|
|
export function collectSwiftFiles(
|
|
dir: string,
|
|
opts: { excludeGenerated?: boolean; outputDir?: string } = {},
|
|
): string[] {
|
|
const out: string[] = [];
|
|
const excludeGenerated = opts.excludeGenerated ?? true;
|
|
const root = resolve(dir);
|
|
const outputDir = opts.outputDir ? resolve(opts.outputDir) : undefined;
|
|
|
|
function walk(currentDir: string): void {
|
|
for (const name of readdirSync(currentDir)) {
|
|
const full = join(currentDir, name);
|
|
const s = statSync(full);
|
|
if (s.isDirectory()) {
|
|
// The generated subtree must never participate in its own cache key.
|
|
// Keep the well-known-name guard for direct collectSwiftFiles callers,
|
|
// and use the actual --output path when generate() supplies one.
|
|
const isOutputSubtree = outputDir !== undefined
|
|
&& outputDir !== root
|
|
&& resolve(full) === outputDir;
|
|
if (excludeGenerated && (name === 'DebugBridgeGenerated' || isOutputSubtree)) continue;
|
|
walk(full);
|
|
} else if (name.endsWith('.swift')) {
|
|
// Skip generated accessor files wherever they live. Otherwise moving
|
|
// an old copy outside the output directory poisons the next cache key.
|
|
if (excludeGenerated && name === 'StateAccessor.swift') continue;
|
|
out.push(full);
|
|
}
|
|
}
|
|
}
|
|
|
|
walk(root);
|
|
return out.sort();
|
|
}
|
|
|
|
export function parseSwift(source: string): AccessorSpec[] {
|
|
const specs: AccessorSpec[] = [];
|
|
const diagnostics: string[] = [];
|
|
const masked = maskSwiftSource(source);
|
|
// Find `@Observable\n(public )?(final )?class <Name>` followed by a brace
|
|
// block. We then scan inside that block for @Snapshotable fields.
|
|
const classPattern = /@Observable\s*(?:(?:public|internal|fileprivate|private)\s+)?(?:final\s+)?class\s+(\w+)[^{]*\{/g;
|
|
|
|
for (const match of masked.matchAll(classPattern)) {
|
|
const className = match[1]!;
|
|
const matchOffset = match.index!;
|
|
const openBraceOffset = matchOffset + match[0].lastIndexOf('{');
|
|
const startIdx = openBraceOffset + 1;
|
|
const endIdx = findMatchingBrace(masked, startIdx - 1);
|
|
if (endIdx === -1) continue;
|
|
const body = masked.slice(startIdx, endIdx);
|
|
|
|
const parsed = parseFields(body, source, startIdx, className);
|
|
if (braceDepthAt(masked, matchOffset) !== 0) {
|
|
if (parsed.fields.length > 0 || parsed.diagnostics.length > 0) {
|
|
const line = source.slice(0, matchOffset).split(/\r?\n/).length;
|
|
diagnostics.push(`${className} (line ${line}): nested @Observable types are not supported; move the type to file scope`);
|
|
}
|
|
continue;
|
|
}
|
|
diagnostics.push(...parsed.diagnostics);
|
|
const fields = parsed.fields;
|
|
if (fields.length > 0) {
|
|
specs.push({ className, fields });
|
|
}
|
|
}
|
|
|
|
if (diagnostics.length > 0) throw new AccessorGenerationError(diagnostics);
|
|
return specs;
|
|
}
|
|
|
|
function braceDepthAt(masked: string, offset: number): number {
|
|
let depth = 0;
|
|
for (let i = 0; i < offset; i++) {
|
|
if (masked[i] === '{') depth++;
|
|
else if (masked[i] === '}') depth = Math.max(0, depth - 1);
|
|
}
|
|
return depth;
|
|
}
|
|
|
|
function findMatchingBrace(s: string, openIdx: number): number {
|
|
// Strings and comments have already been blanked by maskSwiftSource, so
|
|
// braces here are syntax rather than prose or literal content.
|
|
let depth = 0;
|
|
for (let i = openIdx; i < s.length; i++) {
|
|
const c = s[i];
|
|
if (c === '{') depth++;
|
|
else if (c === '}') {
|
|
depth--;
|
|
if (depth === 0) return i;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
/**
|
|
* Blank comments and string literals while preserving byte offsets/newlines.
|
|
* A canonical standalone `// @Snapshotable` comment is rewritten to the
|
|
* equivalent attribute token. This is intentionally lexical rather than a
|
|
* whole-file regexp: markers inside nested block comments, normal/triple/raw
|
|
* strings, trailing comments, and prose comments must never opt a field in.
|
|
*/
|
|
function maskSwiftSource(source: string): string {
|
|
const out = source.split('');
|
|
|
|
const blank = (start: number, end: number): void => {
|
|
for (let j = start; j < end; j++) {
|
|
if (out[j] !== '\n' && out[j] !== '\r') out[j] = ' ';
|
|
}
|
|
};
|
|
|
|
let i = 0;
|
|
while (i < source.length) {
|
|
if (source[i] === '/' && source[i + 1] === '/') {
|
|
let end = i + 2;
|
|
while (end < source.length && source[end] !== '\n' && source[end] !== '\r') end++;
|
|
const lineStart = source.lastIndexOf('\n', i - 1) + 1;
|
|
const standalone = source.slice(lineStart, i).trim().length === 0;
|
|
const isMarker = standalone && source.slice(i + 2, end).trim() === '@Snapshotable';
|
|
blank(i, end);
|
|
if (isMarker) {
|
|
const marker = '@Snapshotable';
|
|
for (let j = 0; j < marker.length; j++) out[i + j] = marker[j]!;
|
|
}
|
|
i = end;
|
|
continue;
|
|
}
|
|
|
|
if (source[i] === '/' && source[i + 1] === '*') {
|
|
const start = i;
|
|
i += 2;
|
|
let depth = 1;
|
|
while (i < source.length && depth > 0) {
|
|
if (source[i] === '/' && source[i + 1] === '*') {
|
|
depth++;
|
|
i += 2;
|
|
} else if (source[i] === '*' && source[i + 1] === '/') {
|
|
depth--;
|
|
i += 2;
|
|
} else {
|
|
i++;
|
|
}
|
|
}
|
|
blank(start, i);
|
|
continue;
|
|
}
|
|
|
|
// Swift strings may be ordinary, multiline, or raw (`#"..."#` and
|
|
// `#"""..."""#`). Mask the entire literal, including interpolation;
|
|
// declarations cannot legally originate inside a literal.
|
|
let hashCount = 0;
|
|
while (source[i + hashCount] === '#') hashCount++;
|
|
const quoteIdx = i + hashCount;
|
|
if (source[quoteIdx] === '"') {
|
|
const start = i;
|
|
const triple = source.slice(quoteIdx, quoteIdx + 3) === '"""';
|
|
const quoteCount = triple ? 3 : 1;
|
|
i = quoteIdx + quoteCount;
|
|
while (i < source.length) {
|
|
if (hashCount === 0 && source[i] === '\\') {
|
|
i += 2;
|
|
continue;
|
|
}
|
|
const quoteRun = source.slice(i, i + quoteCount) === '"'.repeat(quoteCount);
|
|
const hashesMatch = source.slice(i + quoteCount, i + quoteCount + hashCount) === '#'.repeat(hashCount);
|
|
if (quoteRun && hashesMatch) {
|
|
i += quoteCount + hashCount;
|
|
break;
|
|
}
|
|
i++;
|
|
}
|
|
blank(start, i);
|
|
continue;
|
|
}
|
|
|
|
i++;
|
|
}
|
|
return out.join('');
|
|
}
|
|
|
|
const DECL_MODIFIERS = new Set([
|
|
'public', 'internal', 'package', 'open', 'private', 'fileprivate',
|
|
'final', 'static', 'class', 'lazy', 'weak', 'unowned', 'override',
|
|
'nonisolated', 'isolated', 'borrowing', 'consuming',
|
|
]);
|
|
|
|
function parseFields(
|
|
body: string,
|
|
fullSource: string,
|
|
bodyOffset: number,
|
|
className: string,
|
|
): { fields: AccessorField[]; diagnostics: string[] } {
|
|
const fields: AccessorField[] = [];
|
|
const diagnostics: string[] = [];
|
|
let braceDepth = 0;
|
|
|
|
const lineFor = (localOffset: number): number => {
|
|
const absolute = bodyOffset + localOffset;
|
|
let line = 1;
|
|
for (let j = 0; j < absolute; j++) if (fullSource[j] === '\n') line++;
|
|
return line;
|
|
};
|
|
const fail = (offset: number, message: string): void => {
|
|
diagnostics.push(`${className} (line ${lineFor(offset)}): ${message}`);
|
|
};
|
|
const skipWhitespace = (start: number): number => {
|
|
let at = start;
|
|
while (at < body.length && /\s/.test(body[at]!)) at++;
|
|
return at;
|
|
};
|
|
const identifierAt = (start: number): { text: string; end: number } | undefined => {
|
|
const m = /^[A-Za-z_]\w*/.exec(body.slice(start));
|
|
return m ? { text: m[0], end: start + m[0].length } : undefined;
|
|
};
|
|
const skipBalancedParens = (start: number): number => {
|
|
if (body[start] !== '(') return start;
|
|
let depth = 0;
|
|
for (let at = start; at < body.length; at++) {
|
|
if (body[at] === '(') depth++;
|
|
else if (body[at] === ')' && --depth === 0) return at + 1;
|
|
}
|
|
return body.length;
|
|
};
|
|
|
|
for (let i = 0; i < body.length; i++) {
|
|
if (body[i] === '{') {
|
|
braceDepth++;
|
|
continue;
|
|
}
|
|
if (body[i] === '}') {
|
|
braceDepth--;
|
|
continue;
|
|
}
|
|
if (braceDepth !== 0 || !body.startsWith('@Snapshotable', i)) continue;
|
|
const before = i === 0 ? '' : body[i - 1]!;
|
|
const after = body[i + '@Snapshotable'.length] ?? '';
|
|
if (/\w/.test(before) || /\w/.test(after)) continue;
|
|
|
|
const markerOffset = i;
|
|
let at = skipWhitespace(i + '@Snapshotable'.length);
|
|
const modifiers: string[] = [];
|
|
let bindingKind: 'var' | 'let' | undefined;
|
|
|
|
// Permit other Swift attributes between the marker and declaration. They
|
|
// remain the compiler's responsibility; this scanner only owns the
|
|
// snapshot contract. Parenthesized attribute arguments are skipped.
|
|
while (body[at] === '@') {
|
|
const attribute = identifierAt(at + 1);
|
|
if (!attribute) break;
|
|
at = skipWhitespace(attribute.end);
|
|
if (body[at] === '(') at = skipBalancedParens(at);
|
|
at = skipWhitespace(at);
|
|
}
|
|
|
|
while (at < body.length) {
|
|
const token = identifierAt(at);
|
|
if (!token) break;
|
|
if (token.text === 'var' || token.text === 'let') {
|
|
bindingKind = token.text;
|
|
at = token.end;
|
|
break;
|
|
}
|
|
if (!DECL_MODIFIERS.has(token.text)) break;
|
|
let modifier = token.text;
|
|
at = skipWhitespace(token.end);
|
|
if (body[at] === '(') {
|
|
const end = skipBalancedParens(at);
|
|
modifier += body.slice(at, end).replace(/\s+/g, '');
|
|
at = skipWhitespace(end);
|
|
}
|
|
modifiers.push(modifier);
|
|
}
|
|
|
|
if (!bindingKind) {
|
|
fail(markerOffset, '@Snapshotable must immediately precede a stored property declaration');
|
|
continue;
|
|
}
|
|
|
|
at = skipWhitespace(at);
|
|
const identifier = identifierAt(at);
|
|
const fieldName = identifier?.text ?? '<unknown>';
|
|
if (!identifier) {
|
|
fail(markerOffset, '@Snapshotable only supports a single identifier binding');
|
|
continue;
|
|
}
|
|
at = skipWhitespace(identifier.end);
|
|
|
|
if (bindingKind === 'let') {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' must be declared var, not let`);
|
|
continue;
|
|
}
|
|
if (modifiers.some(m => /^(?:private|fileprivate)(?:\(set\))?$/.test(m))) {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' cannot be private, fileprivate, private(set), or fileprivate(set)`);
|
|
continue;
|
|
}
|
|
if (modifiers.some(m => m === 'static' || m === 'class')) {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' must be an instance property`);
|
|
continue;
|
|
}
|
|
if (body[at] !== ':') {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' requires an explicit type annotation`);
|
|
continue;
|
|
}
|
|
|
|
at = skipWhitespace(at + 1);
|
|
const typeStart = at;
|
|
let parens = 0;
|
|
let brackets = 0;
|
|
let angles = 0;
|
|
let typeEnd = at;
|
|
let delimiter = '';
|
|
for (; at < body.length; at++) {
|
|
const c = body[at]!;
|
|
if (c === '(') parens++;
|
|
else if (c === ')') parens--;
|
|
else if (c === '[') brackets++;
|
|
else if (c === ']') brackets--;
|
|
else if (c === '<') angles++;
|
|
else if (c === '>') angles = Math.max(0, angles - 1);
|
|
const topLevel = parens === 0 && brackets === 0 && angles === 0;
|
|
if (topLevel && (c === '=' || c === '{' || c === ',' || c === ';')) {
|
|
delimiter = c;
|
|
break;
|
|
}
|
|
if (topLevel && (c === '\n' || c === '\r')) {
|
|
const soFar = body.slice(typeStart, at).trim();
|
|
if (soFar.length > 0 && !/(?:->|[&.,])\s*$/.test(soFar)) break;
|
|
}
|
|
typeEnd = at + 1;
|
|
}
|
|
const typeText = body.slice(typeStart, typeEnd).replace(/\s+/g, ' ').trim();
|
|
if (typeText.length === 0) {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' requires an explicit type annotation`);
|
|
continue;
|
|
}
|
|
if (delimiter === '{') {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' must be stored and writable`);
|
|
continue;
|
|
}
|
|
if (delimiter === ',') {
|
|
fail(markerOffset, '@Snapshotable declarations must contain exactly one binding');
|
|
continue;
|
|
}
|
|
if (delimiter === '=') {
|
|
// A declaration such as `var a: Int = 1, b: Int = 2` reaches `=`
|
|
// before its binding comma. Scan the initializer at syntax depth zero
|
|
// so commas in arrays/calls/closures remain valid.
|
|
let initializerAt = at + 1;
|
|
let expressionParens = 0;
|
|
let expressionBrackets = 0;
|
|
let expressionBraces = 0;
|
|
let hasSecondBinding = false;
|
|
for (; initializerAt < body.length; initializerAt++) {
|
|
const c = body[initializerAt]!;
|
|
if (c === '(') expressionParens++;
|
|
else if (c === ')') expressionParens--;
|
|
else if (c === '[') expressionBrackets++;
|
|
else if (c === ']') expressionBrackets--;
|
|
else if (c === '{') expressionBraces++;
|
|
else if (c === '}') {
|
|
if (expressionBraces === 0) break;
|
|
expressionBraces--;
|
|
}
|
|
const topLevel = expressionParens === 0 && expressionBrackets === 0 && expressionBraces === 0;
|
|
if (topLevel && c === ',') {
|
|
hasSecondBinding = true;
|
|
break;
|
|
}
|
|
if (topLevel && (c === '\n' || c === '\r' || c === ';')) break;
|
|
}
|
|
if (hasSecondBinding) {
|
|
fail(markerOffset, '@Snapshotable declarations must contain exactly one binding');
|
|
continue;
|
|
}
|
|
}
|
|
const wrappedOptional = optionalWrappedType(typeText);
|
|
if (wrappedOptional !== undefined && optionalWrappedType(wrappedOptional) !== undefined) {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' cannot use a nested Optional type`);
|
|
continue;
|
|
}
|
|
const typeIssue = snapshotTypeIssue(typeText);
|
|
if (typeIssue !== undefined) {
|
|
fail(markerOffset, `@Snapshotable field '${fieldName}' ${typeIssue}`);
|
|
continue;
|
|
}
|
|
|
|
fields.push({ name: fieldName, typeText });
|
|
}
|
|
return { fields, diagnostics };
|
|
}
|
|
|
|
export function computeCacheKey(inputs: {
|
|
swiftFiles: string[];
|
|
swiftVersion: string;
|
|
toolGitRev: string;
|
|
platformTriple: string;
|
|
buildId?: string;
|
|
}): string {
|
|
const h = createHash('sha256');
|
|
h.update(`${GENERATOR_FORMAT_VERSION}|swift=${inputs.swiftVersion}|tool=${inputs.toolGitRev}|platform=${inputs.platformTriple}|build=${inputs.buildId ?? 'unknown'}|`);
|
|
for (const f of inputs.swiftFiles) {
|
|
const content = readFileSync(f);
|
|
// Cache identity is content-based. Absolute checkout paths must not make
|
|
// equivalent source trees produce different generated output.
|
|
h.update(`${content.length}:`);
|
|
h.update(content);
|
|
h.update('|');
|
|
}
|
|
return h.digest('hex');
|
|
}
|
|
|
|
/** Stable snapshot-schema fingerprint, deliberately independent of cache ABI,
|
|
* source paths, app build provenance, and unmarked source. Field/class order is
|
|
* source order because restore payload compatibility is an ordered contract. */
|
|
export function computeAccessorHash(specs: AccessorSpec[]): string {
|
|
let signature = 'snapshot-schema-v1\n';
|
|
for (const spec of specs) {
|
|
signature += `C${Buffer.byteLength(spec.className)}:${spec.className}\n`;
|
|
for (const field of spec.fields) {
|
|
signature += `F${Buffer.byteLength(field.name)}:${field.name}`;
|
|
signature += `T${Buffer.byteLength(field.typeText)}:${field.typeText}\n`;
|
|
}
|
|
signature += 'E\n';
|
|
}
|
|
return createHash('sha256').update(signature).digest('hex');
|
|
}
|
|
|
|
/** Return the wrapped type for one top-level Optional spelling. */
|
|
export function optionalWrappedType(typeText: string): string | undefined {
|
|
const type = typeText.trim();
|
|
if (type.endsWith('?')) {
|
|
const wrapped = type.slice(0, -1).trim();
|
|
return wrapped.length > 0 ? wrapped : undefined;
|
|
}
|
|
|
|
const optional = /^(?:Swift\.)?Optional\s*</.exec(type);
|
|
if (!optional) return undefined;
|
|
const open = type.indexOf('<', optional.index);
|
|
let depth = 0;
|
|
for (let i = open; i < type.length; i++) {
|
|
if (type[i] === '<') depth++;
|
|
else if (type[i] === '>') {
|
|
depth--;
|
|
if (depth === 0) {
|
|
if (type.slice(i + 1).trim().length > 0) return undefined;
|
|
const wrapped = type.slice(open + 1, i).trim();
|
|
return wrapped.length > 0 ? wrapped : undefined;
|
|
}
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function splitTopLevel(type: string, delimiter: string): string[] {
|
|
const parts: string[] = [];
|
|
let start = 0;
|
|
let angle = 0;
|
|
let square = 0;
|
|
let paren = 0;
|
|
for (let i = 0; i < type.length; i++) {
|
|
const char = type[i]!;
|
|
if (char === '<') angle++;
|
|
else if (char === '>') angle--;
|
|
else if (char === '[') square++;
|
|
else if (char === ']') square--;
|
|
else if (char === '(') paren++;
|
|
else if (char === ')') paren--;
|
|
else if (char === delimiter && angle === 0 && square === 0 && paren === 0) {
|
|
parts.push(type.slice(start, i));
|
|
start = i + 1;
|
|
}
|
|
}
|
|
parts.push(type.slice(start));
|
|
return parts;
|
|
}
|
|
|
|
function genericArgument(type: string, name: string): string | undefined {
|
|
const prefix = `${name}<`;
|
|
if (!type.startsWith(prefix) || !type.endsWith('>')) return undefined;
|
|
let depth = 0;
|
|
for (let i = name.length; i < type.length; i++) {
|
|
if (type[i] === '<') depth++;
|
|
else if (type[i] === '>') {
|
|
depth--;
|
|
if (depth === 0 && i !== type.length - 1) return undefined;
|
|
if (depth < 0) return undefined;
|
|
}
|
|
}
|
|
return depth === 0 ? type.slice(prefix.length, -1) : undefined;
|
|
}
|
|
|
|
/** Return a user-facing suffix when a Swift type cannot round-trip through
|
|
* Foundation JSON without custom encoding. The accepted grammar is deliberately
|
|
* narrow: JSON scalar values, arrays, string-keyed dictionaries, and Optional
|
|
* compositions of those types. */
|
|
export function snapshotTypeIssue(typeText: string): string | undefined {
|
|
const type = typeText.replace(/\s+/g, '');
|
|
if (type.length === 0) return 'requires a JSON-compatible type';
|
|
if (type.endsWith('!')) {
|
|
return 'cannot use an implicitly unwrapped Optional; use T? instead';
|
|
}
|
|
|
|
if (type.endsWith('?')) {
|
|
const wrapped = type.slice(0, -1);
|
|
if (wrapped.endsWith('?')
|
|
|| genericArgument(wrapped, 'Optional') !== undefined
|
|
|| genericArgument(wrapped, 'Swift.Optional') !== undefined) {
|
|
return 'cannot use a nested Optional type';
|
|
}
|
|
return snapshotTypeIssue(wrapped);
|
|
}
|
|
const optional = genericArgument(type, 'Optional') ?? genericArgument(type, 'Swift.Optional');
|
|
if (optional !== undefined) {
|
|
if (optional.endsWith('?')
|
|
|| genericArgument(optional, 'Optional') !== undefined
|
|
|| genericArgument(optional, 'Swift.Optional') !== undefined) {
|
|
return 'cannot use a nested Optional type';
|
|
}
|
|
return snapshotTypeIssue(optional);
|
|
}
|
|
|
|
const scalar = type === 'CoreGraphics.CGFloat'
|
|
? 'CGFloat'
|
|
: (type.startsWith('Swift.') ? type.slice('Swift.'.length) : type);
|
|
if (JSON_SCALAR_TYPES.has(scalar)) return undefined;
|
|
|
|
if (type.startsWith('[') && type.endsWith(']')) {
|
|
const inner = type.slice(1, -1);
|
|
const dictionaryParts = splitTopLevel(inner, ':');
|
|
if (dictionaryParts.length === 1) return snapshotTypeIssue(inner);
|
|
if (dictionaryParts.length === 2) {
|
|
const key = dictionaryParts[0]!.replace(/^Swift\./, '');
|
|
if (key !== 'String') return 'must use String keys for snapshot dictionaries';
|
|
return snapshotTypeIssue(dictionaryParts[1]!);
|
|
}
|
|
return 'requires a JSON-compatible array or dictionary type';
|
|
}
|
|
|
|
const array = genericArgument(type, 'Array') ?? genericArgument(type, 'Swift.Array');
|
|
if (array !== undefined) return snapshotTypeIssue(array);
|
|
const dictionary = genericArgument(type, 'Dictionary') ?? genericArgument(type, 'Swift.Dictionary');
|
|
if (dictionary !== undefined) {
|
|
const parts = splitTopLevel(dictionary, ',');
|
|
if (parts.length !== 2) return 'requires a JSON-compatible dictionary type';
|
|
const key = parts[0]!.replace(/^Swift\./, '');
|
|
if (key !== 'String') return 'must use String keys for snapshot dictionaries';
|
|
return snapshotTypeIssue(parts[1]!);
|
|
}
|
|
|
|
return `uses unsupported snapshot type '${typeText}'; use JSON scalar, array, or String-keyed dictionary types`;
|
|
}
|
|
|
|
export function validateAccessorSpecs(specs: AccessorSpec[]): void {
|
|
const owners = new Map<string, string>();
|
|
const diagnostics: string[] = [];
|
|
for (const spec of specs) {
|
|
for (const field of spec.fields) {
|
|
const previous = owners.get(field.name);
|
|
if (previous !== undefined) {
|
|
diagnostics.push(`snapshot key '${field.name}' is declared by both ${previous} and ${spec.className}; keys must be unique across @Observable types`);
|
|
} else {
|
|
owners.set(field.name, spec.className);
|
|
}
|
|
}
|
|
}
|
|
if (diagnostics.length > 0) throw new AccessorGenerationError(diagnostics);
|
|
}
|
|
|
|
function swiftStringLiteral(value: string): string {
|
|
return JSON.stringify(value);
|
|
}
|
|
|
|
export function render(specs: AccessorSpec[], buildId: string, accessorHash: string): string {
|
|
validateAccessorSpecs(specs);
|
|
let out = '// AUTO-GENERATED — DO NOT EDIT. Regenerate with /ios-sync.\n';
|
|
out += '#if DEBUG\nimport Foundation\nimport DebugBridgeCore\n\n';
|
|
for (const spec of specs) {
|
|
// Accessors compile in the app target beside its usually-internal state
|
|
// types. Making this API public would make valid internal models fail
|
|
// Swift type checking (a public signature cannot expose an internal type).
|
|
out += `@MainActor\nenum ${spec.className}Accessor {\n`;
|
|
out += ` private static func decodeSnapshotValue<T: Decodable>(_ value: Any, as type: T.Type) -> T? {\n`;
|
|
out += ` guard JSONSerialization.isValidJSONObject(["value": value]),\n`;
|
|
out += ` let data = try? JSONSerialization.data(withJSONObject: ["value": value]),\n`;
|
|
out += ` let decoded = try? JSONDecoder().decode([String: T].self, from: data) else { return nil }\n`;
|
|
out += ` return decoded["value"]\n`;
|
|
out += ` }\n\n`;
|
|
out += ` static func register(_ state: ${spec.className}) {\n`;
|
|
out += ` StateServer.shared.register(\n`;
|
|
out += ` buildId: {\n`;
|
|
out += ` let shortVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String\n`;
|
|
out += ` let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String\n`;
|
|
out += ` if let shortVersion, let bundleVersion { return "\\(shortVersion) (\\(bundleVersion))" }\n`;
|
|
out += ` return shortVersion ?? bundleVersion ?? ${swiftStringLiteral(buildId)}\n`;
|
|
out += ` }(),\n`;
|
|
out += ` accessorHash: ${swiftStringLiteral(accessorHash)},\n`;
|
|
out += ` atomicRestore: { keys, apply in\n`;
|
|
out += ` // Validate every key and value before assignment.\n`;
|
|
out += ` // Successful assignments are sequential on MainActor.\n`;
|
|
spec.fields.forEach((field, index) => {
|
|
out += ` guard let raw${index} = keys["${field.name}"] else {\n`;
|
|
out += ` return .missingKey("${field.name}")\n`;
|
|
out += ` }\n`;
|
|
const wrapped = optionalWrappedType(field.typeText);
|
|
if (wrapped !== undefined) {
|
|
out += ` let restored${index}: ${field.typeText}\n`;
|
|
out += ` if raw${index} is NSNull {\n`;
|
|
out += ` restored${index} = nil\n`;
|
|
out += ` } else if let typed = Self.decodeSnapshotValue(raw${index}, as: ${wrapped}.self) {\n`;
|
|
out += ` restored${index} = typed\n`;
|
|
out += ` } else {\n`;
|
|
out += ` return .typeMismatch("${field.name}")\n`;
|
|
out += ` }\n`;
|
|
} else {
|
|
out += ` guard let restored${index} = Self.decodeSnapshotValue(raw${index}, as: ${field.typeText}.self) else {\n`;
|
|
out += ` return .typeMismatch("${field.name}")\n`;
|
|
out += ` }\n`;
|
|
}
|
|
});
|
|
out += ` if apply {\n`;
|
|
spec.fields.forEach((field, index) => {
|
|
out += ` state.${field.name} = restored${index}\n`;
|
|
});
|
|
out += ` }\n`;
|
|
out += ` return .ok\n`;
|
|
out += ` }\n`;
|
|
out += ` )\n`;
|
|
for (const field of spec.fields) {
|
|
const wrapped = optionalWrappedType(field.typeText);
|
|
out += ` StateServer.shared.registerAccessor(\n`;
|
|
out += ` key: "${field.name}",\n`;
|
|
out += ` type: "${field.typeText}",\n`;
|
|
if (wrapped !== undefined) {
|
|
out += ` read: {\n`;
|
|
out += ` guard let value = state.${field.name} else { return NSNull() }\n`;
|
|
out += ` return value as Any\n`;
|
|
out += ` },\n`;
|
|
} else {
|
|
out += ` read: { state.${field.name} as Any? },\n`;
|
|
}
|
|
out += ` write: { value in\n`;
|
|
if (wrapped !== undefined) {
|
|
out += ` if value is NSNull {\n`;
|
|
out += ` state.${field.name} = nil\n`;
|
|
out += ` return true\n`;
|
|
out += ` }\n`;
|
|
out += ` guard let typed = Self.decodeSnapshotValue(value, as: ${wrapped}.self) else { return false }\n`;
|
|
} else {
|
|
out += ` guard let typed = Self.decodeSnapshotValue(value, as: ${field.typeText}.self) else { return false }\n`;
|
|
}
|
|
out += ` state.${field.name} = typed\n`;
|
|
out += ` return true\n`;
|
|
out += ` }\n`;
|
|
out += ` )\n`;
|
|
}
|
|
out += ` }\n}\n\n`;
|
|
}
|
|
out += '#endif\n';
|
|
return out;
|
|
}
|
|
|
|
function detectSwiftVersion(): string {
|
|
if (process.env.SWIFT_VERSION) return process.env.SWIFT_VERSION;
|
|
try {
|
|
const out = execSync('swift --version', { stdio: ['ignore', 'pipe', 'ignore'], timeout: 30_000 }).toString();
|
|
const m = out.match(/Apple Swift version (\d+\.\d+\.\d+)/);
|
|
if (m) return m[1]!;
|
|
} catch {
|
|
/* swift not installed */
|
|
}
|
|
return 'unknown';
|
|
}
|
|
|
|
function detectToolGitRev(): string {
|
|
if (process.env.GEN_ACCESSORS_REV) return process.env.GEN_ACCESSORS_REV;
|
|
try {
|
|
return execSync('git rev-parse --short HEAD', {
|
|
cwd: dirname(new URL(import.meta.url).pathname),
|
|
stdio: ['ignore', 'pipe', 'ignore'],
|
|
timeout: 30_000,
|
|
}).toString().trim();
|
|
} catch {
|
|
return 'dev';
|
|
}
|
|
}
|
|
|
|
function detectBuildId(): string {
|
|
if (process.env.APP_BUILD_ID) return process.env.APP_BUILD_ID;
|
|
const marketing = process.env.MARKETING_VERSION;
|
|
const build = process.env.CURRENT_PROJECT_VERSION;
|
|
if (marketing && build) return `${marketing} (${build})`;
|
|
if (build) return build;
|
|
return 'unknown';
|
|
}
|
|
|
|
export function defaultCacheRoot(): string {
|
|
return process.env.GSTACK_IOS_CACHE_ROOT ?? join(resolveStateRoot(), 'cache', 'gen-accessors');
|
|
}
|
|
|
|
export function generate(inputs: GenInputs): GenResult {
|
|
const inputDir = resolve(inputs.inputDir);
|
|
const outputDir = resolve(inputs.outputDir ?? inputDir);
|
|
const cacheRoot = inputs.cacheRoot ?? defaultCacheRoot();
|
|
const swiftFiles = collectSwiftFiles(inputDir, { outputDir });
|
|
const buildId = inputs.buildId ?? detectBuildId();
|
|
|
|
// Parse before cache lookup. This keeps diagnostics deterministic even when
|
|
// an older cache entry exists, and gives us the schema-only accessor hash.
|
|
const allSpecs: AccessorSpec[] = [];
|
|
for (const f of swiftFiles) {
|
|
const src = readFileSync(f, 'utf-8');
|
|
allSpecs.push(...parseSwift(src));
|
|
}
|
|
validateAccessorSpecs(allSpecs);
|
|
const accessorHash = computeAccessorHash(allSpecs);
|
|
|
|
const cacheKey = computeCacheKey({
|
|
swiftFiles,
|
|
swiftVersion: inputs.swiftVersion ?? detectSwiftVersion(),
|
|
toolGitRev: inputs.toolGitRev ?? detectToolGitRev(),
|
|
platformTriple: inputs.platformTriple ?? FALLBACK_PLATFORM,
|
|
buildId,
|
|
});
|
|
|
|
const cachedOutput = join(cacheRoot, cacheKey, 'StateAccessor.swift');
|
|
const finalOutput = join(outputDir, 'StateAccessor.swift');
|
|
mkdirSync(outputDir, { recursive: true });
|
|
|
|
if (existsSync(cachedOutput)) {
|
|
copyFileSync(cachedOutput, finalOutput);
|
|
// Parse for return value but use cached content as truth.
|
|
return {
|
|
outputPath: finalOutput,
|
|
cacheKey,
|
|
accessorHash,
|
|
specs: allSpecs,
|
|
cacheHit: true,
|
|
};
|
|
}
|
|
|
|
const rendered = render(allSpecs, buildId, accessorHash);
|
|
writeFileSync(finalOutput, rendered);
|
|
|
|
// Populate cache (best-effort — cache failures don't break codegen).
|
|
try {
|
|
mkdirSync(join(cacheRoot, cacheKey), { recursive: true });
|
|
writeFileSync(cachedOutput, rendered);
|
|
} catch {
|
|
// best-effort
|
|
}
|
|
|
|
return {
|
|
outputPath: finalOutput,
|
|
cacheKey,
|
|
accessorHash,
|
|
specs: allSpecs,
|
|
cacheHit: false,
|
|
};
|
|
}
|
|
|
|
export function pruneCache(cacheRoot: string = defaultCacheRoot(), maxAgeDays = 30): { pruned: string[] } {
|
|
const pruned: string[] = [];
|
|
if (!existsSync(cacheRoot)) return { pruned };
|
|
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
|
for (const name of readdirSync(cacheRoot)) {
|
|
const full = join(cacheRoot, name);
|
|
try {
|
|
const s = statSync(full);
|
|
if (s.isDirectory() && s.mtimeMs < cutoff) {
|
|
rmSync(full, { recursive: true, force: true });
|
|
pruned.push(full);
|
|
}
|
|
} catch { /* ignore */ }
|
|
}
|
|
return { pruned };
|
|
}
|
|
|
|
// CLI entry
|
|
if (import.meta.main) {
|
|
const args = process.argv.slice(2);
|
|
const inputIdx = args.indexOf('--input');
|
|
if (inputIdx === -1) {
|
|
process.stderr.write('usage: gen-accessors --input <dir> [--output <dir>]\n');
|
|
process.exit(2);
|
|
}
|
|
const inputDir = args[inputIdx + 1]!;
|
|
const outputIdx = args.indexOf('--output');
|
|
const outputDir = outputIdx !== -1 ? args[outputIdx + 1] : undefined;
|
|
try {
|
|
const result = generate({ inputDir, outputDir });
|
|
process.stdout.write(
|
|
result.cacheHit
|
|
? `gen-accessors: cache hit (${result.cacheKey.slice(0, 12)})\n`
|
|
: `gen-accessors: wrote ${result.specs.length} accessor(s) to ${result.outputPath}\n`,
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof AccessorGenerationError) {
|
|
process.stderr.write(`${error.message}\n`);
|
|
process.exit(4);
|
|
}
|
|
throw error;
|
|
}
|
|
}
|