Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/components/GitHubCode.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
---
import { z } from "astro:schema";
import { Code } from "@astrojs/starlight/components";
import TypeScriptExample from "./TypeScriptExample.astro";
import type { ComponentProps } from "astro/types";

type Props = z.infer<typeof props>;

Expand All @@ -15,15 +17,17 @@ const props = z
.transform((val) => val.split("-").map(Number))
.optional(),
tag: z.string().optional(),
code: z.custom<ComponentProps<typeof Code>>().optional(),
})
.strict()
.refine(
(val) => {
return !(val.lines && val.tag);
},
{ message: "Lines and tag are mutually exclusive filters." },
);

const { repo, commit, file, lang, lines, tag } = props.parse(Astro.props);
const { repo, commit, file, lang, lines, tag, code } = props.parse(Astro.props);

const res = await fetch(
`https://gh-code.developers.cloudflare.com/${repo}/${commit}/${file}`,
Expand Down Expand Up @@ -64,6 +68,10 @@ if (lines) {
contentLines = contentLines.filter(
(line) => !/<[/]?docs-tag name=".*">/.test(line),
);

const Wrapper = lang === "ts" ? TypeScriptExample : Fragment;
---

<Code code={contentLines.join("\n")} lang={lang} />
<Wrapper>
<Code {...code} code={contentLines.join("\n")} lang={lang} />
</Wrapper>
48 changes: 14 additions & 34 deletions src/components/TypeScriptExample.astro
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,20 @@ import tsBlankSpace from "ts-blank-space";
import { format } from "prettier";
import { parse } from "node-html-parser";
import { Code, Tabs, TabItem } from "@astrojs/starlight/components";
import type { ComponentProps } from "astro/types";

type Props = z.infer<typeof props>;
type Props = z.input<typeof props>;

const props = z
.object({
filename: z.string().optional(),
tabsWrapper: z.boolean().default(true),
playground: z.boolean().default(false),
code: z.custom<ComponentProps<typeof Code>>().optional(),
})
.or(
z.object({
filename: z.object({
js: z.string(),
ts: z.string(),
}),
tabsWrapper: z.boolean().default(true),
playground: z.boolean().default(false),
}),
);

const { filename, tabsWrapper, playground } = props.parse(Astro.props);
.strict();

let jsTitle, tsTitle;
const { filename, playground, code } = props.parse(Astro.props);

if (filename) {
if (typeof filename === "object") {
jsTitle = filename.js;
tsTitle = filename.ts;
} else {
jsTitle = filename.replace(".ts", ".js");
tsTitle = filename;
}
}
const slot = await Astro.slots.render("default");

const html = parse(slot);
Expand All @@ -49,31 +30,30 @@ if (!copy) {
);
}

let code = copy.attributes["data-code"];
let raw = copy.attributes["data-code"];

if (!code) {
if (!raw) {
throw new Error(
`[TypeScriptExample] Unable to find data-code attribute on copy button.`,
);
}

code = code.replace(/\u007f/g, "\n");

const js = await format(tsBlankSpace(code), { parser: "babel", useTabs: true });
raw = raw.replace(/\u007f/g, "\n");

const TabsWrapper = tabsWrapper ? Tabs : Fragment;
const js = await format(tsBlankSpace(raw), { parser: "babel", useTabs: true });
---

<TabsWrapper syncKey="workersExamples">
<Tabs syncKey="workersExamples">
<TabItem label="JavaScript" icon="seti:javascript">
<Code
{...code}
lang="js"
code={js}
title={jsTitle}
title={filename?.replace(".ts", ".js")}
meta={playground ? "playground" : undefined}
/>
</TabItem>
<TabItem label="TypeScript" icon="seti:typescript">
<Code lang="ts" code={code} title={tsTitle} />
<Code {...code} lang="ts" code={raw} title={filename} />
</TabItem>
</TabsWrapper>
</Tabs>
10 changes: 5 additions & 5 deletions src/content/docs/agents/examples/using-ai-models.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Modern [reasoning models](https://platform.openai.com/docs/guides/reasoning) or

Instead of buffering the entire response, or risking the client disconecting, you can stream the response back to the client by using the [WebSocket API](/agents/examples/websockets/).

<TypeScriptExample file="src/index.ts">
<TypeScriptExample filename="src/index.ts">

```ts
import { Agent } from "agents-sdk"
Expand Down Expand Up @@ -85,7 +85,7 @@ You can use [any of the models available in Workers AI](/workers-ai/models/) wit

Workers AI supports streaming responses out-of-the-box by setting `stream: true`, and we strongly recommend using them to avoid buffering and delaying responses, especially for larger models or reasoning models that require more time to generate a response.

<TypeScriptExample file="src/index.ts">
<TypeScriptExample filename="src/index.ts">

```ts
import { Agent } from "agents-sdk"
Expand Down Expand Up @@ -135,7 +135,7 @@ Model routing allows you to route requests to different AI models based on wheth

:::

<TypeScriptExample file="src/index.ts">
<TypeScriptExample filename="src/index.ts">

```ts
import { Agent } from "agents-sdk"
Expand Down Expand Up @@ -189,7 +189,7 @@ To use the AI SDK, install the `ai` package and use it within your Agent. The ex
npm install ai @ai-sdk/openai
```

<TypeScriptExample file="src/index.ts">
<TypeScriptExample filename="src/index.ts">

```ts
import { Agent } from "agents-sdk"
Expand All @@ -216,7 +216,7 @@ Agents can call models across any service, including those that support the Open

Agents can stream responses back over HTTP using Server Sent Events (SSE) from within an `onRequest` handler, or by using the native [WebSockets](/agents/examples/websockets/) API in your Agent to responses back to a client, which is especially useful for larger models that can take over 30+ seconds to reply.

<TypeScriptExample file="src/index.ts">
<TypeScriptExample filename="src/index.ts">

```ts
import { Agent } from "agents-sdk"
Expand Down
52 changes: 0 additions & 52 deletions src/content/docs/style-guide/components/code.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -100,55 +100,3 @@ export default {
};
```
````

## TypeScript examples

The `TypeScriptExample` component uses [`ts-blank-space`](https://github.com/bloomberg/ts-blank-space) to remove TypeScript-specific syntax from your example and provide a JavaScript tab. This reduces maintenance burden by only having a single example to maintain.

:::note
Some TypeScript syntax influences runtime behaviour, and cannot be stripped.

Please refer to the [Unsupported Syntax](https://github.com/bloomberg/ts-blank-space?tab=readme-ov-file#unsupported-syntax) section of the project's README.
:::

### Input

* `filename` `string | { js: string, ts: string }` (optional)
* If a single TypeScript filename is passed, this will be used for JavaScript but with a `.js` file extension.
* `<TypeScriptExample filename="example.ts">`
* To specify different filenames for the two languages, pass an object with a `js` and `ts` filename including extensions.
* `<TypeScriptExample filename={{ js: "foo.js", ts: "bar.ts" }}>`
* `tabsWrapper` `boolean` (optional)
* When set to `false`, this component will not render `<Tabs>` components.
* This allows you to include the JS/TS tabs in your own `<Tabs>` and add `<TabItem>`s before/after, i.e for Python examples.
* `playground` `boolean` (optional)
* When set to `true`, a "Open Worker in Playground" link will render on the JavaScript codeblock.

````mdx live
import { TypeScriptExample } from "~/components";

<TypeScriptExample filename="index.ts">
```ts
interface Environment {
KV: KVNamespace;
}

export default {
async fetch(req, env, ctx): Promise<Response> {
if (req !== "POST") {
return new Response("Method Not Allowed", {
status: 405,
headers: {
"Allow": "POST"
}
});
}

await env.KV.put("foo", "bar");

return new Response();
}
} satisfies ExportedHandler<Environment>
```
</TypeScriptExample>
````
27 changes: 24 additions & 3 deletions src/content/docs/style-guide/components/github-code.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
title: GitHubCode
---

import { GitHubCode } from "~/components";

The `GitHubCode` component allows you to include files from Cloudflare repositories.

The remote content can be filtered by lines or a region enclosed in tags.
Expand All @@ -14,14 +16,25 @@ import { GitHubCode } from "~/components";

## Usage

```mdx live
import { GitHubCode } from "~/components";
<GitHubCode
repo="cloudflare/workflows-starter"
file="src/index.ts"
commit="a844e629ec80968118d4b116d4b26f5dcb107137"
lang="ts"
code={{
collapse: "3-6"
}}
/>

```mdx
<GitHubCode
repo="cloudflare/workflows-starter"
file="src/index.ts"
commit="a844e629ec80968118d4b116d4b26f5dcb107137"
lang="ts"
code={{
collapse: "2-3"
}}
/>
```

Expand Down Expand Up @@ -109,6 +122,8 @@ The long (40-characters) Git commit hash to pull from, for example `ab3951b5c953

The language to use for the code block, for example `rs`.

If the `lang` is `ts`, the [`TypeScriptExample`](/style-guide/components/typescript-example/) component will be used to provide a JavaScript tab as well.

### `lines`

**type:** `string`
Expand All @@ -121,4 +136,10 @@ A range of lines to filter the content using, for example `1-3`.

A region to filter the content with, for example `no-logging`.

This should be represented as starting `<docs-tag name="no-logging">` and closing `</docs-tag name="no-logging">` comments in the source file.
This should be represented as starting `<docs-tag name="no-logging">` and closing `</docs-tag name="no-logging">` comments in the source file.

### `code`

**type**: `object`

Props to pass to the [Expressive Code component](https://expressive-code.com/key-features/code-component/).
71 changes: 71 additions & 0 deletions src/content/docs/style-guide/components/typescript-example.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
title: TypeScript example
---

## TypeScript examples

The `TypeScriptExample` component uses [`ts-blank-space`](https://github.com/bloomberg/ts-blank-space) to remove TypeScript-specific syntax from your example and provide a JavaScript tab. This reduces maintenance burden by only having a single example to maintain.

This component is automatically used in the [`GitHubCode`](/style-guide/components/github-code/) component when the `lang` is set to `ts`.

:::note
Some TypeScript syntax influences runtime behaviour, and cannot be stripped.

Please refer to the [Unsupported Syntax](https://github.com/bloomberg/ts-blank-space?tab=readme-ov-file#unsupported-syntax) section of the project's README.
:::

## Component

````mdx live
import { TypeScriptExample } from "~/components";

<TypeScriptExample>
```ts
interface Environment {
KV: KVNamespace;
}

export default {
async fetch(req, env, ctx): Promise<Response> {
if (req !== "POST") {
return new Response("Method Not Allowed", {
status: 405,
headers: {
"Allow": "POST"
}
});
}

await env.KV.put("foo", "bar");

return new Response();
}
} satisfies ExportedHandler<Environment>
```
</TypeScriptExample>
````


## `<TypeScriptExample>` Props

### `filename`

**type:** `string`

An optional filename, ending in `.ts`.

`.ts` will be replaced by `.js` for the JavaScript tab.

### `playground`

**type:** `boolean`

If set to `true`, a [`Run Worker in Playground`](/style-guide/components/code/#playground) button will appear on the JavaScript tab.

### `code`

**type**: `object`

Props to pass to the [Expressive Code component](https://expressive-code.com/key-features/code-component/).

These props will apply to both code blocks and so options like `collapse` may not work as expected, as lines may be removed from the TypeScript code.
4 changes: 2 additions & 2 deletions src/content/docs/workers/get-started/prompting.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1003,9 +1003,9 @@ Depending on the model and user prompt, it may generate invalid code, configurat

### Passing a system prompt

If you are building an AI application that will itself generate code, you can additionally use the prompt above as a "system prompt", which will give the LLM additional information on how to structure the output code. For example:
If you are building an AI application that will itself generate code, you can additionally use the prompt above as a "system prompt", which will give the LLM additional information on how to structure the output code. For example:

<TypeScriptExample file="index.ts">
<TypeScriptExample filename="index.ts">

```ts
import workersPrompt from "./workersPrompt.md"
Expand Down
Loading