zitejs 0.10.0-start.2 → 0.10.0-start.21

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 (188) hide show
  1. package/dist/cjs/auth/actions.d.ts +28 -0
  2. package/dist/cjs/auth/actions.js +93 -0
  3. package/dist/cjs/auth/client.d.ts +357 -0
  4. package/dist/cjs/auth/client.js +66 -0
  5. package/dist/cjs/auth/index.d.ts +2 -249
  6. package/dist/cjs/auth/index.js +11 -108
  7. package/dist/cjs/auth/index.test.js +48 -0
  8. package/dist/cjs/auth/previewClaim.d.ts +7 -0
  9. package/dist/cjs/auth/previewClaim.js +16 -0
  10. package/dist/cjs/auth/profileUpdates.d.ts +9 -0
  11. package/dist/cjs/auth/profileUpdates.js +11 -0
  12. package/dist/cjs/backend/index.d.ts +121 -3
  13. package/dist/cjs/backend/index.test.js +58 -0
  14. package/dist/cjs/bundle/index.d.ts +8 -0
  15. package/dist/cjs/bundle/index.js +9 -8
  16. package/dist/cjs/check/index.d.ts +45 -1
  17. package/dist/cjs/check/index.js +198 -109
  18. package/dist/cjs/check/start/problem.d.ts +11 -0
  19. package/dist/cjs/check/start/problem.js +5 -0
  20. package/dist/cjs/check/start/routeTree.d.ts +9 -0
  21. package/dist/cjs/check/start/routeTree.js +111 -0
  22. package/dist/cjs/check/start/sourceRules.d.ts +8 -0
  23. package/dist/cjs/check/start/sourceRules.js +1159 -0
  24. package/dist/cjs/check/start/tsgo.d.ts +2 -0
  25. package/dist/cjs/check/start/tsgo.js +35 -0
  26. package/dist/cjs/cli.js +1 -1
  27. package/dist/cjs/client/index.d.ts +24 -0
  28. package/dist/cjs/dev/index.js +14 -4
  29. package/dist/cjs/integrations/rules.d.ts +13 -0
  30. package/dist/cjs/integrations/rules.js +31 -0
  31. package/dist/cjs/integrations/rules.test.js +1 -0
  32. package/dist/cjs/internal/appMode.d.ts +3 -0
  33. package/dist/cjs/internal/appMode.js +15 -0
  34. package/dist/cjs/runtime/index.d.ts +64 -25
  35. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  36. package/dist/cjs/runtime/sendEmailParamsTypes.test-d.js +33 -0
  37. package/dist/cjs/start/entries.d.ts +10 -4
  38. package/dist/cjs/start/entries.js +23 -6
  39. package/dist/cjs/steps/index.d.ts +78 -0
  40. package/dist/cjs/steps/index.js +507 -0
  41. package/dist/cjs/steps/index.test.d.ts +1 -0
  42. package/dist/cjs/steps/index.test.js +635 -0
  43. package/dist/cjs/sync/index.js +2 -1
  44. package/dist/cjs/sync/lib.d.ts +10 -3
  45. package/dist/cjs/sync/lib.js +44 -25
  46. package/dist/cjs/sync/lib.test.js +116 -36
  47. package/dist/cjs/types/fields.d.ts +8 -1
  48. package/dist/cjs/types/fields.js +7 -1
  49. package/dist/cjs/types/tables.d.ts +16 -0
  50. package/dist/cjs/upload/index.js +12 -2
  51. package/dist/cjs/upload/index.test.js +39 -0
  52. package/dist/cjs/vite/index.js +8 -3
  53. package/dist/cjs/vite/index.test.js +10 -2
  54. package/dist/esm/auth/actions.d.ts +28 -0
  55. package/dist/esm/auth/actions.js +55 -0
  56. package/dist/esm/auth/client.d.ts +357 -0
  57. package/dist/esm/auth/client.js +62 -0
  58. package/dist/esm/auth/index.d.ts +2 -249
  59. package/dist/esm/auth/index.js +2 -103
  60. package/dist/esm/auth/index.test.js +48 -0
  61. package/dist/esm/auth/previewClaim.d.ts +7 -0
  62. package/dist/esm/auth/previewClaim.js +12 -0
  63. package/dist/esm/auth/profileUpdates.d.ts +9 -0
  64. package/dist/esm/auth/profileUpdates.js +6 -0
  65. package/dist/esm/backend/index.d.ts +121 -3
  66. package/dist/esm/backend/index.test.js +58 -0
  67. package/dist/esm/bundle/index.d.ts +8 -0
  68. package/dist/esm/bundle/index.js +8 -8
  69. package/dist/esm/check/index.d.ts +45 -1
  70. package/dist/esm/check/index.js +198 -113
  71. package/dist/esm/check/start/problem.d.ts +11 -0
  72. package/dist/esm/check/start/problem.js +1 -0
  73. package/dist/esm/check/start/routeTree.d.ts +9 -0
  74. package/dist/esm/check/start/routeTree.js +70 -0
  75. package/dist/esm/check/start/sourceRules.d.ts +8 -0
  76. package/dist/esm/check/start/sourceRules.js +1156 -0
  77. package/dist/esm/check/start/tsgo.d.ts +2 -0
  78. package/dist/esm/check/start/tsgo.js +29 -0
  79. package/dist/esm/cli.js +1 -1
  80. package/dist/esm/client/index.d.ts +24 -0
  81. package/dist/esm/dev/index.js +16 -6
  82. package/dist/esm/integrations/rules.d.ts +13 -0
  83. package/dist/esm/integrations/rules.js +31 -0
  84. package/dist/esm/integrations/rules.test.js +1 -0
  85. package/dist/esm/internal/appMode.d.ts +3 -0
  86. package/dist/esm/internal/appMode.js +10 -0
  87. package/dist/esm/runtime/index.d.ts +64 -25
  88. package/dist/esm/runtime/sendEmailParamsTypes.test-d.d.ts +1 -0
  89. package/dist/esm/runtime/sendEmailParamsTypes.test-d.js +31 -0
  90. package/dist/esm/start/aiUsage.d.ts +23 -0
  91. package/dist/esm/start/aiUsage.js +146 -0
  92. package/dist/esm/start/airtable/arrayFields.d.ts +10 -0
  93. package/dist/esm/start/airtable/arrayFields.js +30 -0
  94. package/dist/esm/start/airtable/dispatch.d.ts +54 -0
  95. package/dist/esm/start/airtable/dispatch.js +483 -0
  96. package/dist/esm/start/airtable/formulas.d.ts +70 -0
  97. package/dist/esm/start/airtable/formulas.js +260 -0
  98. package/dist/esm/start/airtable/index.d.ts +8 -0
  99. package/dist/esm/start/airtable/index.js +54 -0
  100. package/dist/esm/start/authHooks.d.ts +7 -0
  101. package/dist/esm/start/authHooks.js +10 -0
  102. package/dist/esm/start/authHooksModule.d.ts +1 -0
  103. package/dist/esm/start/authHooksModule.js +3 -0
  104. package/dist/esm/start/clientErrorMessage.test.d.ts +1 -0
  105. package/dist/esm/start/clientErrorMessage.test.js +105 -0
  106. package/dist/esm/start/credentials.d.ts +2 -0
  107. package/dist/esm/start/credentials.js +2 -0
  108. package/dist/esm/start/data/baseRunner.d.ts +92 -0
  109. package/dist/esm/start/data/baseRunner.js +83 -0
  110. package/dist/esm/start/data/dispatch.d.ts +16 -0
  111. package/dist/esm/start/data/dispatch.js +198 -0
  112. package/dist/esm/start/data/index.d.ts +15 -0
  113. package/dist/esm/start/data/index.js +58 -0
  114. package/dist/esm/start/data/sqlNameMappings.d.ts +58 -0
  115. package/dist/esm/start/data/sqlNameMappings.js +92 -0
  116. package/dist/esm/start/data/transformations.d.ts +97 -0
  117. package/dist/esm/start/data/transformations.js +262 -0
  118. package/dist/esm/start/data/types.d.ts +91 -0
  119. package/dist/esm/start/data/types.js +14 -0
  120. package/dist/esm/start/describe.d.ts +42 -5
  121. package/dist/esm/start/describe.js +77 -23
  122. package/dist/esm/start/entries.d.ts +10 -4
  123. package/dist/esm/start/entries.js +21 -5
  124. package/dist/esm/start/errors.d.ts +63 -0
  125. package/dist/esm/start/errors.js +146 -0
  126. package/dist/esm/start/errors.test.d.ts +1 -0
  127. package/dist/esm/start/errors.test.js +23 -0
  128. package/dist/esm/start/factories.test-d.d.ts +2 -0
  129. package/dist/esm/start/factories.test-d.js +20 -0
  130. package/dist/esm/start/host.d.ts +2 -2
  131. package/dist/esm/start/index.d.ts +32 -27
  132. package/dist/esm/start/index.js +79 -47
  133. package/dist/esm/start/instance.d.ts +4 -4
  134. package/dist/esm/start/instance.js +54 -11
  135. package/dist/esm/start/outbound.d.ts +11 -0
  136. package/dist/esm/start/outbound.js +400 -0
  137. package/dist/esm/start/previewClaim.d.ts +7 -0
  138. package/dist/esm/start/previewClaim.js +23 -0
  139. package/dist/esm/start/problems.js +1 -1
  140. package/dist/esm/start/quiet.d.ts +2 -0
  141. package/dist/esm/start/quiet.js +27 -0
  142. package/dist/esm/start/redactSecrets.d.ts +15 -0
  143. package/dist/esm/start/redactSecrets.js +154 -0
  144. package/dist/esm/start/redactSecrets.test.d.ts +1 -0
  145. package/dist/esm/start/redactSecrets.test.js +151 -0
  146. package/dist/esm/start/registration.d.ts +13 -0
  147. package/dist/esm/start/registration.js +21 -0
  148. package/dist/esm/start/registrationHash.d.ts +22 -0
  149. package/dist/esm/start/registrationHash.js +470 -0
  150. package/dist/esm/start/router.d.ts +25 -4
  151. package/dist/esm/start/router.js +169 -11
  152. package/dist/esm/start/runLog.d.ts +7 -4
  153. package/dist/esm/start/runLog.js +64 -6
  154. package/dist/esm/start/scope.d.ts +4 -4
  155. package/dist/esm/start/server.d.ts +40 -36
  156. package/dist/esm/start/server.js +322 -49
  157. package/dist/esm/start/steps.d.ts +28 -0
  158. package/dist/esm/start/steps.js +97 -0
  159. package/dist/esm/start/types.d.ts +179 -6
  160. package/dist/esm/start/version.d.ts +1 -0
  161. package/dist/esm/start/version.js +2 -0
  162. package/dist/esm/start/vite.js +91 -14
  163. package/dist/esm/start/worker.d.ts +6 -0
  164. package/dist/esm/start/worker.js +12 -0
  165. package/dist/esm/start/workflow.d.ts +46 -12
  166. package/dist/esm/start/workflow.js +10 -3
  167. package/dist/esm/start/workflow.test-d.js +50 -8
  168. package/dist/esm/start/workflowModules.js +1 -1
  169. package/dist/esm/start/workflowRun.d.ts +26 -8
  170. package/dist/esm/start/workflowRun.js +39 -8
  171. package/dist/esm/steps/index.d.ts +78 -0
  172. package/dist/esm/steps/index.js +502 -0
  173. package/dist/esm/steps/index.test.d.ts +1 -0
  174. package/dist/esm/steps/index.test.js +633 -0
  175. package/dist/esm/sync/index.js +2 -1
  176. package/dist/esm/sync/lib.d.ts +10 -3
  177. package/dist/esm/sync/lib.js +44 -25
  178. package/dist/esm/sync/lib.test.js +116 -36
  179. package/dist/esm/types/fields.d.ts +8 -1
  180. package/dist/esm/types/fields.js +6 -0
  181. package/dist/esm/types/tables.d.ts +16 -0
  182. package/dist/esm/upload/index.js +12 -2
  183. package/dist/esm/upload/index.test.js +39 -0
  184. package/dist/esm/vite/index.js +8 -3
  185. package/dist/esm/vite/index.test.js +10 -2
  186. package/package.json +37 -16
  187. package/dist/cjs/start/problems.d.ts +0 -19
  188. package/dist/cjs/start/problems.js +0 -11
@@ -6,6 +6,8 @@ const requestContext = { user: { id: "u1", email: "a@b.c", roles: [] } };
6
6
  // Direct execute() calls need the step surface the runtime always provides.
7
7
  const stepStub = {
8
8
  run: async (_name, fn) => await fn(),
9
+ sleep: async () => { },
10
+ sleepUntil: async () => { },
9
11
  };
10
12
  afterEach(() => {
11
13
  vi.unstubAllGlobals();
@@ -205,6 +207,62 @@ describe("platform-triggered runs", () => {
205
207
  return params.trigger;
206
208
  },
207
209
  });
210
+ createEndpoint({
211
+ trigger: { table: "orders", on: ["updated"], fields: ["status"] },
212
+ execute: async ({ input, trigger }) => {
213
+ // @ts-expect-error a database change has no cursor API
214
+ trigger?.advance("x");
215
+ const status = input.record?.status;
216
+ return { status, changed: input.changedFields, at: input.event };
217
+ },
218
+ });
219
+ createEndpoint({
220
+ // @ts-expect-error a database trigger names its table, not a connection
221
+ trigger: { table: "orders", on: ["created"], integration: "x" },
222
+ execute: async () => 1,
223
+ });
224
+ createEndpoint({
225
+ trigger: { form: "Intake form", on: ["submitted"] },
226
+ execute: async ({ input, trigger }) => {
227
+ // @ts-expect-error a form submission has no cursor API
228
+ trigger?.advance("x");
229
+ return {
230
+ email: input.answers.Email,
231
+ workEmail: input.answersById["wWorkEmail"],
232
+ id: input.submissionId,
233
+ };
234
+ },
235
+ });
236
+ createEndpoint({
237
+ // @ts-expect-error a form trigger watches submissions only
238
+ trigger: { form: "Intake form", on: ["updated"] },
239
+ execute: async () => 1,
240
+ });
241
+ createEndpoint({
242
+ // @ts-expect-error only created, updated and deleted
243
+ trigger: { table: "orders", on: ["archived"] },
244
+ execute: async () => 1,
245
+ });
246
+ });
247
+ it("hands a database trigger its change without parsing it against the input schema", async () => {
248
+ const endpoint = createEndpoint({
249
+ inputSchema: z.object({ orderId: z.string() }),
250
+ trigger: { table: "orders", on: ["created"] },
251
+ execute: async ({ input }) => input.recordId,
252
+ });
253
+ await expect(endpoint.execute({
254
+ step: stepStub,
255
+ input: {
256
+ event: "created",
257
+ table: "orders",
258
+ recordId: "rec_1",
259
+ record: { id: "rec_1" },
260
+ previous: null,
261
+ changedFields: [],
262
+ },
263
+ context: { user: null },
264
+ trigger: { headers: {}, deliveryId: "db:e1:rec_1" },
265
+ })).resolves.toBe("rec_1");
208
266
  });
209
267
  it("types a trigger's registration exports and checks what subscribe returns", async () => {
210
268
  const subscribe = (async (input) => ({
@@ -20,10 +20,18 @@
20
20
  * "@babel/parser": "^7.26.0"
21
21
  */
22
22
  import * as esbuild from 'esbuild';
23
+ import { type SourceRoot } from '../sourceRoots.js';
23
24
  export declare const UNSUPPORTED_IN_WORKERD: Set<string>;
24
25
  export declare const BASE_BUILD_OPTIONS: esbuild.BuildOptions;
25
26
  export declare function createAliasPlugin(opts: {
26
27
  baseDir?: string;
27
28
  sdkPath?: string;
28
29
  }): esbuild.Plugin;
30
+ export interface EndpointBundleResult {
31
+ bundledEndpoints: Record<string, string>;
32
+ endpointErrors?: Record<string, string>;
33
+ bundledAuthHooks?: string;
34
+ authHooksError?: string;
35
+ }
36
+ export declare function bundleEndpoints(baseDir: string, root: SourceRoot, endpointNames: string[], logLevel: esbuild.LogLevel): Promise<EndpointBundleResult>;
29
37
  export declare function runBundle(): Promise<void>;
@@ -366,7 +366,7 @@ import endpoint from '${entryImport}';
366
366
  globalThis.__endpoint = endpoint;
367
367
  `;
368
368
  }
369
- async function bundleEndpointsImpl(baseDir, root, endpointNames) {
369
+ export async function bundleEndpoints(baseDir, root, endpointNames, logLevel) {
370
370
  const bundledEndpoints = {};
371
371
  const endpointErrors = {};
372
372
  const aliasPlugin = createAliasPlugin({ baseDir });
@@ -403,7 +403,7 @@ async function bundleEndpointsImpl(baseDir, root, endpointNames) {
403
403
  resolveDir: `${baseDir}/src`,
404
404
  loader: 'ts',
405
405
  },
406
- logLevel: 'warning',
406
+ logLevel,
407
407
  plugins: [aliasPlugin],
408
408
  });
409
409
  if (result.warnings && result.warnings.length > 0) {
@@ -473,7 +473,7 @@ globalThis.__endpoint = endpoint;
473
473
  resolveDir: `${baseDir}/src`,
474
474
  loader: 'ts',
475
475
  },
476
- logLevel: 'warning',
476
+ logLevel,
477
477
  plugins: [aliasPlugin],
478
478
  });
479
479
  if (result.outputFiles && result.outputFiles.length > 0) {
@@ -500,14 +500,12 @@ globalThis.__endpoint = endpoint;
500
500
  }
501
501
  }
502
502
  }
503
- const output = JSON.stringify({
503
+ return {
504
504
  bundledEndpoints,
505
505
  endpointErrors: Object.keys(endpointErrors).length > 0 ? endpointErrors : undefined,
506
506
  bundledAuthHooks,
507
507
  authHooksError,
508
- });
509
- fs.writeFileSync('/tmp/zitejs-bundle-result.json', output);
510
- console.log(output);
508
+ };
511
509
  }
512
510
  async function bundleOneOffScriptImpl(scriptPath, sdkPath) {
513
511
  const rawScript = fs.readFileSync(scriptPath, 'utf-8');
@@ -625,5 +623,7 @@ export async function runBundle() {
625
623
  endpointNames = listEndpointNames(root, baseDir);
626
624
  }
627
625
  // Even with no endpoints, zite.auth.ts may still need bundling.
628
- return bundleEndpointsImpl(baseDir, root, endpointNames);
626
+ const output = JSON.stringify(await bundleEndpoints(baseDir, root, endpointNames, 'warning'));
627
+ fs.writeFileSync('/tmp/zitejs-bundle-result.json', output);
628
+ console.log(output);
629
629
  }
@@ -1 +1,45 @@
1
- export declare function runCheck(): Promise<void>;
1
+ import { type Problem } from './start/problem.js';
2
+ /**
3
+ * A step's result. `unchecked` is why it couldn't answer at all (killed, out of
4
+ * memory, a tool missing): nothing for the app to fix, so it carries no output.
5
+ */
6
+ type StepResult = {
7
+ ok: boolean;
8
+ output?: string;
9
+ unchecked?: string;
10
+ };
11
+ type Step = {
12
+ name: string;
13
+ } & StepResult;
14
+ /** One app's check, as `--json` reports it. */
15
+ export type AppCheck = {
16
+ path: string;
17
+ runtime: 'classic' | 'start';
18
+ /** False when something in it needs fixing. */
19
+ ok: boolean;
20
+ /** Set when a step couldn't run to an answer, so the app wasn't fully checked. */
21
+ unchecked?: true;
22
+ steps: Step[];
23
+ problems: Problem[];
24
+ };
25
+ /**
26
+ * While `--json` checks, stdout carries only the report: app code that logs as
27
+ * it's described in-process goes to stderr instead.
28
+ */
29
+ export declare const withStdoutOnStderr: <T>(run: () => Promise<T>) => Promise<T>;
30
+ /** Prints as it goes, or with `--json` stays quiet and reports everything at the end. */
31
+ export declare class Reporter {
32
+ private readonly json;
33
+ readonly apps: AppCheck[];
34
+ constructor(json: boolean);
35
+ app(path: string, runtime: AppCheck['runtime'], heading: boolean): AppCheck;
36
+ step(app: AppCheck, name: string, result: StepResult): boolean;
37
+ problems(app: AppCheck, problems: Problem[]): void;
38
+ }
39
+ /**
40
+ * Runs a tool to its answer, or says why it gave none: a kill (a signal, or an
41
+ * exit of 128 and up with nothing printed) is a sandbox limit, not the app's.
42
+ */
43
+ export declare function runTool(file: string, args: string[], cwd: string): StepResult;
44
+ export declare function runCheck(args?: string[]): Promise<void>;
45
+ export {};
@@ -1,7 +1,10 @@
1
- import { execFileSync } from 'child_process';
2
- import { existsSync } from 'fs';
3
- import { join } from 'path';
4
- import { listEndpointNames, listSourceDirs } from '../sourceRoots.js';
1
+ import { execFileSync, spawnSync } from 'child_process';
2
+ import * as esbuild from 'esbuild';
3
+ import { existsSync, readdirSync, readFileSync } from 'fs';
4
+ import { join, relative, resolve } from 'path';
5
+ import { bundleEndpoints } from '../bundle/index.js';
6
+ import { listEndpointNames, listSourceDirs, sourceRootOf } from '../sourceRoots.js';
7
+ import { formatProblem } from './start/problem.js';
5
8
  /**
6
9
  * An argument array, not a command string, so no shell is involved.
7
10
  *
@@ -25,28 +28,9 @@ function run(file, args, cwd) {
25
28
  return { ok: false, output: (e.stderr ?? '') + (e.stdout ?? '') };
26
29
  }
27
30
  }
28
- /**
29
- * `zitejs bundle` reports per-endpoint failures inside its JSON payload and
30
- * still exits 0, so a non-empty `endpointErrors` is the only signal there is.
31
- */
32
- function bundleFailures(output) {
33
- const line = output
34
- .trim()
35
- .split('\n')
36
- .reverse()
37
- .find(l => l.startsWith('{'));
38
- if (!line)
39
- return ['bundle produced no result'];
40
- let result;
41
- try {
42
- result = JSON.parse(line);
43
- }
44
- catch {
45
- return [`could not parse bundle output: ${line.slice(0, 200)}`];
46
- }
31
+ async function bundleFailures(root, appPath, endpointNames) {
32
+ const result = await bundleEndpoints(resolve(appPath), root, endpointNames, 'silent').finally(() => esbuild.stop());
47
33
  const failures = [];
48
- if (result.error)
49
- failures.push(result.error);
50
34
  for (const [name, err] of Object.entries(result.endpointErrors ?? {})) {
51
35
  failures.push(`${name}: ${err}`);
52
36
  }
@@ -57,41 +41,183 @@ function bundleFailures(output) {
57
41
  }
58
42
  const indent = (output) => output.trim().split('\n').map(l => ` ${l}`).join('\n');
59
43
  /**
60
- * A Start app: `vite build` first, since it regenerates the route tree tsc
61
- * reads, then tsc, then describe, which reports what the platform's build
62
- * refuses, read the same way.
44
+ * While `--json` checks, stdout carries only the report: app code that logs as
45
+ * it's described in-process goes to stderr instead.
63
46
  */
64
- async function checkStartApp(appPath) {
65
- process.stdout.write(' vite build ... ');
66
- const vite = run('npx', ['vite', 'build'], appPath);
67
- console.log(vite.ok ? '✓' : '✗');
68
- if (!vite.ok) {
69
- console.log(indent(vite.output));
47
+ export const withStdoutOnStderr = async (run) => {
48
+ const write = process.stdout.write;
49
+ process.stdout.write = process.stderr.write.bind(process.stderr);
50
+ try {
51
+ return await run();
52
+ }
53
+ finally {
54
+ process.stdout.write = write;
55
+ }
56
+ };
57
+ /** Prints as it goes, or with `--json` stays quiet and reports everything at the end. */
58
+ export class Reporter {
59
+ json;
60
+ apps = [];
61
+ constructor(json) {
62
+ this.json = json;
63
+ }
64
+ app(path, runtime, heading) {
65
+ const app = { path, runtime, ok: true, steps: [], problems: [] };
66
+ this.apps.push(app);
67
+ if (heading && !this.json)
68
+ console.log(`\n── ${path} ──`);
69
+ return app;
70
+ }
71
+ step(app, name, result) {
72
+ if (result.unchecked) {
73
+ app.steps.push({ name, ok: false, unchecked: result.unchecked });
74
+ app.unchecked = true;
75
+ if (!this.json)
76
+ console.log(` ${name} ... unchecked: ${result.unchecked}`);
77
+ return false;
78
+ }
79
+ const output = result.output?.trim();
80
+ app.steps.push({ name, ok: result.ok, ...(output && !result.ok && { output }) });
81
+ if (!result.ok)
82
+ app.ok = false;
83
+ if (!this.json) {
84
+ console.log(` ${name} ... ${result.ok ? '✓' : '✗'}`);
85
+ if (!result.ok && output)
86
+ console.log(indent(output));
87
+ }
88
+ return result.ok;
89
+ }
90
+ problems(app, problems) {
91
+ app.problems.push(...problems);
92
+ if (problems.some(p => p.severity === 'error'))
93
+ app.ok = false;
94
+ if (!this.json && problems.length)
95
+ console.log(problems.map(p => ` ${formatProblem(p)}`).join('\n'));
96
+ }
97
+ }
98
+ const SKIPPED_DIRS = new Set(['node_modules', 'dist', '.output', '.tanstack', '.wrangler']);
99
+ /** The app's own source, by app-relative path. */
100
+ function readAppSources(appPath) {
101
+ const sources = {};
102
+ const visit = (dir) => {
103
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
104
+ if (SKIPPED_DIRS.has(entry.name))
105
+ continue;
106
+ const full = join(dir, entry.name);
107
+ if (entry.isDirectory())
108
+ visit(full);
109
+ else if (/\.[cm]?[jt]sx?$/.test(entry.name))
110
+ sources[relative(appPath, full)] = readFileSync(full, 'utf-8');
111
+ }
112
+ };
113
+ const src = join(appPath, 'src');
114
+ if (existsSync(src))
115
+ visit(src);
116
+ return sources;
117
+ }
118
+ const isInternalApp = (appPath) => {
119
+ try {
120
+ return JSON.parse(readFileSync(join(appPath, 'zite.config.json'), 'utf-8'))?.accessMode === 'internal';
121
+ }
122
+ catch {
70
123
  return false;
71
124
  }
72
- process.stdout.write(' tsc --noEmit ... ');
73
- // --pretty for `file:line:col - error` lines, the shape the platform re-roots.
74
- const tsc = run('npx', ['tsc', '--noEmit', '--pretty', '-p', 'tsconfig.app.json'], appPath);
75
- console.log(tsc.ok ? '✓' : '✗');
76
- if (!tsc.ok)
77
- console.log(indent(tsc.output));
78
- process.stdout.write(' describe ... ');
125
+ };
126
+ /**
127
+ * tsgo's Node launcher rethrows its compiler's kill: an exit of 1 with Node's
128
+ * `Error: Command failed: …/tsgo …` dump, `signal: 'SIGKILL'` included. Matched
129
+ * at line start, since `--pretty` quotes source lines that could hold either.
130
+ */
131
+ const launcherKill = (output) => /^Error: Command failed: \S*tsgo\b/m.test(output) ? output.match(/\bsignal: '(SIG[A-Z]+)'/)?.[1] : undefined;
132
+ /**
133
+ * Runs a tool to its answer, or says why it gave none: a kill (a signal, or an
134
+ * exit of 128 and up with nothing printed) is a sandbox limit, not the app's.
135
+ */
136
+ export function runTool(file, args, cwd) {
137
+ const result = spawnSync(file, args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
138
+ const output = (result.stderr ?? '') + (result.stdout ?? '');
139
+ if (result.error)
140
+ return { ok: false, unchecked: `couldn't run: ${result.error.message}` };
141
+ const signal = result.signal ?? (result.status !== 0 ? launcherKill(output) : undefined);
142
+ if (signal)
143
+ return { ok: false, unchecked: `killed by ${signal}` };
144
+ if (result.status !== null && result.status >= 128 && !output.trim()) {
145
+ return { ok: false, unchecked: `exited ${result.status} with no output` };
146
+ }
147
+ return { ok: result.status === 0, output };
148
+ }
149
+ const isMissingModule = (err) => err?.code === 'MODULE_NOT_FOUND';
150
+ /**
151
+ * A Start app, in about a second: its route tree regenerated as `vite build`
152
+ * writes it, a tsgo typecheck, which reads that tree, then the source rules.
153
+ * Neither a build nor describe: the platform's build is where access is decided
154
+ * and enforced, and these only say early what it would refuse.
155
+ */
156
+ async function checkStartApp(reporter, app, appPath) {
157
+ const { regenerateRouteTree } = await import('./start/routeTree.js');
158
+ let routeTree = { ok: true };
79
159
  try {
80
- const { describeBuiltApp } = await import('../start/describeBuilt.js');
81
- const { descriptionProblems } = await import('../start/problems.js');
82
- const problems = descriptionProblems((await describeBuiltApp(appPath)));
83
- console.log(problems.length ? '✗' : '✓');
84
- if (problems.length)
85
- console.log(problems.map(p => ` ${p}`).join('\n'));
86
- return tsc.ok && problems.length === 0;
160
+ await regenerateRouteTree(appPath);
87
161
  }
88
162
  catch (err) {
89
- console.log('✗');
90
- console.log(` ${err instanceof Error ? err.message : String(err)}`);
91
- return false;
163
+ const message = err instanceof Error ? err.message : String(err);
164
+ routeTree = isMissingModule(err)
165
+ ? { ok: false, unchecked: `the app's TanStack Start isn't installed: ${message}` }
166
+ : { ok: false, output: message };
167
+ }
168
+ if (reporter.step(app, 'route tree', routeTree)) {
169
+ const { findTsgo } = await import('./start/tsgo.js');
170
+ const tsgo = findTsgo(appPath);
171
+ reporter.step(app, 'tsgo --noEmit', !existsSync(join(appPath, 'tsconfig.app.json'))
172
+ ? { ok: false, output: `no ${join(appPath, 'tsconfig.app.json')}` }
173
+ : !tsgo
174
+ ? { ok: false, unchecked: "tsgo isn't installed (npm install -g @typescript/native-preview)" }
175
+ : // --pretty for `file:line:col - error` lines, the shape the platform re-roots. Two checkers, not
176
+ // four, hold half the type graph: a large app fits the sandbox's memory.
177
+ runTool(process.execPath, [tsgo, '--noEmit', '--pretty', '-p', 'tsconfig.app.json', '--checkers', '2'], appPath));
178
+ }
179
+ const { sourceProblems } = await import('./start/sourceRules.js');
180
+ const root = sourceRootOf(appPath);
181
+ let hints;
182
+ try {
183
+ hints = sourceProblems(readAppSources(appPath), {
184
+ internal: isInternalApp(appPath),
185
+ kind: root && { apps: 'app', automations: 'automation' }[root],
186
+ });
187
+ }
188
+ catch (err) {
189
+ // A rule's own bug is nothing for the app to fix, and mustn't cost the report the steps before it.
190
+ reporter.step(app, 'source', { ok: false, unchecked: `source rules failed: ${err instanceof Error ? err.message : String(err)}` });
191
+ return;
192
+ }
193
+ reporter.step(app, 'source', { ok: !hints.some(p => p.severity === 'error') });
194
+ reporter.problems(app, hints);
195
+ }
196
+ async function checkClassicApp(reporter, app, root, appPath) {
197
+ // Only tsconfig.app.json compiles anything. The app's tsconfig.json is a
198
+ // solution-style config — `"files": []` plus a reference — so
199
+ // `tsc --noEmit -p tsconfig.json` type-checks zero files and exits 0. It
200
+ // used to be the fallback, which meant an app missing tsconfig.app.json
201
+ // reported a passing typecheck it never ran.
202
+ const tsconfigAppPath = join(appPath, 'tsconfig.app.json');
203
+ reporter.step(app, 'tsc --noEmit', existsSync(tsconfigAppPath)
204
+ ? run('npx', ['tsc', '--noEmit', '-p', tsconfigAppPath], '.')
205
+ : { ok: false, output: `no ${tsconfigAppPath}` });
206
+ // Endpoints never reach vite — they are bundled separately for the lambda,
207
+ // against a different resolver. tsc and vite both pass on an endpoint whose
208
+ // `zitejs/*` alias has no generated file behind it; only the bundler knows.
209
+ const endpointNames = listEndpointNames(root, appPath);
210
+ if (endpointNames.length > 0) {
211
+ const failures = await bundleFailures(root, appPath, endpointNames);
212
+ reporter.step(app, 'bundle endpoints', { ok: failures.length === 0, output: failures.join('\n') });
213
+ }
214
+ if (existsSync(join(appPath, 'vite.config.ts'))) {
215
+ reporter.step(app, 'vite build', run('npx', ['vite', 'build'], appPath));
92
216
  }
93
217
  }
94
- export async function runCheck() {
218
+ export async function runCheck(args = process.argv.slice(3)) {
219
+ const json = args.includes('--json');
220
+ const reporter = new Reporter(json);
95
221
  const { isStartAppDir } = await import('../start/entries.js');
96
222
  // Run inside a Start app, its own zitejs checks just that app: the workspace
97
223
  // root's is a classic release that doesn't know Start.
@@ -101,72 +227,31 @@ export async function runCheck() {
101
227
  console.error('No apps or automations found under apps/ or automations/.');
102
228
  process.exit(1);
103
229
  }
104
- let allPassed = inStartApp ? await checkStartApp('.') : true;
105
- for (const { root, dir: app, path: appPath } of appDirs) {
106
- console.log(`\n── ${appPath} ──`);
107
- if (isStartAppDir(appPath)) {
108
- if (!(await checkStartApp(appPath)))
109
- allPassed = false;
110
- continue;
111
- }
112
- // Only tsconfig.app.json compiles anything. The app's tsconfig.json is a
113
- // solution-style config — `"files": []` plus a reference — so
114
- // `tsc --noEmit -p tsconfig.json` type-checks zero files and exits 0. It
115
- // used to be the fallback, which meant an app missing tsconfig.app.json
116
- // reported a passing typecheck it never ran.
117
- const tsconfigAppPath = join(appPath, 'tsconfig.app.json');
118
- if (!existsSync(tsconfigAppPath)) {
119
- console.log(` tsc --noEmit ... ✗ (no ${tsconfigAppPath})`);
120
- allPassed = false;
121
- }
122
- else {
123
- process.stdout.write(' tsc --noEmit ... ');
124
- const tsc = run('npx', ['tsc', '--noEmit', '-p', tsconfigAppPath], '.');
125
- if (tsc.ok) {
126
- console.log('✓');
230
+ const checkAll = async () => {
231
+ if (inStartApp)
232
+ await checkStartApp(reporter, reporter.app('.', 'start', false), '.');
233
+ for (const { root, path: appPath } of appDirs) {
234
+ if (isStartAppDir(appPath)) {
235
+ await checkStartApp(reporter, reporter.app(appPath, 'start', true), appPath);
127
236
  }
128
237
  else {
129
- console.log('✗');
130
- console.log(tsc.output.trim().split('\n').map(l => ` ${l}`).join('\n'));
131
- allPassed = false;
132
- }
133
- }
134
- // Endpoints never reach vite — they are bundled separately for the lambda,
135
- // against a different resolver. tsc and vite both pass on an endpoint whose
136
- // `zitejs/*` alias has no generated file behind it; only the bundler knows.
137
- if (listEndpointNames(root, appPath).length > 0) {
138
- process.stdout.write(' bundle endpoints ... ');
139
- const bundle = run('npx', ['zitejs', 'bundle', '--app', app], '.');
140
- const failures = bundle.ok ? bundleFailures(bundle.output) : [bundle.output];
141
- if (failures.length === 0) {
142
- console.log('✓');
143
- }
144
- else {
145
- console.log('✗');
146
- console.log(failures.map(l => ` ${l}`).join('\n'));
147
- allPassed = false;
148
- }
149
- }
150
- const viteConfig = join(appPath, 'vite.config.ts');
151
- if (existsSync(viteConfig)) {
152
- process.stdout.write(' vite build ... ');
153
- const vite = run('npx', ['vite', 'build'], appPath);
154
- if (vite.ok) {
155
- console.log('✓');
156
- }
157
- else {
158
- console.log('✗');
159
- console.log(vite.output.trim().split('\n').map(l => ` ${l}`).join('\n'));
160
- allPassed = false;
238
+ await checkClassicApp(reporter, reporter.app(appPath, 'classic', true), root, appPath);
161
239
  }
162
240
  }
163
- }
164
- console.log('');
165
- if (allPassed) {
166
- console.log('All apps pass.');
241
+ };
242
+ await (json ? withStdoutOnStderr(checkAll) : checkAll());
243
+ const failed = reporter.apps.some(app => !app.ok);
244
+ const unchecked = reporter.apps.some(app => app.unchecked);
245
+ if (json) {
246
+ process.stdout.write(`${JSON.stringify({ ok: !failed && !unchecked, ...(unchecked && { unchecked: true }), apps: reporter.apps })}\n`);
167
247
  }
168
248
  else {
169
- console.log('Some apps failed.');
170
- process.exit(1);
249
+ console.log('');
250
+ console.log(failed ? 'Some apps failed.' : unchecked ? 'Some apps were not fully checked.' : 'All apps pass.');
171
251
  }
252
+ // 3: nothing to fix, but not everything ran.
253
+ if (failed)
254
+ process.exit(1);
255
+ if (unchecked)
256
+ process.exit(3);
172
257
  }
@@ -0,0 +1,11 @@
1
+ export type Severity = "error" | "warning";
2
+ /** One finding of `zitejs check`, named by its rule. Errors fail the check; warnings only report. */
3
+ export type Problem = {
4
+ rule: string;
5
+ severity: Severity;
6
+ /** App-relative. */
7
+ file?: string;
8
+ line?: number;
9
+ message: string;
10
+ };
11
+ export declare const formatProblem: ({ rule, severity, file, line, message }: Problem) => string;
@@ -0,0 +1 @@
1
+ export const formatProblem = ({ rule, severity, file, line, message }) => `${severity} ${rule}${file ? ` ${file}${line ? `:${line}` : ""}` : ""}: ${message}`;
@@ -0,0 +1,9 @@
1
+ export declare const ENTRY_EXTENSIONS: string[];
2
+ /** Start's footer (start-plugin-core route-tree-footer), which types the router and start instance for `@tanstack/react-start`. */
3
+ export declare const startRouteTreeFooter: (generatedRouteTree: string, routerFile: string, startFile: string | undefined) => string[];
4
+ /**
5
+ * Regenerates the route tree with the router generator the app's own
6
+ * `@tanstack/react-start` builds with, configured as zitejs's Start plugin
7
+ * configures it, so the file is the one `vite build` writes, byte for byte.
8
+ */
9
+ export declare function regenerateRouteTree(appDir: string): Promise<void>;
@@ -0,0 +1,70 @@
1
+ // `src/routeTree.gen.ts` as `vite build` writes it, without vite: tsgo types
2
+ // each `createFileRoute` from it, and only the generator may write it.
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { START_INSTANCE_ENTRY } from "../../start/entries.js";
8
+ // As Start resolves its entries (start-plugin-core resolve-entries).
9
+ export const ENTRY_EXTENSIONS = [".ts", ".js", ".mts", ".mjs", ".tsx", ".jsx"];
10
+ const resolveEntry = (srcDirectory, name) => {
11
+ const base = path.resolve(srcDirectory, name);
12
+ if (existsSync(base) && statSync(base).isFile())
13
+ return base;
14
+ return ENTRY_EXTENSIONS.map((extension) => base + extension).find((file) => existsSync(file));
15
+ };
16
+ const importPath = (generatedRouteTree, file) => {
17
+ let relative = path.relative(path.dirname(generatedRouteTree), file);
18
+ if (!relative.startsWith("."))
19
+ relative = `./${relative}`;
20
+ return relative.split(path.sep).join("/");
21
+ };
22
+ /** Start's footer (start-plugin-core route-tree-footer), which types the router and start instance for `@tanstack/react-start`. */
23
+ export const startRouteTreeFooter = (generatedRouteTree, routerFile, startFile) => {
24
+ const blocks = [
25
+ `import type { getRouter } from '${importPath(generatedRouteTree, routerFile)}'`,
26
+ startFile
27
+ ? `import type { startInstance } from '${importPath(generatedRouteTree, startFile)}'`
28
+ : "import type { createStart } from '@tanstack/react-start'",
29
+ "declare module '@tanstack/react-start' {\n interface Register {\n ssr: true\n router: Awaited<ReturnType<typeof getRouter>>",
30
+ ...(startFile ? [" config: Awaited<ReturnType<typeof startInstance.getOptions>>"] : []),
31
+ " }\n}",
32
+ ];
33
+ return [blocks.join("\n")];
34
+ };
35
+ /** A package's ESM entry, resolved from `fromFile` as Node would. */
36
+ const importPackage = async (fromFile, name) => {
37
+ const manifest = createRequire(fromFile).resolve(`${name}/package.json`);
38
+ const { exports, module, main } = JSON.parse(readFileSync(manifest, "utf-8"));
39
+ const root = exports?.["."] ?? exports;
40
+ const entry = root?.import?.default ?? root?.import ?? root?.default ?? module ?? main ?? "index.js";
41
+ return import(pathToFileURL(path.join(path.dirname(manifest), entry)).href);
42
+ };
43
+ /**
44
+ * Regenerates the route tree with the router generator the app's own
45
+ * `@tanstack/react-start` builds with, configured as zitejs's Start plugin
46
+ * configures it, so the file is the one `vite build` writes, byte for byte.
47
+ */
48
+ export async function regenerateRouteTree(appDir) {
49
+ const root = path.resolve(appDir);
50
+ const srcDirectory = path.join(root, "src");
51
+ const routesDirectory = path.join(srcDirectory, "routes");
52
+ if (!existsSync(routesDirectory))
53
+ return;
54
+ const generatedRouteTree = path.join(srcDirectory, "routeTree.gen.ts");
55
+ const routerFile = resolveEntry(srcDirectory, "router");
56
+ if (!routerFile)
57
+ throw new Error("src/router.tsx is missing: Start reads the app's router from it");
58
+ // zite() points Start's entry at the generated start instance, relative to src/.
59
+ const startFile = resolveEntry(srcDirectory, path.join("..", START_INSTANCE_ENTRY.replace(/\.ts$/, "")));
60
+ const startManifest = createRequire(path.join(root, "package.json")).resolve("@tanstack/react-start/package.json");
61
+ const coreManifest = createRequire(startManifest).resolve("@tanstack/start-plugin-core/package.json");
62
+ const { getConfig, Generator } = (await importPackage(coreManifest, "@tanstack/router-generator"));
63
+ const footer = startRouteTreeFooter(generatedRouteTree, routerFile, startFile);
64
+ const config = {
65
+ ...getConfig({ routesDirectory, generatedRouteTree }, root),
66
+ target: "react",
67
+ routeTreeFileFooter: () => footer,
68
+ };
69
+ await new Generator({ config, root }).run();
70
+ }
@@ -0,0 +1,8 @@
1
+ import type { Problem } from "./problem.js";
2
+ /** Which a Start project is, when the check can tell from where it sits. */
3
+ export type SourceKind = "app" | "automation";
4
+ /** Every source hint for one Start app, given its files by app-relative path. */
5
+ export declare function sourceProblems(sources: Record<string, string>, { internal, kind }?: {
6
+ internal?: boolean;
7
+ kind?: SourceKind;
8
+ }): Problem[];