@cloudflare/think 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,6 +27,35 @@ export class MyAgent extends Think<Env> {
27
27
 
28
28
  That's it. Think handles the WebSocket chat protocol, message persistence, the agentic loop, message sanitization, stream resumption, client tool support, and workspace file tools. Connect from the browser with `useAgentChat` from `@cloudflare/ai-chat`.
29
29
 
30
+ ## Think framework
31
+
32
+ The Think Vite plugin can generate the Worker entry, stable Durable Object
33
+ exports, friendly route helpers, and inferred Worker config from an `agents/`
34
+ directory:
35
+
36
+ ```ts
37
+ import { cloudflare } from "@cloudflare/vite-plugin";
38
+ import { think } from "@cloudflare/think/vite";
39
+ import { defineConfig } from "vite";
40
+
41
+ export default defineConfig({
42
+ plugins: [think(), cloudflare()]
43
+ });
44
+ ```
45
+
46
+ Use `main: "virtual:think/entry"` in framework projects. Top-level agents under
47
+ `agents/` get generated Durable Object bindings and migrations; nested
48
+ `agents/*/agents/*` entries are facet exports for `ctx.exports` and do not need
49
+ production Wrangler bindings or migrations. Apps with auth or custom routing can
50
+ add `src/server.ts`; the generated entry still wraps it and injects
51
+ `think.router` for manifest-aware routing.
52
+
53
+ The framework supports one sub-agent layer today. If you need nested sub-agents,
54
+ please reach out with your use case so we can design that model deliberately.
55
+
56
+ See the full Think framework docs in `docs/think/index.md` for conventions,
57
+ custom server handlers, diagnostics, and route-prefix configuration.
58
+
30
59
  ## Messengers
31
60
 
32
61
  Think can own messenger ingress directly. Declare providers with
@@ -296,12 +325,15 @@ Script execution requires a Worker Loader binding:
296
325
  | Export | Description |
297
326
  | --------------------------------------- | ------------------------------------------------------------- |
298
327
  | `@cloudflare/think` | `Think`, `Session`, `Workspace` — main class + re-exports |
328
+ | `@cloudflare/think/framework` | Framework manifest discovery and declarative `agent()` helper |
329
+ | `@cloudflare/think/server-entry` | Framework Worker entry helpers for custom server handlers |
299
330
  | `@cloudflare/think/messengers` | Messenger contracts, Chat SDK bridge, state agent, delivery |
300
331
  | `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
301
332
  | `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
302
333
  | `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
303
334
  | `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
304
335
  | `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
336
+ | `@cloudflare/think/vite` | Think Vite plugin and generated Worker config helpers |
305
337
 
306
338
  ## Think
307
339
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,650 @@
1
+ #!/usr/bin/env node
2
+ import { a as readWranglerConfig, c as createThinkWorkerConfig, h as discoverThinkApp, i as readProjectFiles, m as summarizeThinkManifest, n as createThinkProject, o as resolveThinkManifest, t as applyUserBindingNames } from "../project-D1o1-3dN.js";
3
+ import { n as isThinkGeneratedFile, t as generateThinkTypes } from "../types-codegen-B6c5KpYH.js";
4
+ import { access, mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import yargs from "yargs";
7
+ import { hideBin } from "yargs/helpers";
8
+ import { spawn } from "node:child_process";
9
+ import { initCommand, looksLikeThinkApp } from "create-think";
10
+ //#region src/cli/init.ts
11
+ const VITE_CONFIG_FILES = [
12
+ "vite.config.ts",
13
+ "vite.config.mts",
14
+ "vite.config.js",
15
+ "vite.config.mjs"
16
+ ];
17
+ /**
18
+ * `think init` has two modes:
19
+ *
20
+ * - New project: when a `--template` is given, or when the command is run
21
+ * outside an existing npm project. Delegates to `create-think`, which fetches
22
+ * a complete starter template (no framework dependency required at runtime).
23
+ * - Augment in place: when run inside an existing npm project with no
24
+ * `--template`. Adds Think framework files (agent, Vite/Wrangler config,
25
+ * generated types) and merges dependencies into the current project.
26
+ */
27
+ async function initCommand$1(options) {
28
+ const baseRoot = path.resolve(options.root ?? process.cwd());
29
+ const insideExistingProject = !options.directory && await fileExists(path.join(baseRoot, "package.json"));
30
+ if (Boolean(options.template) || !insideExistingProject) {
31
+ await initCommand(options);
32
+ return;
33
+ }
34
+ await augmentExistingProject(baseRoot, options);
35
+ }
36
+ async function augmentExistingProject(root, options) {
37
+ const projectName = packageName(options.name ?? path.basename(root));
38
+ if (await looksLikeThinkApp(root)) {
39
+ console.log(["This already looks like a Think app.", "Try `think inspect` to review the manifest or `think types` to refresh generated declarations."].join("\n"));
40
+ return;
41
+ }
42
+ const migrationReason = await unsafeMigrationReason(root);
43
+ if (migrationReason) throw new Error([
44
+ "This directory already has Vite or Wrangler configuration, so `think init` will not migrate it automatically yet.",
45
+ migrationReason,
46
+ "Start a new Think app with `npm create think`, or add `@cloudflare/think/vite` and Think framework files manually."
47
+ ].join("\n"));
48
+ const plan = await createInitPlan({
49
+ root,
50
+ projectName,
51
+ routePrefix: options.routePrefix
52
+ });
53
+ const skipped = await existingPlanFiles(plan);
54
+ if (options.dryRun) {
55
+ printDryRun(plan, skipped, options.install ?? true);
56
+ return;
57
+ }
58
+ await writePlannedFiles(plan, skipped);
59
+ if (options.install ?? true) await (options.installRunner ?? runNpmInstall)(root);
60
+ printSuccess(plan, skipped, options.install ?? true);
61
+ }
62
+ async function createInitPlan(options) {
63
+ const sourceFiles = {
64
+ "agents/assistant/agent.ts": agentSource(),
65
+ "agents/assistant/skills/project-helper/SKILL.md": starterSkillSource()
66
+ };
67
+ const manifest = discoverThinkApp({
68
+ root: options.root,
69
+ routePrefix: options.routePrefix,
70
+ files: sourceFiles
71
+ });
72
+ const workerConfig = createThinkWorkerConfig(manifest, {
73
+ name: options.projectName,
74
+ routePrefix: options.routePrefix
75
+ });
76
+ workerConfig.ai = { binding: "AI" };
77
+ workerConfig.worker_loaders = [{ binding: "LOADER" }];
78
+ const typeFiles = generateThinkTypes(manifest, {
79
+ files: sourceFiles,
80
+ typesFile: "think.d.ts"
81
+ });
82
+ return {
83
+ root: options.root,
84
+ projectName: options.projectName,
85
+ packageJsonPath: "package.json",
86
+ files: [
87
+ {
88
+ path: "package.json",
89
+ content: packageJsonSource(options.projectName),
90
+ merge: "package-json"
91
+ },
92
+ {
93
+ path: "vite.config.ts",
94
+ content: viteConfig(options.routePrefix)
95
+ },
96
+ {
97
+ path: "wrangler.jsonc",
98
+ content: `${JSON.stringify(workerConfig, null, 2)}\n`
99
+ },
100
+ {
101
+ path: "tsconfig.json",
102
+ content: tsconfig()
103
+ },
104
+ {
105
+ path: "agents/assistant/agent.ts",
106
+ content: sourceFiles["agents/assistant/agent.ts"]
107
+ },
108
+ {
109
+ path: "agents/assistant/skills/project-helper/SKILL.md",
110
+ content: sourceFiles["agents/assistant/skills/project-helper/SKILL.md"]
111
+ },
112
+ ...typeFiles
113
+ ]
114
+ };
115
+ }
116
+ async function existingPlanFiles(plan) {
117
+ const existing = /* @__PURE__ */ new Set();
118
+ for (const file of plan.files) {
119
+ if (file.merge === "package-json") continue;
120
+ if (await fileExists(path.join(plan.root, file.path))) existing.add(file.path);
121
+ }
122
+ return existing;
123
+ }
124
+ async function writePlannedFiles(plan, skip) {
125
+ await mkdir(plan.root, { recursive: true });
126
+ for (const file of plan.files) {
127
+ if (skip.has(file.path)) continue;
128
+ const absolute = path.join(plan.root, file.path);
129
+ await mkdir(path.dirname(absolute), { recursive: true });
130
+ await writeFile(absolute, file.merge === "package-json" ? await mergePackageJson(absolute, file.content) : file.content, "utf8");
131
+ }
132
+ }
133
+ async function mergePackageJson(absolutePath, generatedContent) {
134
+ const generated = JSON.parse(generatedContent);
135
+ const existingSource = await readTextIfExists$1(absolutePath);
136
+ if (!existingSource) return generatedContent;
137
+ const existing = JSON.parse(existingSource);
138
+ return `${JSON.stringify(mergePackageJsonData(existing, generated), null, 2)}\n`;
139
+ }
140
+ function mergePackageJsonData(existing, generated) {
141
+ return {
142
+ ...generated,
143
+ ...existing,
144
+ type: generated.type ?? existing.type,
145
+ scripts: {
146
+ ...generated.scripts,
147
+ ...existing.scripts
148
+ },
149
+ dependencies: {
150
+ ...generated.dependencies,
151
+ ...existing.dependencies
152
+ },
153
+ devDependencies: {
154
+ ...generated.devDependencies,
155
+ ...existing.devDependencies
156
+ }
157
+ };
158
+ }
159
+ async function unsafeMigrationReason(root) {
160
+ for (const file of [
161
+ ...VITE_CONFIG_FILES,
162
+ "wrangler.jsonc",
163
+ "wrangler.json",
164
+ "wrangler.toml"
165
+ ]) if (await fileExists(path.join(root, file))) return `Found existing ${file}.`;
166
+ return null;
167
+ }
168
+ function printDryRun(plan, skipped, install) {
169
+ const lines = ["Think init would add to the current project:", ...plan.files.filter((file) => !skipped.has(file.path)).map((file) => `- ${file.path}`)];
170
+ if (skipped.size > 0) lines.push("", "Would keep your existing files (left unchanged):", ...[...skipped].map((file) => `- ${file}`));
171
+ lines.push(install ? "Would run: npm install" : "Would skip dependency install.");
172
+ console.log(lines.join("\n"));
173
+ }
174
+ function printSuccess(plan, skipped, install) {
175
+ const lines = [`Added Think to ${plan.root}.`, install ? "Installed npm dependencies." : "Skipped npm install."];
176
+ if (skipped.size > 0) lines.push("", "Kept your existing files (not overwritten):", ...[...skipped].map((file) => `- ${file}`), "Reconcile them with Think's expected setup if the app does not build.");
177
+ lines.push("", "Next steps:", "- Edit agents/assistant/agent.ts to customize the model, prompt, skills, and schedules", "- npm run dev", "- npm run types", "- npm run deploy");
178
+ console.log(lines.join("\n"));
179
+ }
180
+ async function runNpmInstall(root) {
181
+ await new Promise((resolve, reject) => {
182
+ const child = spawn("npm", ["install"], {
183
+ cwd: root,
184
+ stdio: "inherit",
185
+ shell: process.platform === "win32"
186
+ });
187
+ child.on("error", reject);
188
+ child.on("exit", (code) => {
189
+ if (code === 0) {
190
+ resolve();
191
+ return;
192
+ }
193
+ reject(/* @__PURE__ */ new Error(`npm install failed with exit code ${code ?? "unknown"}.`));
194
+ });
195
+ });
196
+ }
197
+ const FRAMEWORK_DEPENDENCIES = {
198
+ "@cloudflare/think": "latest",
199
+ agents: "latest"
200
+ };
201
+ const THIRD_PARTY_DEPENDENCIES = {
202
+ ai: "^6.0.196",
203
+ "workers-ai-provider": "^3.1.14"
204
+ };
205
+ const THIRD_PARTY_DEV_DEPENDENCIES = {
206
+ "@cloudflare/vite-plugin": "^1.39.2",
207
+ "@cloudflare/workers-types": "^4.20260604.1",
208
+ typescript: "^6.0.3",
209
+ vite: "^8.0.16",
210
+ wrangler: "^4.97.0"
211
+ };
212
+ function packageJsonSource(projectName) {
213
+ return `${JSON.stringify({
214
+ name: projectName,
215
+ private: true,
216
+ type: "module",
217
+ scripts: {
218
+ dev: "vite dev",
219
+ build: "vite build",
220
+ deploy: "vite build && wrangler deploy",
221
+ types: "think types --all"
222
+ },
223
+ dependencies: {
224
+ ...FRAMEWORK_DEPENDENCIES,
225
+ ...THIRD_PARTY_DEPENDENCIES
226
+ },
227
+ devDependencies: { ...THIRD_PARTY_DEV_DEPENDENCIES }
228
+ }, null, 2)}\n`;
229
+ }
230
+ function viteConfig(routePrefix) {
231
+ return [
232
+ `import { cloudflare } from "@cloudflare/vite-plugin";`,
233
+ `import { think } from "@cloudflare/think/vite";`,
234
+ `import { defineConfig } from "vite";`,
235
+ "",
236
+ "export default defineConfig({",
237
+ ` plugins: [think${routePrefix ? `({ routePrefix: ${JSON.stringify(routePrefix)} })` : "()"}, cloudflare()]`,
238
+ "});",
239
+ ""
240
+ ].join("\n");
241
+ }
242
+ function agentSource() {
243
+ return [
244
+ `import { Think, skills } from "@cloudflare/think";`,
245
+ `import { createWorkersAI } from "workers-ai-provider";`,
246
+ `import bundledSkills from "agents:skills";`,
247
+ "",
248
+ "type Env = Cloudflare.Env & {",
249
+ " AI: Ai;",
250
+ " LOADER: WorkerLoader;",
251
+ "};",
252
+ "",
253
+ "export class Assistant extends Think<Env> {",
254
+ " override getModel() {",
255
+ " return createWorkersAI({ binding: this.env.AI })(",
256
+ " \"@cf/moonshotai/kimi-k2.6\",",
257
+ " { sessionAffinity: this.sessionAffinity }",
258
+ " );",
259
+ " }",
260
+ "",
261
+ " override getSystemPrompt() {",
262
+ " return \"You are a helpful assistant. Keep answers clear, practical, and concise.\";",
263
+ " }",
264
+ "",
265
+ " override getSkills() {",
266
+ " return [bundledSkills];",
267
+ " }",
268
+ "",
269
+ " override getSkillScriptRunner() {",
270
+ " return skills.runner({",
271
+ " loader: this.env.LOADER,",
272
+ " workspaceInstance: this.workspace",
273
+ " });",
274
+ " }",
275
+ "}",
276
+ ""
277
+ ].join("\n");
278
+ }
279
+ function starterSkillSource() {
280
+ return [
281
+ "---",
282
+ "name: project-helper",
283
+ "description: Help users plan and explain small project changes. Use when the user asks for implementation guidance, debugging steps, or a concise project plan.",
284
+ "---",
285
+ "",
286
+ "# Project Helper",
287
+ "",
288
+ "Use this skill to give practical, action-oriented project help.",
289
+ "",
290
+ "## Instructions",
291
+ "",
292
+ "1. Restate the user's goal in one sentence.",
293
+ "2. Identify the smallest useful next step.",
294
+ "3. Call out any important risk or missing context.",
295
+ "4. Keep the answer concise and easy to act on.",
296
+ ""
297
+ ].join("\n");
298
+ }
299
+ function tsconfig() {
300
+ return `${JSON.stringify({
301
+ compilerOptions: {
302
+ target: "ES2021",
303
+ module: "ES2022",
304
+ moduleResolution: "bundler",
305
+ strict: true,
306
+ verbatimModuleSyntax: true,
307
+ types: ["@cloudflare/workers-types"]
308
+ },
309
+ include: [
310
+ "agents",
311
+ "think.d.ts",
312
+ "vite.config.ts"
313
+ ]
314
+ }, null, 2)}\n`;
315
+ }
316
+ function packageName(name) {
317
+ return name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").replace(/^[._]+/, "") || "think-agent";
318
+ }
319
+ async function readTextIfExists$1(file) {
320
+ try {
321
+ return await readFile(file, "utf8");
322
+ } catch (error) {
323
+ if (isMissingFileError$1(error)) return null;
324
+ throw error;
325
+ }
326
+ }
327
+ async function fileExists(file) {
328
+ try {
329
+ await access(file);
330
+ return true;
331
+ } catch (error) {
332
+ if (isMissingFileError$1(error)) return false;
333
+ throw error;
334
+ }
335
+ }
336
+ function isMissingFileError$1(error) {
337
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
338
+ }
339
+ //#endregion
340
+ //#region src/cli/inspect.ts
341
+ async function inspectCommand(options) {
342
+ const root = path.resolve(options.root ?? process.cwd());
343
+ const project = await createThinkProject({
344
+ routePrefix: options.routePrefix,
345
+ allowNonVirtualMain: options.allowNonVirtualMain
346
+ }, root);
347
+ if (options.json) {
348
+ console.log(JSON.stringify({
349
+ root,
350
+ manifest: project.manifest,
351
+ workerConfig: project.workerConfig,
352
+ diagnostics: project.diagnostics,
353
+ wranglerConfig: {
354
+ path: project.wranglerConfig.path,
355
+ parsed: Boolean(project.wranglerConfig.config),
356
+ error: project.wranglerConfig.error
357
+ }
358
+ }, null, 2));
359
+ return;
360
+ }
361
+ const lines = [
362
+ "Think inspect",
363
+ `Root: ${root}`,
364
+ "",
365
+ ...summarizeThinkManifest(project.manifest),
366
+ "",
367
+ `Route prefix: ${project.manifest.routePrefix}`,
368
+ `App entry: ${project.manifest.appEntrypoint ?? "none"}`,
369
+ `Wrangler config: ${project.wranglerConfig.path ?? "not found"}`,
370
+ "",
371
+ "Features:",
372
+ ...formatFeatures(project.manifest),
373
+ "",
374
+ "Route surfaces:",
375
+ ...formatRouteSurfaces(project.manifest.routeSurfaces),
376
+ "",
377
+ "Schedules:",
378
+ ...formatNamedFacts(project.manifest.schedules),
379
+ "",
380
+ "Messengers:",
381
+ ...formatNamedFacts(project.manifest.messengers),
382
+ "",
383
+ "Tools:",
384
+ ...formatNamedFacts(project.manifest.tools),
385
+ "",
386
+ "Platform requirements:",
387
+ ...formatPlatformRequirements(project.manifest),
388
+ "",
389
+ "Expected top-level Durable Objects:",
390
+ ...formatBindings(project.manifest.bindings),
391
+ "",
392
+ "Diagnostics:",
393
+ ...formatDiagnostics(project.diagnostics)
394
+ ];
395
+ if (project.wranglerConfig.error) lines.push("", `[warning] ${project.wranglerConfig.error}`);
396
+ console.log(lines.join("\n"));
397
+ }
398
+ function formatBindings(bindings) {
399
+ if (bindings.length === 0) return ["- none"];
400
+ return bindings.map((binding) => `- ${binding.name} -> class ${binding.className}`);
401
+ }
402
+ function formatFeatures(manifest) {
403
+ if (manifest.features.length === 0) return ["- none"];
404
+ return manifest.agents.flatMap((agent) => {
405
+ if (agent.features.length === 0 && agent.env.length === 0) return [];
406
+ return [`- ${agent.id}: ${[agent.features.length ? `features ${agent.features.join(", ")}` : null, agent.env.length ? `env ${agent.env.join(", ")}` : null].filter(Boolean).join(" | ") || "none"}`];
407
+ });
408
+ }
409
+ function formatRouteSurfaces(surfaces) {
410
+ if (surfaces.length === 0) return ["- none"];
411
+ return surfaces.map((surface) => `- ${surface.kind} ${surface.id}: ${surface.pattern}${surface.requiredRunWorkerFirst ? " | requires run_worker_first" : ""}`);
412
+ }
413
+ function formatNamedFacts(facts) {
414
+ if (facts.length === 0) return ["- none"];
415
+ return facts.map((fact) => `- ${fact.id}${fact.agent ? ` | agent ${fact.agent}` : ""}${fact.sourcePath ? ` | ${fact.sourcePath}` : ""}`);
416
+ }
417
+ function formatPlatformRequirements(manifest) {
418
+ if (manifest.platformRequirements.length === 0) return ["- none"];
419
+ return manifest.platformRequirements.map((requirement) => `- ${requirement.kind} ${requirement.binding}${requirement.agent ? ` | agent ${requirement.agent}` : ""} | ${requirement.reason}`);
420
+ }
421
+ function formatDiagnostics(diagnostics) {
422
+ if (diagnostics.length === 0) return ["- none"];
423
+ return diagnostics.map((diagnostic) => `- ${severityLabel(diagnostic.severity)} [${diagnostic.code}] ${diagnostic.message}`);
424
+ }
425
+ function severityLabel(severity) {
426
+ return severity.toUpperCase();
427
+ }
428
+ //#endregion
429
+ //#region src/cli/types.ts
430
+ async function typesCommand(options) {
431
+ const root = path.resolve(options.root ?? process.cwd());
432
+ const typesFile = normalizePath(options.typesFile ?? "think.d.ts");
433
+ const wranglerEnvFile = normalizePath(options.wranglerEnvFile ?? "env.d.ts");
434
+ const files = await readProjectFiles(root, "agents");
435
+ const manifest = await resolveThinkManifest({
436
+ files,
437
+ routePrefix: options.routePrefix
438
+ }, root);
439
+ const wranglerConfig = await readWranglerConfig(root);
440
+ if (wranglerConfig.config) applyUserBindingNames(manifest, wranglerConfig.config);
441
+ if (options.all && !options.dryRun && !options.check) await runWranglerTypes(root, wranglerEnvFile, options.wranglerArgs ?? []);
442
+ const generated = generateThinkTypes(manifest, {
443
+ files,
444
+ typesFile
445
+ });
446
+ if (options.dryRun) {
447
+ console.log(["Think types would update:", ...generated.map((file) => `- ${file.path}`)].join("\n"));
448
+ return;
449
+ }
450
+ if (options.check) {
451
+ const stale = await findStaleFiles(root, generated);
452
+ if (stale.length > 0) throw new Error([
453
+ "Think generated types are out of date.",
454
+ "Run `think types` to update:",
455
+ ...stale.map((file) => `- ${file}`)
456
+ ].join("\n"));
457
+ console.log("Think generated types are up to date.");
458
+ return;
459
+ }
460
+ for (const file of generated) await writeGeneratedFile(root, file);
461
+ console.log(["Generated Think types:", ...generated.map((file) => `- ${file.path}`)].join("\n"));
462
+ }
463
+ async function findStaleFiles(root, files) {
464
+ const stale = [];
465
+ for (const file of files) {
466
+ const expected = await expectedFileContent(root, file);
467
+ if (await readTextIfExists(path.join(root, file.path)) !== expected) stale.push(file.path);
468
+ }
469
+ return stale;
470
+ }
471
+ async function writeGeneratedFile(root, file) {
472
+ const absolute = path.join(root, file.path);
473
+ const expected = await expectedFileContent(root, file);
474
+ await mkdir(path.dirname(absolute), { recursive: true });
475
+ await writeFile(absolute, expected, "utf8");
476
+ }
477
+ async function expectedFileContent(root, file) {
478
+ const current = await readTextIfExists(path.join(root, file.path));
479
+ if (current && !isThinkGeneratedFile(current)) throw new Error(`${file.path} already exists and is not Think-generated; pass a different output path or replace it with a Think-generated file.`);
480
+ return file.content;
481
+ }
482
+ async function readTextIfExists(file) {
483
+ try {
484
+ return await readFile(file, "utf8");
485
+ } catch (error) {
486
+ if (isMissingFileError(error)) return null;
487
+ throw error;
488
+ }
489
+ }
490
+ async function runWranglerTypes(root, envFile, passthroughArgs) {
491
+ const command = await resolveWranglerCommand(root);
492
+ const args = [
493
+ "types",
494
+ envFile,
495
+ ...defaultWranglerTypeArgs(passthroughArgs),
496
+ ...passthroughArgs
497
+ ];
498
+ await new Promise((resolve, reject) => {
499
+ const child = spawn(command, args, {
500
+ cwd: root,
501
+ stdio: "inherit"
502
+ });
503
+ child.on("error", (error) => {
504
+ reject(/* @__PURE__ */ new Error(`Could not run Wrangler to generate platform types. Install wrangler in this project, or run \`think types\` without --all to generate only Think declarations.\n\n${error.message}`));
505
+ });
506
+ child.on("exit", (code) => {
507
+ if (code === 0) {
508
+ resolve();
509
+ return;
510
+ }
511
+ reject(/* @__PURE__ */ new Error(`Wrangler type generation failed with exit code ${code ?? "unknown"}. Fix the Wrangler error above, or run \`think types\` without --all if you intentionally want only Think declarations.`));
512
+ });
513
+ });
514
+ }
515
+ function defaultWranglerTypeArgs(args) {
516
+ return args.some((arg) => arg === "--include-runtime" || arg.startsWith("--include-runtime=")) ? [] : ["--include-runtime", "false"];
517
+ }
518
+ async function resolveWranglerCommand(root) {
519
+ const executable = process.platform === "win32" ? "wrangler.cmd" : "wrangler";
520
+ const local = path.join(root, "node_modules", ".bin", executable);
521
+ try {
522
+ await access(local);
523
+ return local;
524
+ } catch {
525
+ return executable;
526
+ }
527
+ }
528
+ function normalizePath(file) {
529
+ return file.replace(/\\/g, "/").replace(/^\.?\//, "");
530
+ }
531
+ function isMissingFileError(error) {
532
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
533
+ }
534
+ //#endregion
535
+ //#region src/cli/create.ts
536
+ function createCli(argv = process.argv) {
537
+ return yargs(hideBin(argv)).parserConfiguration({ "populate--": true }).scriptName("think").usage("$0 <command> [options]").command("init [directory]", "Scaffold a new Think app from a starter template, or add Think to the current project", (cmd) => cmd.positional("directory", {
538
+ type: "string",
539
+ describe: "Target directory to initialize. Omit to choose interactively."
540
+ }).option("root", {
541
+ type: "string",
542
+ describe: "Base directory for initialization",
543
+ default: process.cwd()
544
+ }).option("name", {
545
+ type: "string",
546
+ describe: "Package and Worker name for the generated app"
547
+ }).option("template", {
548
+ type: "string",
549
+ describe: "Starter template to scaffold (default: basic)"
550
+ }).option("ref", {
551
+ type: "string",
552
+ describe: "Git ref to fetch remote templates from"
553
+ }).option("route-prefix", {
554
+ type: "string",
555
+ describe: "Think route prefix when adding Think to an existing project"
556
+ }).option("yes", {
557
+ alias: "y",
558
+ type: "boolean",
559
+ describe: "Use defaults and skip prompts",
560
+ default: false
561
+ }).option("install", {
562
+ type: "boolean",
563
+ describe: "Run npm install after writing files",
564
+ default: true
565
+ }).option("dry-run", {
566
+ type: "boolean",
567
+ describe: "Print files that would be written without writing them",
568
+ default: false
569
+ }), async (args) => {
570
+ await initCommand$1({
571
+ root: args.root,
572
+ directory: args.directory,
573
+ name: args.name,
574
+ template: args.template,
575
+ ref: args.ref,
576
+ routePrefix: args.routePrefix,
577
+ yes: args.yes,
578
+ install: args.install,
579
+ dryRun: args.dryRun
580
+ });
581
+ }).command("inspect", "Inspect the Think app manifest, routing, bindings, and diagnostics", (cmd) => cmd.option("root", {
582
+ type: "string",
583
+ describe: "Project root to inspect",
584
+ default: process.cwd()
585
+ }).option("json", {
586
+ type: "boolean",
587
+ describe: "Print machine-readable JSON output",
588
+ default: false
589
+ }).option("route-prefix", {
590
+ type: "string",
591
+ describe: "Override the Think route prefix"
592
+ }).option("allow-non-virtual-main", {
593
+ type: "boolean",
594
+ describe: "Do not report non-virtual Wrangler main as an error during inspection",
595
+ default: false
596
+ }), async (args) => {
597
+ await inspectCommand({
598
+ root: args.root,
599
+ json: args.json,
600
+ routePrefix: args.routePrefix,
601
+ allowNonVirtualMain: args.allowNonVirtualMain
602
+ });
603
+ }).command("types", "Generate Think TypeScript declarations", (cmd) => cmd.option("root", {
604
+ type: "string",
605
+ describe: "Project root to generate types for",
606
+ default: process.cwd()
607
+ }).option("types-file", {
608
+ type: "string",
609
+ describe: "Think declaration file to generate",
610
+ default: "think.d.ts"
611
+ }).option("all", {
612
+ type: "boolean",
613
+ describe: "Also run Wrangler type generation before Think typegen",
614
+ default: false
615
+ }).option("wrangler-env-file", {
616
+ type: "string",
617
+ describe: "Wrangler env declaration file to generate with --all",
618
+ default: "env.d.ts"
619
+ }).option("route-prefix", {
620
+ type: "string",
621
+ describe: "Override the Think route prefix"
622
+ }).option("dry-run", {
623
+ type: "boolean",
624
+ describe: "Print files that would be written without writing them",
625
+ default: false
626
+ }).option("check", {
627
+ type: "boolean",
628
+ describe: "Check generated Think types without modifying files",
629
+ default: false
630
+ }), async (args) => {
631
+ await typesCommand({
632
+ root: args.root,
633
+ typesFile: args.typesFile,
634
+ wranglerEnvFile: args.wranglerEnvFile,
635
+ routePrefix: args.routePrefix,
636
+ all: args.all,
637
+ dryRun: args.dryRun,
638
+ check: args.check,
639
+ wranglerArgs: Array.isArray(args["--"]) ? args["--"].map(String) : []
640
+ });
641
+ }).demandCommand(1, "Please provide a command").strict().help();
642
+ }
643
+ //#endregion
644
+ //#region src/cli/index.ts
645
+ console.warn("The `think` CLI is part of the experimental @cloudflare/think framework layer and may change or be removed in any release.");
646
+ createCli().parse();
647
+ //#endregion
648
+ export {};
649
+
650
+ //# sourceMappingURL=index.js.map