Files
sim/apps/docs/lib/content/request-samples.ts
Emir KarabegandWaleed Latif 7860fbe8cc feat(docs): rebuild documentation with the shared Sim design system (#9459)
* feat(docs): rebuild documentation with the Paper design system

* fix(docs): verify nested tabs and fresh-checkout CI setup

* chore(docs): refresh preservation evidence against latest staging

* fix(docs): align shared navigation and controls with Paper

* fix(docs): share active heading across responsive outlines

* fix(docs): track the final section at the end of the page

* fix(docs): preserve sidebar scroll in a persistent layout

* fix(docs): restore live screenshot backgrounds and framing

* fix(docs): finish layout polish and clean implementation references

* fix(docs): align shared dark theme and overlay states

* fix(docs): remove dark borders from platform screenshots

* test(docs): benchmark production navigation and image delivery in CI

* fix(docs): preserve machine content and production reading contracts

* fix(docs): retain readable tabs without JavaScript and verify current staging

* fix(docs): expose root response schemas and generate clean-checkout types

* fix(docs): resolve no-script tabs in the preflight cascade layer

* perf(docs): import only the search schema constructors

* fix(docs): preserve retrieval excerpts and reduce reading overhead

* fix(docs): reuse in-flight intent prefetches during navigation

* docs: record production readiness evidence and release requirements

* docs: clarify optimizer measurement provenance

* docs: preserve latest staging Search assets and compatibility evidence

* fix(docs): polish responsive controls and keep search indexing current

* test(docs): select the visible API example in browser checks

* test(docs): execute native examples against streaming and binary responses

* fix(docs): stream native API responses without buffering

* test(docs): cover review regressions through public interfaces

* fix(docs): preserve accessible examples and gate index publication

* fix(docs): finish accessible controls and cached content validation

* fix(docs): validate integration parents and report partial search failures

* fix(docs): refine navigation and compact sample controls

* fix(docs): isolate synchronous corpus validation from HTTP readers

* fix(docs): restore Paper interaction styling and verify responsive controls

* fix(docs): score each search page once per retrieval source

* fix(docs): attribute benchmark metrics to their source document

---------

Co-authored-by: Waleed Latif <walif6@gmail.com>
2026-10-30 17:06:09 -07:00

144 lines
5.6 KiB
TypeScript

interface RequestInput {
method: string
url: string
headers: Record<string, string>
body?: string
fields?: Array<{ name: string; value: string; file: boolean }>
}
const quote = (value: string) => JSON.stringify(value)
/** Native HTTP examples preserve request bytes and copy response bytes as they arrive. */
export function nativeRequestSamples({ method, url, headers, body, fields }: RequestInput) {
const goImports = ['io', 'net/http', 'os']
const goBody: string[] = []
let goPayload = 'nil'
const javaBody: string[] = []
let javaPayload = 'HttpRequest.BodyPublishers.noBody()'
const csharpBody: string[] = []
if (fields) {
goImports.push('bytes', 'mime/multipart')
goBody.push('payload := new(bytes.Buffer)', 'writer := multipart.NewWriter(payload)')
javaBody.push(
'String boundary = "SimDocs-" + java.util.UUID.randomUUID();',
'var parts = new java.util.ArrayList<HttpRequest.BodyPublisher>();'
)
csharpBody.push('var form = new MultipartFormDataContent();', 'request.Content = form;')
for (const [index, field] of fields.entries()) {
if (field.file) {
goBody.push(
`file${index} := must(os.Open("/path/to/document.pdf"))`,
`part${index} := must(writer.CreateFormFile(${quote(field.name)}, "document.pdf"))`,
`must(io.Copy(part${index}, file${index}))`,
`check(file${index}.Close())`
)
csharpBody.push(
`form.Add(new StreamContent(File.OpenRead("/path/to/document.pdf")), ${quote(field.name)}, "document.pdf");`
)
} else {
goBody.push(`check(writer.WriteField(${quote(field.name)}, ${quote(field.value)}))`)
csharpBody.push(`form.Add(new StringContent(${quote(field.value)}), ${quote(field.name)});`)
}
const disposition = `\r\nContent-Disposition: form-data; name="${field.name}"${field.file ? '; filename="document.pdf"\r\nContent-Type: application/octet-stream' : ''}\r\n\r\n`
javaBody.push(
`parts.add(HttpRequest.BodyPublishers.ofString("--" + boundary + ${quote(disposition)}));`,
field.file
? 'parts.add(HttpRequest.BodyPublishers.ofFile(java.nio.file.Path.of("/path/to/document.pdf")));'
: `parts.add(HttpRequest.BodyPublishers.ofString(${quote(field.value)}));`,
'parts.add(HttpRequest.BodyPublishers.ofString("\\r\\n"));'
)
}
goBody.push('check(writer.Close())')
goPayload = 'payload'
javaBody.push(
'parts.add(HttpRequest.BodyPublishers.ofString("--" + boundary + "--\\r\\n"));',
'var payload = HttpRequest.BodyPublishers.concat(parts.toArray(HttpRequest.BodyPublisher[]::new));',
'builder.header("Content-Type", "multipart/form-data; boundary=" + boundary);'
)
javaPayload = 'payload'
} else if (body !== undefined) {
goImports.push('strings')
goPayload = `strings.NewReader(${quote(body)})`
javaPayload = `HttpRequest.BodyPublishers.ofString(${quote(body)})`
csharpBody.push(`request.Content = new StringContent(${quote(body)}, Encoding.UTF8);`)
}
const goHeaders = Object.entries(headers).map(
([name, value]) => `request.Header.Set(${quote(name)}, ${quote(value)})`
)
if (fields) goHeaders.push('request.Header.Set("Content-Type", writer.FormDataContentType())')
const javaHeaders = Object.entries(headers).map(
([name, value]) => `builder.header(${quote(name)}, ${quote(value)});`
)
const csharpHeaders = Object.entries(headers).map(([name, value]) =>
name.toLowerCase() === 'content-type'
? `request.Content!.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(${quote(value)});`
: `request.Headers.TryAddWithoutValidation(${quote(name)}, ${quote(value)});`
)
return [
{
label: 'Go',
language: 'go',
code: `package main
import (
${goImports.map((name) => ` ${quote(name)}`).join('\n')}
)
func check(err error) {
if err != nil { panic(err) }
}
func must[T any](value T, err error) T {
check(err)
return value
}
func main() {
${goBody.map((line) => ` ${line}`).join('\n')}
request := must(http.NewRequest(${quote(method)}, ${quote(url)}, ${goPayload}))
${goHeaders.map((line) => ` ${line}`).join('\n')}
response := must(http.DefaultClient.Do(request))
defer response.Body.Close()
if response.StatusCode >= 400 { panic(response.Status) }
must(io.Copy(os.Stdout, response.Body))
}`,
},
{
label: 'Java',
language: 'java',
code: `import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Example {
public static void main(String[] args) throws Exception {
var builder = HttpRequest.newBuilder(URI.create(${quote(url)}));
${[...javaHeaders, ...javaBody].map((line) => ` ${line}`).join('\n')}
var request = builder.method(${quote(method)}, ${javaPayload}).build();
var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofInputStream());
try (var body = response.body()) {
if (response.statusCode() >= 400) throw new IllegalStateException("HTTP " + response.statusCode());
body.transferTo(System.out);
}
}
}`,
},
{
label: 'C#',
language: 'csharp',
code: `using System;
using System.IO;
using System.Net.Http;
using System.Text;
using var client = new HttpClient();
using var request = new HttpRequestMessage(new HttpMethod(${quote(method)}), ${quote(url)});
${[...csharpBody, ...csharpHeaders].join('\n')}
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
await response.Content.CopyToAsync(Console.OpenStandardOutput());`,
},
]
}