@quickback-dev/cli 0.66.1 → 0.66.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/README.md +7 -4
  2. package/dist/commands/build.d.ts +51 -0
  3. package/dist/commands/build.d.ts.map +1 -0
  4. package/dist/commands/build.js +804 -0
  5. package/dist/commands/build.js.map +1 -0
  6. package/dist/commands/build.test.d.ts +2 -0
  7. package/dist/commands/build.test.d.ts.map +1 -0
  8. package/dist/commands/build.test.js +150 -0
  9. package/dist/commands/build.test.js.map +1 -0
  10. package/dist/commands/check.d.ts +2 -2
  11. package/dist/commands/check.js +4 -4
  12. package/dist/commands/check.js.map +1 -1
  13. package/dist/commands/create.d.ts +1 -1
  14. package/dist/commands/create.js +7 -7
  15. package/dist/commands/create.js.map +1 -1
  16. package/dist/commands/deploy.d.ts +6 -6
  17. package/dist/commands/deploy.js +23 -23
  18. package/dist/commands/deploy.js.map +1 -1
  19. package/dist/commands/example.js +1 -1
  20. package/dist/commands/example.js.map +1 -1
  21. package/dist/commands/mcp.js +1 -1
  22. package/dist/commands/mcp.js.map +1 -1
  23. package/dist/commands/migrate.d.ts +1 -1
  24. package/dist/commands/migrate.js +3 -3
  25. package/dist/commands/migrate.js.map +1 -1
  26. package/dist/commands/migrations.js +2 -2
  27. package/dist/commands/migrations.js.map +1 -1
  28. package/dist/commands/push.js +1 -1
  29. package/dist/commands/push.js.map +1 -1
  30. package/dist/commands/start.js +1 -1
  31. package/dist/commands/start.js.map +1 -1
  32. package/dist/cursor/quickback.mdc +1 -1
  33. package/dist/index.js +18 -15
  34. package/dist/index.js.map +1 -1
  35. package/dist/lib/auth.js +1 -1
  36. package/dist/lib/auth.js.map +1 -1
  37. package/dist/lib/compiler-floor.d.ts +1 -1
  38. package/dist/lib/compiler-floor.js +1 -1
  39. package/dist/lib/file-loader.js +2 -2
  40. package/dist/lib/file-loader.js.map +1 -1
  41. package/dist/lib/file-writer.d.ts +2 -0
  42. package/dist/lib/file-writer.d.ts.map +1 -1
  43. package/dist/lib/file-writer.js +16 -0
  44. package/dist/lib/file-writer.js.map +1 -1
  45. package/dist/lib/file-writer.test.js +16 -0
  46. package/dist/lib/file-writer.test.js.map +1 -1
  47. package/dist/lib/migrations/file-envelopes.js +3 -3
  48. package/dist/lib/migrations/file-envelopes.js.map +1 -1
  49. package/dist/lib/prepare-output.test.js +1 -1
  50. package/dist/lib/prepare-output.test.js.map +1 -1
  51. package/dist/lib/schema-sync/index.js +1 -1
  52. package/dist/lib/schema-sync/index.test.js +1 -1
  53. package/dist/lib/schema-sync/index.test.js.map +1 -1
  54. package/dist/skill/SKILL.md +6 -6
  55. package/dist/skill/docs/api/actions.md +27 -3
  56. package/dist/skill/docs/api/batch-operations.md +4 -0
  57. package/dist/skill/docs/api/crud.md +64 -0
  58. package/dist/skill/docs/api/index.md +1 -1
  59. package/dist/skill/docs/api/openapi.md +1 -1
  60. package/dist/skill/docs/api/query-params.md +19 -2
  61. package/dist/skill/docs/changelog/index.md +33 -1
  62. package/dist/skill/docs/configure/agents.md +1 -1
  63. package/dist/skill/docs/configure/index.md +8 -3
  64. package/dist/skill/docs/configure/providers.md +3 -0
  65. package/dist/skill/docs/configure/variables.md +3 -3
  66. package/dist/skill/docs/define/access.md +7 -0
  67. package/dist/skill/docs/define/actions/defining.md +39 -8
  68. package/dist/skill/docs/define/actions/record-and-standalone.md +7 -4
  69. package/dist/skill/docs/define/actions/scoped-db.md +46 -16
  70. package/dist/skill/docs/define/areas.md +1 -1
  71. package/dist/skill/docs/define/diagnostics.md +1 -0
  72. package/dist/skill/docs/define/encryption.md +1 -1
  73. package/dist/skill/docs/define/feature.md +14 -7
  74. package/dist/skill/docs/define/guards.md +34 -3
  75. package/dist/skill/docs/define/schema.md +29 -17
  76. package/dist/skill/docs/define/security.md +1 -1
  77. package/dist/skill/docs/define/transitions.md +35 -4
  78. package/dist/skill/docs/define/views.md +33 -0
  79. package/dist/skill/docs/index.md +2 -2
  80. package/dist/skill/docs/platform/auth/api-keys.md +1 -1
  81. package/dist/skill/docs/platform/auth/using-auth.md +37 -0
  82. package/dist/skill/docs/platform/database/d1.md +2 -2
  83. package/dist/skill/docs/platform/database/neon.md +4 -4
  84. package/dist/skill/docs/platform/email/index.md +1 -1
  85. package/dist/skill/docs/platform/queues/handlers.md +1 -1
  86. package/dist/skill/docs/platform/queues/using-queues.md +1 -1
  87. package/dist/skill/docs/platform/schedules/index.md +1 -1
  88. package/dist/skill/docs/platform/storage/index.md +3 -3
  89. package/dist/skill/docs/platform/storage/r2.md +87 -37
  90. package/dist/skill/docs/platform/storage/using-r2.md +99 -19
  91. package/dist/skill/docs/platform/webhooks/inbound.md +40 -0
  92. package/dist/skill/docs/start/deploy-browser.md +39 -44
  93. package/dist/skill/docs/start/deploy-owner-access.md +28 -19
  94. package/dist/skill/docs/start/deploy.md +2 -2
  95. package/dist/skill/docs/start/first-api.md +1 -1
  96. package/dist/skill/docs/start/hand-crafted.md +3 -3
  97. package/dist/skill/docs/start/index.md +3 -3
  98. package/dist/skill/docs/start/quickstart.md +3 -3
  99. package/dist/skill/docs/start/template-blog.md +2 -2
  100. package/dist/skill/docs/start/template-cloudflare.md +2 -2
  101. package/dist/skill/docs/start/template-empty.md +1 -1
  102. package/dist/skill/docs/start/templates.md +1 -1
  103. package/dist/skill/docs/tooling/claude-skill.md +1 -1
  104. package/dist/skill/docs/tooling/cli.md +40 -19
  105. package/dist/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  106. package/dist/skill/docs/tooling/cloud-compiler/endpoints.md +5 -3
  107. package/dist/skill/docs/tooling/cloud-compiler/index.md +1 -1
  108. package/dist/skill/docs/tooling/cloud-compiler/local-compiler.md +2 -2
  109. package/dist/skill/docs/tooling/cloud-compiler/troubleshooting.md +47 -2
  110. package/dist/skill/docs/tooling/output.md +32 -2
  111. package/dist/skill/docs/tooling/troubleshooting.md +1 -1
  112. package/dist/skill/docs/ui/account/environment-variables.md +2 -2
  113. package/dist/skill/docs/ui/account/features/admin.md +1 -1
  114. package/dist/skill/docs/ui/account/features/avatars.md +24 -8
  115. package/dist/skill/docs/ui/account/features/index.md +9 -5
  116. package/dist/skill/docs/ui/account/features/organizations.md +3 -2
  117. package/dist/skill/docs/ui/account/index.md +3 -1
  118. package/dist/skill/docs/ui/account/with-quickback.md +1 -1
  119. package/dist/skill/docs/ui/admin/actions.md +97 -3
  120. package/dist/skill/docs/ui/admin/components.md +4 -6
  121. package/dist/skill/docs/ui/admin/connecting.md +15 -3
  122. package/dist/skill/docs/ui/admin/index.md +71 -6
  123. package/dist/skill/docs/ui/admin/inline-editing.md +38 -4
  124. package/dist/skill/docs/ui/admin/record-layouts.md +22 -21
  125. package/dist/skill/docs/ui/admin/schema-format.md +39 -2
  126. package/dist/skill/docs/ui/admin/schema-registry.md +107 -7
  127. package/dist/skill/docs/ui/admin/security.md +19 -4
  128. package/dist/skill/docs/ui/admin/table-views.md +59 -12
  129. package/package.json +1 -1
  130. package/src/cursor/quickback.mdc +1 -1
  131. package/src/skill/SKILL.md +6 -6
  132. package/src/skill/docs/api/actions.md +27 -3
  133. package/src/skill/docs/api/batch-operations.md +4 -0
  134. package/src/skill/docs/api/crud.md +64 -0
  135. package/src/skill/docs/api/index.md +1 -1
  136. package/src/skill/docs/api/openapi.md +1 -1
  137. package/src/skill/docs/api/query-params.md +19 -2
  138. package/src/skill/docs/changelog/index.md +33 -1
  139. package/src/skill/docs/configure/agents.md +1 -1
  140. package/src/skill/docs/configure/index.md +8 -3
  141. package/src/skill/docs/configure/providers.md +3 -0
  142. package/src/skill/docs/configure/variables.md +3 -3
  143. package/src/skill/docs/define/access.md +7 -0
  144. package/src/skill/docs/define/actions/defining.md +39 -8
  145. package/src/skill/docs/define/actions/record-and-standalone.md +7 -4
  146. package/src/skill/docs/define/actions/scoped-db.md +46 -16
  147. package/src/skill/docs/define/areas.md +1 -1
  148. package/src/skill/docs/define/diagnostics.md +1 -0
  149. package/src/skill/docs/define/encryption.md +1 -1
  150. package/src/skill/docs/define/feature.md +14 -7
  151. package/src/skill/docs/define/guards.md +34 -3
  152. package/src/skill/docs/define/schema.md +29 -17
  153. package/src/skill/docs/define/security.md +1 -1
  154. package/src/skill/docs/define/transitions.md +35 -4
  155. package/src/skill/docs/define/views.md +33 -0
  156. package/src/skill/docs/index.md +2 -2
  157. package/src/skill/docs/platform/auth/api-keys.md +1 -1
  158. package/src/skill/docs/platform/auth/using-auth.md +37 -0
  159. package/src/skill/docs/platform/database/d1.md +2 -2
  160. package/src/skill/docs/platform/database/neon.md +4 -4
  161. package/src/skill/docs/platform/email/index.md +1 -1
  162. package/src/skill/docs/platform/queues/handlers.md +1 -1
  163. package/src/skill/docs/platform/queues/using-queues.md +1 -1
  164. package/src/skill/docs/platform/schedules/index.md +1 -1
  165. package/src/skill/docs/platform/storage/index.md +3 -3
  166. package/src/skill/docs/platform/storage/r2.md +87 -37
  167. package/src/skill/docs/platform/storage/using-r2.md +99 -19
  168. package/src/skill/docs/platform/webhooks/inbound.md +40 -0
  169. package/src/skill/docs/start/deploy-browser.md +39 -44
  170. package/src/skill/docs/start/deploy-owner-access.md +28 -19
  171. package/src/skill/docs/start/deploy.md +2 -2
  172. package/src/skill/docs/start/first-api.md +1 -1
  173. package/src/skill/docs/start/hand-crafted.md +3 -3
  174. package/src/skill/docs/start/index.md +3 -3
  175. package/src/skill/docs/start/quickstart.md +3 -3
  176. package/src/skill/docs/start/template-blog.md +2 -2
  177. package/src/skill/docs/start/template-cloudflare.md +2 -2
  178. package/src/skill/docs/start/template-empty.md +1 -1
  179. package/src/skill/docs/start/templates.md +1 -1
  180. package/src/skill/docs/tooling/claude-skill.md +1 -1
  181. package/src/skill/docs/tooling/cli.md +40 -19
  182. package/src/skill/docs/tooling/cloud-compiler/authentication.md +1 -1
  183. package/src/skill/docs/tooling/cloud-compiler/endpoints.md +5 -3
  184. package/src/skill/docs/tooling/cloud-compiler/index.md +1 -1
  185. package/src/skill/docs/tooling/cloud-compiler/local-compiler.md +2 -2
  186. package/src/skill/docs/tooling/cloud-compiler/troubleshooting.md +47 -2
  187. package/src/skill/docs/tooling/output.md +32 -2
  188. package/src/skill/docs/tooling/troubleshooting.md +1 -1
  189. package/src/skill/docs/ui/account/environment-variables.md +2 -2
  190. package/src/skill/docs/ui/account/features/admin.md +1 -1
  191. package/src/skill/docs/ui/account/features/avatars.md +24 -8
  192. package/src/skill/docs/ui/account/features/index.md +9 -5
  193. package/src/skill/docs/ui/account/features/organizations.md +3 -2
  194. package/src/skill/docs/ui/account/index.md +3 -1
  195. package/src/skill/docs/ui/account/with-quickback.md +1 -1
  196. package/src/skill/docs/ui/admin/actions.md +97 -3
  197. package/src/skill/docs/ui/admin/components.md +4 -6
  198. package/src/skill/docs/ui/admin/connecting.md +15 -3
  199. package/src/skill/docs/ui/admin/index.md +71 -6
  200. package/src/skill/docs/ui/admin/inline-editing.md +38 -4
  201. package/src/skill/docs/ui/admin/record-layouts.md +22 -21
  202. package/src/skill/docs/ui/admin/schema-format.md +39 -2
  203. package/src/skill/docs/ui/admin/schema-registry.md +107 -7
  204. package/src/skill/docs/ui/admin/security.md +19 -4
  205. package/src/skill/docs/ui/admin/table-views.md +59 -12
@@ -0,0 +1,804 @@
1
+ /**
2
+ * Compile Command
3
+ *
4
+ * Loads configuration and features from disk, calls the remote compiler API,
5
+ * writes the generated files to the project root, and runs post-compile commands.
6
+ *
7
+ * Project structure:
8
+ * my-app/
9
+ * ├── quickback/
10
+ * │ ├── quickback.config.ts
11
+ * │ ├── features/...
12
+ * │ └── drizzle/ ← migration SQL + meta (compiler-owned)
13
+ * ├── src/ ← compiled code written here
14
+ * ├── supabase/migrations/ ← for Supabase provider
15
+ * └── package.json
16
+ */
17
+ import { join, dirname, resolve, relative, sep } from 'path';
18
+ import fs from 'fs/promises';
19
+ import pc from 'picocolors';
20
+ import ora from 'ora';
21
+ import { callCompiler, getApiUrl } from '../lib/api-client.js';
22
+ import { harvestActionInputSchemasDetailed, missingActionInputSchemaKeys, } from '../lib/action-harvest.js';
23
+ import { ensureAuthForCompile, getStoredUser } from '../lib/auth.js';
24
+ import { loadConfig, loadFeatures, findConfigPath, findFeaturesDir, findServicesDir, loadServices, loadDrizzleMeta, loadProjectLib, loadProjectHooks, loadProjectPlugins, loadProjectEmailTemplates, loadProjectMiddlewares } from '../lib/file-loader.js';
25
+ import { writeFilesWithMerge } from '../lib/file-writer.js';
26
+ import { commitStagedMigrations } from '../lib/migrations/commit.js';
27
+ import { executeClientMigrationPlan } from '../lib/migrations/executor.js';
28
+ import { createPromptAwareMigrationRunner } from '../lib/migrations/prompt-runner.js';
29
+ import { createMigrationPostprocessors } from '../lib/migrations/postprocessors/index.js';
30
+ import { buildClientMigrationPriorState } from '../lib/migrations/prior-state.js';
31
+ import { computeSchemaHash, resolveSchemaEngineVersion } from '../lib/migrations/schema-contract.js';
32
+ import { prepareGeneratedDir } from '../lib/prepare-output.js';
33
+ import { prepareStateArtifacts } from '../lib/prepare-state-output.js';
34
+ import { copyPublicAssets, PublicAssetCollisionError } from '../lib/copy-public-assets.js';
35
+ import { copySourceApps, SourceAppCollisionError } from '../lib/copy-source-apps.js';
36
+ import { isSecurityReportArtifactContent, partitionGeneratedFiles } from '../lib/artifact-routing.js';
37
+ import { runCommand } from '../lib/shell.js';
38
+ // Feature-areas compiler floor + capability recognition — extracted so the
39
+ // fail-closed predicates are unit-tested (compiler-floor.test.ts).
40
+ import { FEATURE_AREAS_COMPILER_FLOOR, compilerSupportsAreas, firstUnknownCapability, } from '../lib/compiler-floor.js';
41
+ import { syncConfigFile } from '../lib/config-sync.js';
42
+ import { getCompileNextSteps } from '../lib/compile-next-steps.js';
43
+ import { applyProjectSchemaSync, planProjectSchemaSync, renderProjectSchemaDiff, renderSchemaDiagnostics, } from '../lib/schema-sync/index.js';
44
+ import { login } from './login.js';
45
+ import { pathExists } from '../lib/async-utils.js';
46
+ /**
47
+ * Where the compiler emits spec blobs (v0.60+). They live under the assets
48
+ * directory rather than the project root so the Worker can serve them through
49
+ * the ASSETS binding instead of importing them — keeping multi-MB specs out of
50
+ * the bundle V8 parses at isolate startup.
51
+ *
52
+ * Mirrors `SPEC_ASSET_DIR` in the compiler; the two packages share no code.
53
+ */
54
+ const SPEC_ASSET_DIR = 'src/apps/__quickback/spec';
55
+ function areSamePath(a, b) {
56
+ return resolve(a) === resolve(b);
57
+ }
58
+ async function resolveQuickbackStateDir(projectRoot, outputDir) {
59
+ const quickbackDir = join(projectRoot, 'quickback');
60
+ if (areSamePath(quickbackDir, outputDir))
61
+ return undefined;
62
+ return await pathExists(quickbackDir) ? quickbackDir : undefined;
63
+ }
64
+ async function syncSecurityReportsToQuickback(projectRoot, outputDir, generatedFiles) {
65
+ const quickbackDir = join(projectRoot, 'quickback');
66
+ if (areSamePath(quickbackDir, outputDir))
67
+ return 0;
68
+ if (!await pathExists(quickbackDir))
69
+ return 0;
70
+ const reportFiles = generatedFiles.filter((file) => file.path.endsWith('.json') && isSecurityReportArtifactContent(file.content));
71
+ let synced = 0;
72
+ for (const file of reportFiles) {
73
+ const targetPath = join(quickbackDir, file.path);
74
+ await fs.mkdir(dirname(targetPath), { recursive: true });
75
+ await fs.writeFile(targetPath, file.content, 'utf-8');
76
+ synced += 1;
77
+ }
78
+ return synced;
79
+ }
80
+ /**
81
+ * `build.outputDir` → the migration staging workspace's `outputRootPath`.
82
+ *
83
+ * The two use different bases, which is the whole reason this exists.
84
+ * `outputDir` is authored relative to the **quickback/ dir** (every other
85
+ * reader does `join(quickbackDir, outputDir)`), while staging resolves its
86
+ * paths against the **project root** and rejects anything containing `..`.
87
+ * Passing the raw value made a legitimate `outputDir: "../src"` — config in
88
+ * `quickback/`, generated tree at `<root>/src`, the standard nested layout —
89
+ * read as a path-escape attempt and fail the compile.
90
+ *
91
+ * Returns a POSIX-style path relative to the project root, or `undefined`
92
+ * when the project doesn't set `outputDir`.
93
+ */
94
+ export function resolveOutputRootPath(projectRoot, quickbackDir, outputDir) {
95
+ if (!outputDir)
96
+ return undefined;
97
+ return relative(projectRoot, join(quickbackDir, outputDir)).split(sep).join('/');
98
+ }
99
+ export async function build(options = {}) {
100
+ const syncConfig = options.syncConfig !== false;
101
+ const verbose = options.verbose === true;
102
+ const fixSchema = options.fixSchema === true;
103
+ console.log(pc.bold('Quickback Build'));
104
+ // Show auth status (and prompt if missing).
105
+ const apiUrl = getApiUrl();
106
+ const authResult = await ensureAuthForCompile({ apiUrl, loginFn: login });
107
+ if (authResult.status === 'cancelled') {
108
+ console.log(pc.gray('\nNo problem — re-run when you\'re ready. You can also `quickback login` directly.'));
109
+ process.exit(0);
110
+ }
111
+ if (authResult.status === 'authenticated') {
112
+ if (authResult.via === 'api-key') {
113
+ console.log(pc.gray('Auth: API key (x-api-key)'));
114
+ }
115
+ else {
116
+ const user = await getStoredUser();
117
+ console.log(pc.gray(`Auth: ${user?.email || 'session'} (Bearer)`));
118
+ }
119
+ }
120
+ console.log(pc.gray(`API: ${apiUrl}\n`));
121
+ const spinner = ora('Loading configuration...').start();
122
+ try {
123
+ // Find config file
124
+ const configPath = await findConfigPath();
125
+ if (!configPath) {
126
+ spinner.fail('Configuration not found');
127
+ console.error(pc.red('Error: quickback.config.ts not found'));
128
+ console.log("Run 'quickback init' to create a new project structure");
129
+ process.exit(1);
130
+ }
131
+ // Determine project root (parent of quickback/ folder)
132
+ const quickbackDir = dirname(configPath);
133
+ const projectRoot = configPath.includes('/quickback/')
134
+ ? dirname(quickbackDir) // Config in quickback/ folder → parent is project root
135
+ : process.cwd(); // Config at cwd → cwd is project root
136
+ // Load config
137
+ const config = await loadConfig(configPath);
138
+ spinner.succeed(`Configuration loaded: ${pc.cyan(config.name)}`);
139
+ // Validate capability floor markers this CLI understands (fail fast,
140
+ // before any loading — an unknown capability means this CLI predates it).
141
+ {
142
+ const unknownCap = firstUnknownCapability(config.requires);
143
+ if (unknownCap) {
144
+ throw new Error(`quickback.config.ts requires capability "${unknownCap}", which this CLI does not ` +
145
+ `recognize. Upgrade @quickback-dev/cli (npm i -g @quickback-dev/cli@latest).`);
146
+ }
147
+ }
148
+ // Keep the authored feature tables as the local source of truth for the
149
+ // managed audit/soft-delete columns the compiler would otherwise inject.
150
+ // Plan before loading features so --fix-schema is reflected in the exact
151
+ // source sent to the compiler.
152
+ const compilerFeatureOptions = config.compiler?.features;
153
+ const schemaPlan = await planProjectSchemaSync({
154
+ projectRoot,
155
+ dialect: config.providers?.database?.name === 'neon' ? 'postgres' : 'sqlite',
156
+ namingConvention: config.providers?.database?.config?.namingConvention === 'camelCase'
157
+ ? 'camelCase'
158
+ : 'snake_case',
159
+ auditFields: compilerFeatureOptions?.auditFields !== false &&
160
+ compilerFeatureOptions?.visibleAuditColumns !== false,
161
+ });
162
+ if (schemaPlan.diagnostics.length > 0) {
163
+ throw new Error(`Authored schema synchronization needs manual attention:\n\n` +
164
+ renderSchemaDiagnostics(schemaPlan.diagnostics, projectRoot));
165
+ }
166
+ if (schemaPlan.changedFiles.length > 0) {
167
+ if (!fixSchema) {
168
+ throw new Error(`Authored feature schemas are missing managed-column declarations:\n\n` +
169
+ `${renderProjectSchemaDiff(schemaPlan)}\n\n` +
170
+ `Run \`quickback schema sync\` or re-run with \`quickback build --fix-schema\`.`);
171
+ }
172
+ const applied = await applyProjectSchemaSync(schemaPlan);
173
+ console.log(pc.gray(` Synchronized ${applied.changedFiles.length} authored schema file(s) before compile`));
174
+ }
175
+ // Load features (recursive tree walk — feature areas)
176
+ spinner.start('Loading features...');
177
+ const featuresDir = await findFeaturesDir(projectRoot);
178
+ const { features, areas } = featuresDir
179
+ ? await loadFeatures(featuresDir)
180
+ : { features: [], areas: [] };
181
+ spinner.succeed(`Loaded ${features.length} feature(s)${areas.length > 0 ? ` in ${areas.length} area(s)` : ''}`);
182
+ // Load project-level shared lib (quickback/lib/) — cross-feature TypeScript
183
+ // imported via the `~/lib/*` alias by any feature.
184
+ const projectLib = await loadProjectLib(projectRoot);
185
+ if (Object.keys(projectLib).length > 0) {
186
+ console.log(pc.gray(` Loaded ${Object.keys(projectLib).length} shared lib file(s) from quickback/lib/`));
187
+ }
188
+ // Load project-level auth hooks (quickback/hooks/) — wired into Better Auth's databaseHooks.
189
+ const projectHooks = await loadProjectHooks(projectRoot);
190
+ if (Object.keys(projectHooks).length > 0) {
191
+ console.log(pc.gray(` Loaded ${Object.keys(projectHooks).length} auth hook(s) from quickback/hooks/`));
192
+ }
193
+ // Load user-authored Better Auth plugin source files (quickback/plugins/) —
194
+ // referenced from defineAuth("better-auth", { customPlugins: [{ from: "./plugins/..." }] }).
195
+ const projectPlugins = await loadProjectPlugins(projectRoot);
196
+ if (Object.keys(projectPlugins).length > 0) {
197
+ console.log(pc.gray(` Loaded ${Object.keys(projectPlugins).length} plugin file(s) from quickback/plugins/`));
198
+ }
199
+ // Load project-supplied email templates (quickback/email-templates/) —
200
+ // referenced from defineAuth("better-auth", { plugins: { emailOtp: { templates: { '<type>': './email-templates/...' } } } }).
201
+ const projectEmailTemplates = await loadProjectEmailTemplates(projectRoot);
202
+ if (Object.keys(projectEmailTemplates).length > 0) {
203
+ console.log(pc.gray(` Loaded ${Object.keys(projectEmailTemplates).length} email template(s) from quickback/email-templates/`));
204
+ }
205
+ // Load project-level Hono middlewares (quickback/middlewares/) — declarative
206
+ // cross-cutting slot mounted between platform middleware and route registration.
207
+ const projectMiddlewares = await loadProjectMiddlewares(projectRoot);
208
+ if (Object.keys(projectMiddlewares).length > 0) {
209
+ console.log(pc.gray(` Loaded ${Object.keys(projectMiddlewares).length} middleware(s) from quickback/middlewares/`));
210
+ }
211
+ // Load services (queues, realtime, embeddings, live views)
212
+ spinner.start('Loading services...');
213
+ const servicesDir = await findServicesDir(projectRoot);
214
+ const services = servicesDir ? await loadServices(servicesDir) : undefined;
215
+ const queueCount = services?.queues?.length || 0;
216
+ const scheduleCount = services?.schedules?.length || 0;
217
+ const emailCount = services?.email?.length || 0;
218
+ const realtimeCount = services?.realtime?.length || 0;
219
+ const embeddingCount = services?.embeddings?.length || 0;
220
+ const viewCount = services?.views?.length || 0;
221
+ const totalServices = queueCount + scheduleCount + emailCount + realtimeCount + embeddingCount + viewCount;
222
+ if (totalServices > 0) {
223
+ const parts = [];
224
+ if (queueCount > 0)
225
+ parts.push(`${queueCount} queue(s)`);
226
+ if (scheduleCount > 0)
227
+ parts.push(`${scheduleCount} schedule(s)`);
228
+ if (emailCount > 0)
229
+ parts.push(`${emailCount} email handler(s)`);
230
+ if (realtimeCount > 0)
231
+ parts.push(`${realtimeCount} realtime namespace(s)`);
232
+ if (embeddingCount > 0)
233
+ parts.push(`${embeddingCount} embedding config(s)`);
234
+ if (viewCount > 0)
235
+ parts.push(`${viewCount} live view(s)`);
236
+ spinner.succeed(`Loaded services: ${parts.join(', ')}`);
237
+ }
238
+ else {
239
+ spinner.info('No services defined');
240
+ }
241
+ // Determine output directory first (needed for loading existing meta)
242
+ const outputDir = config.build?.outputDir
243
+ ? join(quickbackDir, config.build.outputDir)
244
+ : projectRoot;
245
+ // Load existing drizzle meta. Migration state always lives under
246
+ // <project>/quickback/drizzle/... even when the generated runtime tree is
247
+ // written to a nested build.outputDir.
248
+ //
249
+ // The history NEVER leaves this machine. It is read here only to derive
250
+ // the two facts the compiler needs about prior state — the non-id primary
251
+ // keys it must not rewrite, and whether the audit sink was ever emitted —
252
+ // which travel as a few hundred bytes instead of the whole tree. Drizzle
253
+ // runs locally against this same state after the compile returns.
254
+ const drizzleMeta = await loadDrizzleMeta(projectRoot);
255
+ if (drizzleMeta) {
256
+ console.log(pc.gray(` Found existing migration state (${Object.keys(drizzleMeta).length} files, local)`));
257
+ }
258
+ const priorState = buildClientMigrationPriorState(drizzleMeta);
259
+ const schemaEngineVersion = await resolveSchemaEngineVersion();
260
+ // Existing wrangler.toml — forwarded so the compiler can preserve the
261
+ // deployed Durable Object [[migrations]] sequence. CF rejects deploys
262
+ // (code 10061) when the migration list isn't append-only, so a new DO
263
+ // inserted into the middle of `bindings.durableObjects` would otherwise
264
+ // bump every later auto-migration into the wrong slot.
265
+ let existingWranglerToml;
266
+ try {
267
+ existingWranglerToml = await fs.readFile(join(outputDir, 'wrangler.toml'), 'utf-8');
268
+ }
269
+ catch {
270
+ /* No existing wrangler.toml — first compile or generated tree was wiped. Compiler falls back to config order. */
271
+ }
272
+ // Collect page definitions from all features
273
+ const allPages = features.flatMap((f) => (f.pageFiles || []).map((p) => ({
274
+ fileName: p.fileName,
275
+ slug: p.slug,
276
+ feature: p.feature,
277
+ title: p.title,
278
+ source: p.source,
279
+ })));
280
+ const pageCount = allPages.length;
281
+ if (pageCount > 0) {
282
+ console.log(pc.gray(` Found ${pageCount} page definition(s)`));
283
+ }
284
+ // Harvest action input schemas LOCALLY (z.toJSONSchema on the user's own
285
+ // machine) so the compiler never has to execute user action code. V1 keeps
286
+ // the historical static-schema fallback. V2 fails closed and reports the
287
+ // isolated bundle/evaluation reason for each missing action. Only
288
+ // meaningful when there are action files on disk.
289
+ let actionInputSchemas;
290
+ let actionOutputSchemas;
291
+ const hasActionFiles = features.some((f) => Object.keys(f.actionFiles || {}).length > 0);
292
+ // Fail-closed for EVERY contract version since v0.63.0, not just v2. The
293
+ // static fallback cannot emit `required` or `additionalProperties`, so a
294
+ // partial harvest ships operations that look typed and enforce nothing —
295
+ // invisible in a diff, and only caught by comparing specs structurally.
296
+ //
297
+ // This gate lives in the CLI, not the compiler, because only the CLI knows
298
+ // a harvest was ATTEMPTED: Start and other direct API callers post
299
+ // `rawFiles` with no schemas at all (apps/start/server/core.ts) and would
300
+ // fail closed on a check the compiler cannot scope to harvesting clients.
301
+ if (featuresDir && hasActionFiles) {
302
+ spinner.start('Resolving action input schemas...');
303
+ const harvest = await harvestActionInputSchemasDetailed({
304
+ projectRoot,
305
+ featuresDir,
306
+ // `sourceDir` (the authored, area-aware directory) MUST be threaded
307
+ // here — reconstructing the path from `name` alone breaks nested-area
308
+ // action lookup (the v2 harvest then fails to resolve bare/local imports).
309
+ features: features.map((f) => ({ name: f.name, sourceDir: f.sourceDir, actionFiles: f.actionFiles })),
310
+ // Generated runtimes may intentionally live below/sibling to the
311
+ // authored quickback tree. Their installed dependencies cannot be
312
+ // found by Node's normal upward resolution from an action file.
313
+ dependencyRoots: [join(outputDir, 'node_modules')],
314
+ });
315
+ const harvested = harvest.schemas;
316
+ const count = Object.keys(harvested).length;
317
+ const missing = missingActionInputSchemaKeys(features, harvested);
318
+ const diagnosticsByKey = new Map(harvest.diagnostics.map((diagnostic) => [diagnostic.key, diagnostic]));
319
+ const details = missing.map((key) => {
320
+ const diagnostic = diagnosticsByKey.get(key);
321
+ return diagnostic
322
+ ? ` - ${key} [${diagnostic.phase}]: ${diagnostic.message}`
323
+ : ` - ${key}: no schema or diagnostic was produced`;
324
+ });
325
+ if (missing.length > 0) {
326
+ spinner.fail(`${missing.length} action input schema(s) failed to harvest`);
327
+ throw new Error(`Every action input schema must harvest successfully. Missing ${missing.length} of ` +
328
+ `${missing.length + count}: ${missing.join(', ')}\n` +
329
+ `Action harvest diagnostics:\n${details.join('\n')}\n\n` +
330
+ `These actions would fall back to the compiler's static Zod parser, which cannot emit ` +
331
+ `\`required\` or \`additionalProperties\` — the operations would look typed in openapi.json ` +
332
+ `and the MCP tool list while enforcing nothing.\n` +
333
+ `Fix the actions above so every input schema harvests.`);
334
+ }
335
+ if (count > 0) {
336
+ actionInputSchemas = harvested;
337
+ if (Object.keys(harvest.outputSchemas).length > 0) {
338
+ actionOutputSchemas = harvest.outputSchemas;
339
+ }
340
+ spinner.succeed(`Resolved ${count} action input schema(s)`);
341
+ }
342
+ else {
343
+ spinner.info('No action input schemas resolved (using static schemas)');
344
+ }
345
+ }
346
+ else if (hasActionFiles && !featuresDir) {
347
+ // Actions on disk but no features dir to harvest from: the compiler
348
+ // would silently static-parse all of them.
349
+ console.log(pc.yellow('⚠ Action files found but no features directory resolved — action input schemas cannot harvest.'));
350
+ }
351
+ // Call remote compiler API
352
+ spinner.start('Compiling via Quickback API...');
353
+ const result = await callCompiler({
354
+ config,
355
+ actionInputSchemas,
356
+ actionOutputSchemas,
357
+ features: features.map((f) => ({
358
+ name: f.name,
359
+ // Feature areas: ancestor area dirs, outermost first.
360
+ areaPath: f.areaPath,
361
+ schema: f.schema,
362
+ tables: f.tables,
363
+ resourceSource: f.resourceSource,
364
+ // One-file-per-action shape — see apps/compiler/src/discovery/feature-walker.ts
365
+ actionFiles: f.actionFiles,
366
+ featureLibFiles: f.featureLibFiles,
367
+ })),
368
+ // Feature areas: executed _area.ts nodes with their directory position.
369
+ areas: areas.length > 0 ? areas : undefined,
370
+ // Project-level shared lib at quickback/lib/, aliased as `~/lib/*`
371
+ projectLib: Object.keys(projectLib).length > 0 ? projectLib : undefined,
372
+ // Project-level auth hooks at quickback/hooks/ — wired into Better Auth's databaseHooks.
373
+ projectHooks: Object.keys(projectHooks).length > 0 ? projectHooks : undefined,
374
+ // User-authored Better Auth plugin source files at quickback/plugins/.
375
+ projectPlugins: Object.keys(projectPlugins).length > 0 ? projectPlugins : undefined,
376
+ // Project-supplied email templates at quickback/email-templates/, referenced by `plugins.emailOtp.templates`.
377
+ projectEmailTemplates: Object.keys(projectEmailTemplates).length > 0 ? projectEmailTemplates : undefined,
378
+ // Project-level Hono middlewares at quickback/middlewares/ — declarative cross-cutting slot.
379
+ projectMiddlewares: Object.keys(projectMiddlewares).length > 0 ? projectMiddlewares : undefined,
380
+ // Include services (queue handlers, realtime, embeddings, pages)
381
+ services: services || allPages.length > 0 ? {
382
+ queues: services?.queues?.map((q) => ({
383
+ fileName: q.fileName,
384
+ name: q.name,
385
+ messageType: q.messageType,
386
+ source: q.source,
387
+ })),
388
+ schedules: services?.schedules?.map((s) => ({
389
+ fileName: s.fileName,
390
+ name: s.name,
391
+ cron: s.cron,
392
+ source: s.source,
393
+ })),
394
+ email: services?.email?.map((e) => ({
395
+ fileName: e.fileName,
396
+ name: e.name,
397
+ to: e.to,
398
+ source: e.source,
399
+ })),
400
+ realtime: services?.realtime?.map((r) => ({
401
+ fileName: r.fileName,
402
+ name: r.name,
403
+ events: r.events,
404
+ source: r.source,
405
+ })),
406
+ embeddings: services?.embeddings?.map((e) => ({
407
+ fileName: e.fileName,
408
+ name: e.name,
409
+ sourceTable: e.source,
410
+ source: e.sourceCode,
411
+ })),
412
+ // Live views (defineView at services/views/*) — the compiler
413
+ // re-parses `source` for the full include tree.
414
+ views: services?.views?.map((v) => ({
415
+ fileName: v.fileName,
416
+ name: v.name,
417
+ root: v.root,
418
+ source: v.source,
419
+ })),
420
+ pages: allPages.length > 0 ? allPages : undefined,
421
+ } : undefined,
422
+ // Migration ownership: the CLI runs drizzle locally. Instead of the
423
+ // full history this carries the derived prior-state facts plus the
424
+ // existing wrangler.toml (so the compiler preserves the deployed
425
+ // [[migrations]] order — Cloudflare rejects out-of-order migrations).
426
+ // `existingFiles` is deliberately absent; the compiler rejects the
427
+ // request outright if it reappears.
428
+ migration: {
429
+ version: 2,
430
+ owner: 'cli',
431
+ schema: {
432
+ engineVersion: schemaEngineVersion,
433
+ schemaHash: computeSchemaHash(features, config),
434
+ },
435
+ priorState,
436
+ existingRuntimeState: existingWranglerToml
437
+ ? { wranglerToml: existingWranglerToml }
438
+ : undefined,
439
+ },
440
+ }, // Type assertion for the broader compile payload
441
+ (msg) => spinner.text = msg, { verbose });
442
+ // Feature areas: fail CLOSED before accepting output when the responding
443
+ // compiler predates the `areas` payload. An old compiler ignores unknown
444
+ // keys — it would return a compile of the project WITHOUT its area
445
+ // namespaces/vocabulary, and writing that output could produce
446
+ // destructive migrations. Absent meta.version (pre-meta compilers) also
447
+ // fails — never assume support.
448
+ if (areas.length > 0) {
449
+ const compilerVersion = result.meta?.version;
450
+ if (!compilerSupportsAreas(compilerVersion)) {
451
+ throw new Error(`This project uses feature areas (_area.ts), which require compiler ` +
452
+ `>= ${FEATURE_AREAS_COMPILER_FLOOR}, but the responding compiler reported ` +
453
+ `${compilerVersion ? `version ${compilerVersion}` : 'no version'}. Refusing the ` +
454
+ `output — an area-unaware compiler silently drops area admission gates. ` +
455
+ `Point QUICKBACK_API_URL at a current compiler (or use the hosted default).`);
456
+ }
457
+ }
458
+ const totalSecs = result.meta.timings ? (result.meta.timings.totalMs / 1000).toFixed(1) : null;
459
+ spinner.succeed(`Compiled ${result.meta.fileCount} files (v${result.meta.version})${totalSecs ? ` in ${totalSecs}s` : ''}`);
460
+ // Show what was generated — SPA builds, schema registry, OpenAPI
461
+ const spaBuilds = result.meta.timings?.commands?.filter((c) => c.description.includes('SPA build')) || [];
462
+ for (const spa of spaBuilds) {
463
+ const name = spa.description.replace(' SPA build', '');
464
+ const secs = (spa.ms / 1000).toFixed(1);
465
+ if (spa.success) {
466
+ // Count SPA files in the output
467
+ const spaPrefix = `src/apps/${name}/`;
468
+ const spaFiles = result.files.filter((f) => f.path.startsWith(spaPrefix));
469
+ const assetFiles = spaFiles.filter((f) => f.path.includes('/assets/'));
470
+ const info = assetFiles.length > 0
471
+ ? `${assetFiles.length} assets, ${secs}s`
472
+ : `${secs}s`;
473
+ console.log(pc.gray(` ${pc.green('●')} ${name} SPA built (${info})`));
474
+ }
475
+ else {
476
+ console.log(pc.yellow(` ${pc.red('●')} ${name} SPA build failed`));
477
+ }
478
+ }
479
+ // Show skipped SPAs
480
+ const cmsObj = typeof config.cms === 'object' ? config.cms : null;
481
+ const accountObj = typeof config.account === 'object' ? config.account : null;
482
+ if (config.cms && cmsObj?.build === false) {
483
+ console.log(pc.gray(` ${pc.dim('○')} cms SPA skipped (build: false)`));
484
+ }
485
+ if (config.account && accountObj?.build === false) {
486
+ console.log(pc.gray(` ${pc.dim('○')} account SPA skipped (build: false)`));
487
+ }
488
+ const specDir = `${SPEC_ASSET_DIR}/`;
489
+ const hasSchemaRegistry = result.files.some((f) => f.path === `${specDir}schema-registry.json`);
490
+ if (hasSchemaRegistry) {
491
+ console.log(pc.gray(` ${pc.green('●')} CMS schema registry`));
492
+ }
493
+ const hasOpenAPI = result.files.some((f) => f.path === `${specDir}openapi.json`);
494
+ if (hasOpenAPI) {
495
+ console.log(pc.gray(` ${pc.green('●')} OpenAPI specification`));
496
+ }
497
+ // Show timing breakdown
498
+ if (result.meta.timings) {
499
+ const t = result.meta.timings;
500
+ const migrationCmd = t.commands.find((c) => c.description.includes('migration'));
501
+ const parts = [];
502
+ parts.push(`parse ${(t.parseMs / 1000).toFixed(1)}s`);
503
+ parts.push(`generate ${(t.generateMs / 1000).toFixed(1)}s`);
504
+ if (migrationCmd)
505
+ parts.push(`migrations ${(migrationCmd.ms / 1000).toFixed(1)}s`);
506
+ if (spaBuilds.length > 0) {
507
+ const spaTotal = spaBuilds.reduce((sum, s) => sum + s.ms, 0);
508
+ parts.push(`SPAs ${(spaTotal / 1000).toFixed(1)}s`);
509
+ }
510
+ console.log(pc.dim(` ⏱ ${parts.join(' → ')}`));
511
+ }
512
+ // Display warnings if any
513
+ if (result.warnings && result.warnings.length > 0) {
514
+ console.log(pc.yellow('\n⚠ Compilation warnings:'));
515
+ for (const warning of result.warnings) {
516
+ console.log(pc.yellow(` • ${warning}`));
517
+ }
518
+ console.log();
519
+ }
520
+ const quickbackStateDir = await resolveQuickbackStateDir(projectRoot, outputDir);
521
+ const shouldRouteStateArtifactsToQuickback = Boolean(quickbackStateDir);
522
+ const { runtimeFiles, stateFiles } = partitionGeneratedFiles(result.files);
523
+ spinner.start('Writing output...');
524
+ // AUTHORED-TREE files (`quickback/features/*/.quickback/` typed helpers +
525
+ // `quickback/tsconfig.json`) anchor to the PROJECT ROOT — the authored
526
+ // tree lives there even when `build.outputDir` nests the generated
527
+ // runtime tree, and writing them under outputDir would create a phantom
528
+ // `<outputDir>/quickback/`. Only split them out in the standard layout
529
+ // (quickback/ state dir resolved); in the legacy no-quickback-dir
530
+ // fallback, behavior is unchanged (they ride along with result.files).
531
+ const isAuthoredTreeFile = (f) => f.path.startsWith('quickback/');
532
+ const authoredTreeFiles = shouldRouteStateArtifactsToQuickback
533
+ ? runtimeFiles.filter(isAuthoredTreeFile)
534
+ : [];
535
+ const filesToWrite = shouldRouteStateArtifactsToQuickback
536
+ ? runtimeFiles.filter((f) => !isAuthoredTreeFile(f))
537
+ : result.files;
538
+ // src/ is hermetic — every file there is generated. Archive the
539
+ // existing tree, then wipe it before writing the fresh manifest.
540
+ // This is the only way to make removed features, renamed handlers,
541
+ // and obsolete SPA bundles actually disappear from the output;
542
+ // additive merge writes leave them as orphans. The archive at
543
+ // quickback/.archives/src-<ISO>/ is the recovery path if a generator
544
+ // regression silently stops emitting something.
545
+ const archiveDir = quickbackStateDir
546
+ ? join(quickbackStateDir, '.archives')
547
+ : join(outputDir, 'quickback', '.archives');
548
+ const prepareResult = await prepareGeneratedDir(outputDir, 'src', filesToWrite.map((f) => f.path), {
549
+ archiveDir,
550
+ archiveKeep: 3,
551
+ });
552
+ if (prepareResult.wiped && prepareResult.archivePath) {
553
+ console.log(pc.gray(` Archived previous src/ → ${pc.cyan(relative(projectRoot, prepareResult.archivePath))}`));
554
+ }
555
+ else if (prepareResult.skipped === 'empty-manifest') {
556
+ console.log(pc.yellow(` ⚠ Skipping src/ wipe — compiler returned no files for src/. Output may contain stale code.`));
557
+ }
558
+ // Write the generated files. src/ is fresh from the wipe above;
559
+ // migration SQL files outside src/ are kept by writeFilesWithMerge
560
+ // itself; package.json is merged.
561
+ await writeFilesWithMerge(outputDir, filesToWrite);
562
+ // ── Local migration generation ──────────────────────────────────────
563
+ // Drizzle runs HERE, against migration state that never left the machine.
564
+ // Ordered after the runtime write on purpose: generation stages into a
565
+ // temp workspace and only commits from `onPrepared`, so a compile that
566
+ // fails before this point leaves the migration tree untouched, and a
567
+ // failure inside it leaves the tree untouched too.
568
+ if (result.migrationPlan) {
569
+ spinner.start('Generating migrations locally...');
570
+ const migrationWarnings = [];
571
+ try {
572
+ // `onPrepared` is always supplied, so the executor returns its result
573
+ // rather than the bare execution summary.
574
+ const commit = await executeClientMigrationPlan({
575
+ projectRoot,
576
+ plan: result.migrationPlan,
577
+ inputs: result.migrationInputs,
578
+ outputRootPath: resolveOutputRootPath(projectRoot, quickbackDir, config.build?.outputDir),
579
+ // Prompt-aware runner: drizzle-kit's create-or-rename resolver needs
580
+ // a TTY and an answer. The default argv runner ignores stdin, and
581
+ // the executor refuses a plan requiring prompt automation without
582
+ // one — every D1 target sets autoCreateRenames.
583
+ runner: createPromptAwareMigrationRunner({
584
+ projectRoot,
585
+ log: verbose ? (message) => console.log(pc.gray(` ${message}`)) : undefined,
586
+ }),
587
+ postprocessors: createMigrationPostprocessors({
588
+ rlsJournalMigration: result.meta?.rlsJournalMigration,
589
+ triggerJournalMigration: result.meta?.triggerJournalMigration,
590
+ warnings: migrationWarnings,
591
+ log: verbose ? (message) => console.log(pc.gray(` ${message}`)) : undefined,
592
+ }),
593
+ onPrepared: (prepared) => commitStagedMigrations(prepared, { projectRoot }),
594
+ });
595
+ if (commit.created.length > 0) {
596
+ spinner.succeed(`Generated ${commit.created.length} migration file(s)`);
597
+ for (const path of commit.created)
598
+ console.log(pc.gray(` ${pc.green('+')} ${path}`));
599
+ }
600
+ else {
601
+ spinner.succeed('Migrations up to date (no schema changes)');
602
+ }
603
+ }
604
+ catch (error) {
605
+ spinner.fail('Local migration generation failed');
606
+ throw error;
607
+ }
608
+ for (const warning of migrationWarnings) {
609
+ console.log(pc.yellow(` ⚠ ${warning}`));
610
+ }
611
+ }
612
+ // Retired paths — the generic form of "the compiler moved a file and the
613
+ // old copy is still on disk". The manifest can only ADD, and the wipe above
614
+ // only covers `src/`, so anything that relocates OUTSIDE `src/` would leave
615
+ // an orphan forever. The compiler resolves the list against its own
616
+ // manifest, so nothing here is a path this compile wrote.
617
+ //
618
+ // Guarded again on our side: never delete something in filesToWrite. Cheap,
619
+ // and it means a compiler bug can't take live output with it.
620
+ const manifestPaths = new Set(filesToWrite.map((f) => f.path));
621
+ const removedRetired = [];
622
+ for (const retired of result.retiredPaths ?? []) {
623
+ if (manifestPaths.has(retired.path))
624
+ continue;
625
+ // Defensive: the path is output-root-relative by contract, but never let
626
+ // a malformed entry escape the output directory.
627
+ const target = resolve(outputDir, retired.path);
628
+ if (!target.startsWith(resolve(outputDir)))
629
+ continue;
630
+ try {
631
+ await fs.unlink(target);
632
+ removedRetired.push(`${retired.path} (${retired.reason})`);
633
+ }
634
+ catch {
635
+ // Already gone — the steady state after the first post-move compile.
636
+ }
637
+ }
638
+ if (removedRetired.length > 0) {
639
+ console.log(pc.gray(` ${pc.green('●')} Removed ${removedRetired.length} retired file(s):`));
640
+ for (const line of removedRetired)
641
+ console.log(pc.gray(` ${line}`));
642
+ }
643
+ if (authoredTreeFiles.length > 0) {
644
+ // The @quickback/compiler typing twin (quickback/.quickback/compiler/)
645
+ // is compiler-owned and fully regenerated on every compile — wipe the
646
+ // directory before the write so a declaration file dropped from the
647
+ // bundle can't linger (the authored tsconfig includes ./**/*, so a
648
+ // stale .d.ts would still enter the tsc program).
649
+ if (authoredTreeFiles.some((f) => f.path.startsWith('quickback/.quickback/compiler/'))) {
650
+ await fs.rm(resolve(projectRoot, 'quickback', '.quickback', 'compiler'), {
651
+ recursive: true,
652
+ force: true,
653
+ });
654
+ }
655
+ // Typed helpers + tsconfig for the authored tree — anchored to the
656
+ // project root (see isAuthoredTreeFile above).
657
+ await writeFilesWithMerge(projectRoot, authoredTreeFiles);
658
+ console.log(pc.gray(` Wrote ${authoredTreeFiles.length} authored-tree typing file(s) → ${pc.cyan('quickback/')} (editor types for actions)`));
659
+ }
660
+ if (quickbackStateDir && stateFiles.length > 0) {
661
+ // Only files the compiler was actually shown may be removed. The upload
662
+ // is deliberately partial (newest snapshot per meta dir), so anything
663
+ // absent from `drizzleMeta` is invisible to the compiler and its absence
664
+ // from the response means nothing. See prepareStateArtifacts (#201).
665
+ const stateResult = await prepareStateArtifacts(quickbackStateDir, stateFiles, {
666
+ uploadedPaths: Object.keys(drizzleMeta || {}),
667
+ });
668
+ await writeFilesWithMerge(quickbackStateDir, stateFiles);
669
+ spinner.succeed(`Output written to ${pc.cyan(outputDir)} (state artifacts synced to ${pc.cyan(quickbackStateDir)})`);
670
+ if (stateResult.removed.length > 0) {
671
+ console.log(pc.gray(` Removed ${stateResult.removed.length} superseded migration file(s); ` +
672
+ `${stateResult.preserved} preserved` +
673
+ (stateResult.archivePath
674
+ ? ` (previous tree archived to ${pc.cyan(stateResult.archivePath)})`
675
+ : '')));
676
+ }
677
+ }
678
+ else {
679
+ spinner.succeed(`Output written to ${pc.cyan(outputDir)}`);
680
+ }
681
+ // User-supplied static assets — anything under quickback/public/ rides
682
+ // past the compiler verbatim into src/apps/, where the wrangler ASSETS
683
+ // binding already serves it. Compiler stays out of the binary path.
684
+ try {
685
+ const publicResult = await copyPublicAssets({
686
+ projectRoot,
687
+ outputDir,
688
+ manifestPaths: filesToWrite.map((f) => f.path),
689
+ });
690
+ if (publicResult.copied > 0) {
691
+ console.log(pc.gray(` ${pc.green('●')} Copied ${publicResult.copied} static asset(s) from quickback/public/ → src/apps/`));
692
+ }
693
+ }
694
+ catch (error) {
695
+ if (error instanceof PublicAssetCollisionError) {
696
+ spinner.fail('Static asset collision');
697
+ console.error(pc.red(error.message));
698
+ process.exit(1);
699
+ }
700
+ throw error;
701
+ }
702
+ // User-authored source apps — anything under quickback/apps/<name>/
703
+ // rides past the compiler verbatim into src/apps/<name>/, alongside the
704
+ // compiler-emitted SPA shells (cms/, account/). Use this for hand-written
705
+ // companion mini-SPAs (e.g. m/, admin/) that share the worker's ASSETS
706
+ // binding. Static binaries belong in quickback/public/ instead.
707
+ try {
708
+ const appsResult = await copySourceApps({
709
+ projectRoot,
710
+ outputDir,
711
+ manifestPaths: filesToWrite.map((f) => f.path),
712
+ });
713
+ if (appsResult.copied > 0) {
714
+ console.log(pc.gray(` ${pc.green('●')} Copied ${appsResult.copied} source app file(s) from quickback/apps/ → src/apps/`));
715
+ }
716
+ }
717
+ catch (error) {
718
+ if (error instanceof SourceAppCollisionError) {
719
+ spinner.fail('Source app collision');
720
+ console.error(pc.red(error.message));
721
+ process.exit(1);
722
+ }
723
+ throw error;
724
+ }
725
+ // Run post-compile commands from providers
726
+ if (result.commands && result.commands.length > 0) {
727
+ console.log(pc.gray('\nRunning post-compile commands...\n'));
728
+ for (const cmd of result.commands) {
729
+ // Replace {{OUTPUT_DIR}} placeholder with actual path
730
+ const command = cmd.command.replace(/\{\{OUTPUT_DIR\}\}/g, outputDir);
731
+ // Determine working directory based on command's cwd setting
732
+ // 'output' means project root (where compiled code lives)
733
+ const commandCwd = cmd.cwd === 'output' ? outputDir : projectRoot;
734
+ spinner.start(cmd.description);
735
+ try {
736
+ await runCommand(command, { cwd: commandCwd });
737
+ spinner.succeed(cmd.description);
738
+ }
739
+ catch (error) {
740
+ if (cmd.optional) {
741
+ spinner.warn(`${cmd.description} (skipped)`);
742
+ }
743
+ else {
744
+ spinner.fail(cmd.description);
745
+ throw error;
746
+ }
747
+ }
748
+ }
749
+ }
750
+ const syncedSecurityReportFiles = shouldRouteStateArtifactsToQuickback
751
+ ? 0
752
+ : await syncSecurityReportsToQuickback(projectRoot, outputDir, result.files);
753
+ if (syncedSecurityReportFiles > 0) {
754
+ console.log(pc.gray(` Synced ${syncedSecurityReportFiles} security report file(s) to quickback/reports`));
755
+ }
756
+ // Sync schema-driven kitchen-sink block into quickback.config.ts so the
757
+ // user can discover every option Quickback supports without having to
758
+ // read source. The block is owned by Quickback and replaced wholesale
759
+ // on every compile; user-set keys are omitted server-side. To opt out:
760
+ // `quickback build --no-sync-config`.
761
+ if (syncConfig && result.syncedConfig) {
762
+ const syncResult = await syncConfigFile(configPath, result.syncedConfig);
763
+ if (syncResult.changed) {
764
+ const omittedNote = syncResult.omittedKeys.length > 0
765
+ ? ` (you've already set: ${syncResult.omittedKeys.join(', ')})`
766
+ : '';
767
+ const action = syncResult.inserted ? 'Inserted' : 'Refreshed';
768
+ console.log(pc.gray(` ${action} options block in ${pc.cyan(relative(projectRoot, configPath))}${omittedNote}`));
769
+ }
770
+ else if (syncResult.skippedReason) {
771
+ console.log(pc.yellow(` ⚠ Skipped config sync: ${syncResult.skippedReason}`));
772
+ }
773
+ }
774
+ // Print next steps from the exact provider/connection-mode contract.
775
+ // Hyperdrive credentials stay in bindings; DATABASE_URL is never a Worker
776
+ // secret on that lane. Named targets also require explicit Wrangler envs.
777
+ console.log(pc.green('\n✔ Compilation complete!'));
778
+ console.log(`\nGenerated files for: ${pc.cyan(result.meta.features.join(', ') || 'no features')}`);
779
+ console.log('\nNext steps:');
780
+ for (const step of getCompileNextSteps(config)) {
781
+ console.log(pc.gray(` ${step}`));
782
+ }
783
+ }
784
+ catch (error) {
785
+ spinner.fail('Compilation failed');
786
+ if (error instanceof Error) {
787
+ console.error(pc.red('\nError:'), error.message);
788
+ // Check for specific error types
789
+ if (error.message.includes('requires a Pro account')) {
790
+ console.log(pc.yellow('\nThis template requires a Pro account.'));
791
+ console.log('Run: quickback login');
792
+ }
793
+ else if (error.message.includes('fetch')) {
794
+ console.log(pc.yellow('\nCould not connect to the Quickback API.'));
795
+ console.log('Check your internet connection and try again.');
796
+ }
797
+ }
798
+ else {
799
+ console.error(pc.red('\nError:'), error);
800
+ }
801
+ process.exit(1);
802
+ }
803
+ }
804
+ //# sourceMappingURL=build.js.map