An experimental TypeSpec syntax for Lexicon

Compare changes

Choose any two refs to compare.

Changed files
+4260 -347
packages
cli
src
test
helpers
scenarios
basic
expected
lexicons
com
atproto
label
test
example
typelex
project
lexicons
com
atproto
label
init-preserves-main
expected
lexicons
com
example
typelex
project
missing-dependency
expected
lexicons
com
external
media
myapp
typelex
project
nested-init
expected
lexicons
com
myservice
example
typelex
project
parent-lexicons
expected1
app
lexicons
com
atproto
label
myapp
example
expected2
app
lexicons
com
atproto
label
myapp
example
project
app
lexicons
com
atproto
label
reserved-keywords
expected
lexicons
app
bsky
feed
com
atproto
server
pub
leaflet
example
typelex
project
lexicons
app
bsky
feed
com
atproto
server
validation-errors
with-external-lexicons
expected1
lexicons
com
atproto
label
myapp
example
typelex
expected2
lexicons
com
atproto
label
myapp
typelex
project
lexicons
com
atproto
label
emitter
lib
src
test
integration
atproto
input
app
bsky
actor
lexicon-examples
input
community
output
spec
website
scripts
+9
CHANGELOG.md
··· 1 + ### 0.3.1 2 + 3 + - Escape reserved keywords when generating code 4 + 5 + ### 0.3.0 6 + 7 + - New package `@typelex/cli` 8 + - See new recommended workflow on https://typelex.org/#install 9 + 1 10 ### 0.2.0 2 11 3 12 - Add `@external` support
+165 -31
DOCS.md
··· 258 258 259 259 The `@external` decorator tells the emitter to skip JSON output for that namespace. This is useful when referencing definitions from other Lexicons that you don't want to re-emit. 260 260 261 - You could collect external stubs in one file and import them: 262 - 263 - ```typescript 264 - import "@typelex/emitter"; 265 - import "../atproto-stubs.tsp"; 266 - 267 - namespace app.bsky.actor.profile { 268 - model Main { 269 - labels?: (com.atproto.label.defs.SelfLabels | unknown); 270 - } 271 - } 272 - ``` 273 - 274 - Then in `atproto-stubs.tsp`: 275 - 276 - ```typescript 277 - import "@typelex/emitter"; 278 - 279 - @external 280 - namespace com.atproto.label.defs { 281 - model SelfLabels { } 282 - } 283 - 284 - @external 285 - namespace com.atproto.repo.defs { 286 - model StrongRef { } 287 - @token model SomeToken { } // Note: Tokens still need @token 288 - } 289 - // ... more stubs 290 - ``` 261 + Starting with 0.3.0, typelex will automatically generate a `typelex/externals.tsp` file based on the JSON files in your `lexicons/` folder, and enforce that it's imported into your `typelex/main.tsp` entry point. However, this will *not* include Lexicons from your app's namespace, but only external ones. 291 262 292 263 You'll want to ensure the real JSON for external Lexicons is available before running codegen. 293 264 ··· 340 311 ``` 341 312 342 313 Note that `Caption` won't exist as a separate defโ€”the abstraction is erased in the output. 314 + 315 + ### Scalars 316 + 317 + TypeSpec scalars let you create named types with constraints. **By default, scalars create standalone defs** (like models): 318 + 319 + ```typescript 320 + import "@typelex/emitter"; 321 + 322 + namespace com.example { 323 + model Main { 324 + handle?: Handle; 325 + bio?: Bio; 326 + } 327 + 328 + @maxLength(50) 329 + scalar Handle extends string; 330 + 331 + @maxLength(256) 332 + @maxGraphemes(128) 333 + scalar Bio extends string; 334 + } 335 + ``` 336 + 337 + This creates three defs: `main`, `handle`, and `bio`: 338 + 339 + ```json 340 + { 341 + "id": "com.example", 342 + "defs": { 343 + "main": { 344 + "type": "object", 345 + "properties": { 346 + "handle": { "type": "ref", "ref": "#handle" }, 347 + "bio": { "type": "ref", "ref": "#bio" } 348 + } 349 + }, 350 + "handle": { 351 + "type": "string", 352 + "maxLength": 50 353 + }, 354 + "bio": { 355 + "type": "string", 356 + "maxLength": 256, 357 + "maxGraphemes": 128 358 + } 359 + } 360 + } 361 + ``` 362 + 363 + Use `@inline` to expand a scalar inline instead: 364 + 365 + ```typescript 366 + import "@typelex/emitter"; 367 + 368 + namespace com.example { 369 + model Main { 370 + handle?: Handle; 371 + } 372 + 373 + @inline 374 + @maxLength(50) 375 + scalar Handle extends string; 376 + } 377 + ``` 378 + 379 + Now `Handle` is expanded inline (no separate def): 380 + 381 + ```json 382 + // ... 383 + "properties": { 384 + "handle": { "type": "string", "maxLength": 50 } 385 + } 386 + // ... 387 + ``` 343 388 344 389 ## Top-Level Lexicon Types 345 390 ··· 934 979 935 980 ## Defaults and Constants 936 981 937 - ### Defaults 982 + ### Property Defaults 983 + 984 + You can set default values on properties: 938 985 939 986 ```typescript 940 987 import "@typelex/emitter"; ··· 948 995 ``` 949 996 950 997 Maps to: `{"default": 1}`, `{"default": "en"}` 998 + 999 + ### Type Defaults 1000 + 1001 + You can also set defaults on scalar and union types using the `@default` decorator: 1002 + 1003 + ```typescript 1004 + import "@typelex/emitter"; 1005 + 1006 + namespace com.example { 1007 + model Main { 1008 + mode?: Mode; 1009 + priority?: Priority; 1010 + } 1011 + 1012 + @default("standard") 1013 + scalar Mode extends string; 1014 + 1015 + @default(1) 1016 + @closed 1017 + @inline 1018 + union Priority { 1, 2, 3 } 1019 + } 1020 + ``` 1021 + 1022 + This creates a default on the type definition itself: 1023 + 1024 + ```json 1025 + { 1026 + "defs": { 1027 + "mode": { 1028 + "type": "string", 1029 + "default": "standard" 1030 + } 1031 + } 1032 + } 1033 + ``` 1034 + 1035 + For unions with token references, pass the model directly: 1036 + 1037 + ```typescript 1038 + import "@typelex/emitter"; 1039 + 1040 + namespace com.example { 1041 + model Main { 1042 + eventType?: EventType; 1043 + } 1044 + 1045 + @default(InPerson) 1046 + union EventType { Hybrid, InPerson, Virtual, string } 1047 + 1048 + @token model Hybrid {} 1049 + @token model InPerson {} 1050 + @token model Virtual {} 1051 + } 1052 + ``` 1053 + 1054 + This resolves to the fully-qualified token NSID: 1055 + 1056 + ```json 1057 + { 1058 + "eventType": { 1059 + "type": "string", 1060 + "knownValues": [ 1061 + "com.example#hybrid", 1062 + "com.example#inPerson", 1063 + "com.example#virtual" 1064 + ], 1065 + "default": "com.example#inPerson" 1066 + } 1067 + } 1068 + ``` 1069 + 1070 + **Important:** When a scalar or union creates a standalone def (not `@inline`), property-level defaults must match the type's `@default`. Otherwise you'll get an error: 1071 + 1072 + ```typescript 1073 + @default("standard") 1074 + scalar Mode extends string; 1075 + 1076 + model Main { 1077 + mode?: Mode = "custom"; // ERROR: Conflicting defaults! 1078 + } 1079 + ``` 1080 + 1081 + Solutions: 1082 + 1. Make the defaults match: `mode?: Mode = "standard"` 1083 + 2. Mark the type `@inline`: Allows property-level defaults 1084 + 3. Remove the property default: Uses the type's default 951 1085 952 1086 ### Constants 953 1087
+24
LICENSE.md
··· 18 18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 + SOFTWARE. 22 + 23 + Contains lexicons from https://github.com/lexicon-community/lexicon under the following license: 24 + 25 + MIT License 26 + 27 + Copyright (c) 2024 Lexicon Community 28 + 29 + Permission is hereby granted, free of charge, to any person obtaining a copy 30 + of this software and associated documentation files (the "Software"), to deal 31 + in the Software without restriction, including without limitation the rights 32 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 33 + copies of the Software, and to permit persons to whom the Software is 34 + furnished to do so, subject to the following conditions: 35 + 36 + The above copyright notice and this permission notice shall be included in all 37 + copies or substantial portions of the Software. 38 + 39 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 40 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 41 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 42 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 43 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 44 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 45 SOFTWARE.
+1 -1
package.json
··· 5 5 "description": "TypeSpec-based IDL for ATProto Lexicons", 6 6 "scripts": { 7 7 "build": "pnpm -r build", 8 - "test": "pnpm --filter @typelex/emitter test", 8 + "test": "pnpm -r test", 9 9 "test:watch": "pnpm --filter @typelex/emitter test:watch", 10 10 "example": "pnpm --filter @typelex/example build", 11 11 "playground": "pnpm --filter @typelex/playground dev",
+8 -3
packages/cli/package.json
··· 1 1 { 2 2 "name": "@typelex/cli", 3 - "version": "0.2.13", 3 + "version": "0.3.1", 4 4 "main": "dist/index.js", 5 5 "type": "module", 6 6 "bin": { ··· 14 14 "build": "tsc", 15 15 "clean": "rm -rf dist", 16 16 "watch": "tsc --watch", 17 + "test": "npm run build && vitest run", 18 + "test:watch": "npm run build && vitest watch", 17 19 "prepublishOnly": "npm run build" 18 20 }, 19 21 "keywords": [ ··· 26 28 "license": "MIT", 27 29 "dependencies": { 28 30 "@typespec/compiler": "^1.4.0", 31 + "globby": "^14.0.0", 29 32 "picocolors": "^1.1.1", 30 33 "yargs": "^18.0.0" 31 34 }, 32 35 "devDependencies": { 33 36 "@types/node": "^20.0.0", 34 37 "@types/yargs": "^17.0.33", 35 - "typescript": "^5.0.0" 38 + "typescript": "^5.0.0", 39 + "vitest": "^1.0.0", 40 + "@typelex/emitter": "workspace:*" 36 41 }, 37 42 "peerDependencies": { 38 - "@typelex/emitter": "^0.2.0" 43 + "@typelex/emitter": "^0.3.1" 39 44 } 40 45 }
+99 -41
packages/cli/src/commands/init.ts
··· 3 3 import { spawn } from "child_process"; 4 4 import { createInterface } from "readline"; 5 5 import pc from "picocolors"; 6 + import { generateExternalsFile } from "../utils/externals-generator.js"; 7 + import { escapeTypeSpecKeywords } from "../utils/escape-keywords.js"; 6 8 7 9 function gradientText(text: string): string { 8 10 const colors = [ 9 - '\x1b[38;5;33m', 10 - '\x1b[38;5;69m', 11 - '\x1b[38;5;99m', 12 - '\x1b[38;5;133m', 13 - '\x1b[38;5;170m', 14 - '\x1b[38;5;170m', 15 - '\x1b[38;5;133m', 11 + "\x1b[38;5;33m", 12 + "\x1b[38;5;69m", 13 + "\x1b[38;5;99m", 14 + "\x1b[38;5;133m", 15 + "\x1b[38;5;170m", 16 + "\x1b[38;5;170m", 17 + "\x1b[38;5;133m", 16 18 ]; 17 - const reset = '\x1b[0m'; 19 + const reset = "\x1b[0m"; 18 20 19 - return text.split('').map((char, i) => { 20 - const colorIndex = Math.floor((i / text.length) * colors.length); 21 - return colors[colorIndex] + char; 22 - }).join('') + reset; 21 + return ( 22 + text 23 + .split("") 24 + .map((char, i) => { 25 + const colorIndex = Math.floor((i / text.length) * colors.length); 26 + return colors[colorIndex] + char; 27 + }) 28 + .join("") + reset 29 + ); 23 30 } 24 31 25 32 function createMainTemplate(namespace: string): string { 33 + const escapedNamespace = escapeTypeSpecKeywords(namespace); 26 34 return `import "@typelex/emitter"; 27 35 import "./externals.tsp"; 28 36 29 - namespace ${namespace}.post { 30 - @rec("tid") 37 + namespace ${escapedNamespace}.example.profile { 38 + /** My profile. */ 39 + @rec("literal:self") 31 40 model Main { 32 - @required text: string; 33 - @required createdAt: datetime; 41 + /** Free-form profile description.*/ 42 + @maxGraphemes(256) 43 + description?: string; 34 44 } 35 45 } 36 46 `; ··· 49 59 }); 50 60 51 61 return new Promise((resolve) => { 52 - rl.question(`Enter your app's root namespace (e.g. ${pc.cyan("com.example.*")}): `, (answer) => { 53 - rl.close(); 54 - resolve(answer.trim()); 55 - }); 62 + rl.question( 63 + `Which Lexicons do you want to write in typelex (e.g. ${pc.cyan("com.example.*")})? `, 64 + (answer) => { 65 + rl.close(); 66 + resolve(answer.trim()); 67 + }, 68 + ); 56 69 }); 57 70 } 58 71 59 - export async function initCommand(isSetup: boolean = false, flags: string[] = []): Promise<void> { 72 + export async function initCommand( 73 + isSetup: boolean = false, 74 + flags: string[] = [], 75 + ): Promise<void> { 60 76 const originalCwd = process.cwd(); 61 77 62 78 // Find nearest package.json upward ··· 76 92 return initSetup(); 77 93 } 78 94 79 - console.log(`Adding ${gradientText("typelex")}...\n`); 95 + console.log(gradientText("Adding typelex...") + "\n"); 80 96 81 97 // Detect package manager 82 98 let packageManager = "npm"; ··· 101 117 102 118 // Install dependencies 103 119 await new Promise<void>((resolvePromise, reject) => { 104 - const args = packageManager === "npm" 105 - ? ["install", "--save-dev", "@typelex/cli@latest", "@typelex/emitter@latest"] 106 - : ["add", "-D", "@typelex/cli@latest", "@typelex/emitter@latest"]; 120 + const args = 121 + packageManager === "npm" 122 + ? [ 123 + "install", 124 + "--save-dev", 125 + "@typelex/cli@latest", 126 + "@typelex/emitter@latest", 127 + ] 128 + : ["add", "-D", "@typelex/cli@latest", "@typelex/emitter@latest"]; 107 129 108 130 // Add any additional flags 109 131 args.push(...flags); ··· 115 137 116 138 install.on("close", (code) => { 117 139 if (code === 0) { 118 - console.log(`\n${pc.green("โœ“")} Installed ${pc.dim("@typelex/cli")} and ${pc.dim("@typelex/emitter")}\n`); 140 + console.log( 141 + `\n${pc.green("โœ“")} Installed ${pc.dim("@typelex/cli")} and ${pc.dim("@typelex/emitter")}\n`, 142 + ); 119 143 resolvePromise(); 120 144 } else { 121 145 console.error(pc.red("โœ— Failed to install dependencies")); ··· 217 241 : lexiconsDir || "./lexicons"; 218 242 219 243 // Inform about external lexicons 220 - console.log(`\nLexicons other than ${pc.cyan(namespace)} will be considered external.`); 221 - console.log(`Put them into the ${pc.cyan(displayLexiconsPath)} folder as JSON.\n`); 244 + console.log( 245 + `\nLexicons for ${pc.cyan(namespace)} will now be managed by typelex.`, 246 + ); 247 + console.log(`You can begin writing them in ${pc.cyan("typelex/main.tsp")}.`); 248 + console.log( 249 + `Any external lexicons should remain in ${pc.cyan(displayLexiconsPath)}.\n`, 250 + ); 222 251 223 252 // Create typelex directory 224 253 await mkdir(typelexDir, { recursive: true }); ··· 229 258 await access(mainTspPath); 230 259 const content = await readFile(mainTspPath, "utf-8"); 231 260 if (content.trim().length > 0) { 232 - console.log(`${pc.green("โœ“")} ${pc.cyan("typelex/main.tsp")} already exists, skipping`); 261 + console.log( 262 + `${pc.green("โœ“")} ${pc.cyan("typelex/main.tsp")} already exists, skipping`, 263 + ); 233 264 shouldCreateMain = false; 234 265 } 235 266 } catch { ··· 241 272 console.log(`${pc.green("โœ“")} Created ${pc.cyan("typelex/main.tsp")}`); 242 273 } 243 274 244 - // Always create/overwrite externals.tsp 245 - await writeFile(externalsTspPath, EXTERNALS_TSP_TEMPLATE, "utf-8"); 275 + // Generate externals.tsp with any existing external lexicons 276 + const outDir = lexiconsDir || "./lexicons"; 277 + await generateExternalsFile(namespace, cwd, outDir); 246 278 console.log(`${pc.green("โœ“")} Created ${pc.cyan("typelex/externals.tsp")}`); 247 279 248 280 // Add build script to package.json ··· 254 286 } 255 287 if (!packageJson.scripts["build:typelex"]) { 256 288 const outFlag = lexiconsDir ? ` --out ${lexiconsDir}` : ""; 257 - packageJson.scripts["build:typelex"] = `typelex compile ${namespace}${outFlag}`; 258 - await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n", "utf-8"); 259 - console.log(`${pc.green("โœ“")} Added ${pc.cyan("build:typelex")} script to ${pc.cyan("package.json")}`); 289 + packageJson.scripts["build:typelex"] = 290 + `typelex compile ${namespace}${outFlag}`; 291 + await writeFile( 292 + packageJsonPath, 293 + JSON.stringify(packageJson, null, 2) + "\n", 294 + "utf-8", 295 + ); 296 + console.log( 297 + `${pc.green("โœ“")} Added ${pc.cyan("build:typelex")} script to ${pc.cyan("package.json")}`, 298 + ); 260 299 if (hasLocalLexicons) { 261 - console.log(pc.dim(` Using existing lexicons directory: ${pc.cyan("./lexicons")}`)); 300 + console.log( 301 + pc.dim( 302 + ` Using existing lexicons directory: ${pc.cyan("./lexicons")}`, 303 + ), 304 + ); 262 305 } else if (lexiconsDir) { 263 - console.log(pc.dim(` Using existing lexicons directory: ${pc.cyan(lexiconsDir)}`)); 306 + console.log( 307 + pc.dim( 308 + ` Using existing lexicons directory: ${pc.cyan(lexiconsDir)}`, 309 + ), 310 + ); 264 311 } 265 312 } else { 266 - console.log(`${pc.green("โœ“")} ${pc.cyan("build:typelex")} script already exists in ${pc.cyan("package.json")}`); 313 + console.log( 314 + `${pc.green("โœ“")} ${pc.cyan("build:typelex")} script already exists in ${pc.cyan("package.json")}`, 315 + ); 267 316 } 268 317 } catch (err) { 269 - console.warn(pc.yellow(`โš  Could not update ${pc.cyan("package.json")}:`), (err as Error).message); 318 + console.warn( 319 + pc.yellow(`โš  Could not update ${pc.cyan("package.json")}:`), 320 + (err as Error).message, 321 + ); 270 322 } 271 323 272 324 console.log(`\n${pc.green("โœ“")} ${pc.bold("All set!")}`); 273 325 console.log(`\n${pc.bold("Next steps:")}`); 274 - console.log(` ${pc.dim("1.")} Edit ${pc.cyan("typelex/main.tsp")} to define your lexicons`); 275 - console.log(` ${pc.dim("2.")} Keep putting external lexicons into ${pc.cyan(displayLexiconsPath)}`); 276 - console.log(` ${pc.dim("3.")} Run ${pc.cyan("npm run build:typelex")} to compile to JSON`); 326 + console.log( 327 + ` ${pc.dim("1.")} Edit ${pc.cyan("typelex/main.tsp")} to define the ${pc.cyan(namespace)} lexicons`, 328 + ); 329 + console.log( 330 + ` ${pc.dim("2.")} Keep putting external lexicons into ${pc.cyan(displayLexiconsPath)}`, 331 + ); 332 + console.log( 333 + ` ${pc.dim("3.")} Run ${pc.cyan("npm run build:typelex")} to compile to JSON`, 334 + ); 277 335 }
+28
packages/cli/src/utils/escape-keywords.ts
··· 1 + /** 2 + * Complete list of TypeSpec reserved keywords (67 total) 3 + * Source: @typespec/compiler/src/core/scanner.ts 4 + */ 5 + const TYPESPEC_KEYWORDS = new Set([ 6 + // Active keywords 7 + "import", "model", "scalar", "namespace", "using", "op", "enum", "alias", 8 + "is", "interface", "union", "projection", "else", "if", "dec", "fn", 9 + "const", "init", "extern", "extends", "true", "false", "return", "void", 10 + "never", "unknown", "valueof", "typeof", 11 + // Reserved keywords 12 + "statemachine", "macro", "package", "metadata", "env", "arg", "declare", 13 + "array", "struct", "record", "module", "mod", "sym", "context", "prop", 14 + "property", "scenario", "pub", "sub", "typeref", "trait", "this", "self", 15 + "super", "keyof", "with", "implements", "impl", "satisfies", "flag", "auto", 16 + "partial", "private", "public", "protected", "internal", "sealed", "local", 17 + "async" 18 + ]); 19 + 20 + /** 21 + * Escape TypeSpec reserved keywords in a namespace identifier 22 + * Example: "pub.leaflet.example" -> "`pub`.leaflet.example" 23 + */ 24 + export function escapeTypeSpecKeywords(nsid: string): string { 25 + return nsid.split('.').map(part => 26 + TYPESPEC_KEYWORDS.has(part) ? `\`${part}\`` : part 27 + ).join('.'); 28 + }
+3 -2
packages/cli/src/utils/externals-generator.ts
··· 1 1 import { resolve } from "path"; 2 2 import { writeFile, mkdir } from "fs/promises"; 3 3 import { findExternalLexicons, LexiconDoc, isTokenDef, isModelDef } from "./lexicon.js"; 4 + import { escapeTypeSpecKeywords } from "./escape-keywords.js"; 4 5 5 6 /** 6 7 * Convert camelCase to PascalCase ··· 38 39 39 40 for (const [nsid, lexicon] of sortedNamespaces) { 40 41 lines.push("@external"); 41 - // Escape reserved keywords in namespace (like 'record') 42 - const escapedNsid = nsid.replace(/\b(record|union|enum|interface|namespace|model|op|import|using|extends|is|scalar|alias|if|else|return|void|never|unknown|any|true|false|null)\b/g, '`$1`'); 42 + // Escape reserved keywords in namespace 43 + const escapedNsid = escapeTypeSpecKeywords(nsid); 43 44 lines.push(`namespace ${escapedNsid} {`); 44 45 45 46 // Sort definitions for consistent output
+291
packages/cli/test/helpers/test-project.ts
··· 1 + import { mkdtemp, rm, mkdir, writeFile, readFile, readdir, stat } from "fs/promises"; 2 + import { join, resolve, dirname } from "path"; 3 + import { tmpdir } from "os"; 4 + import { spawn } from "child_process"; 5 + import { fileURLToPath } from "url"; 6 + 7 + const __filename = fileURLToPath(import.meta.url); 8 + const __dirname = dirname(__filename); 9 + 10 + export interface TestProjectOptions { 11 + packageManager?: "npm" | "pnpm"; 12 + } 13 + 14 + export class TestProject { 15 + public readonly path: string; 16 + public scenarioPath?: string; 17 + private cleanupHandlers: Array<() => Promise<void>> = []; 18 + 19 + constructor(path: string) { 20 + this.path = path; 21 + } 22 + 23 + static async create(options: TestProjectOptions = {}): Promise<TestProject> { 24 + const tmpDir = await mkdtemp(join(tmpdir(), "typelex-test-")); 25 + const project = new TestProject(tmpDir); 26 + 27 + // Create lock file based on package manager (scenarios provide their own package.json and lexicons) 28 + if (options.packageManager === "pnpm") { 29 + await writeFile(join(tmpDir, "pnpm-lock.yaml"), "lockfileVersion: '6.0'\n"); 30 + } else if (options.packageManager === "npm") { 31 + // npm is default, no lock file needed for detection 32 + } 33 + 34 + return project; 35 + } 36 + 37 + async cleanup(): Promise<void> { 38 + for (const handler of this.cleanupHandlers) { 39 + await handler(); 40 + } 41 + await rm(this.path, { recursive: true, force: true }); 42 + } 43 + 44 + async writeFile(relativePath: string, content: string): Promise<void> { 45 + const fullPath = join(this.path, relativePath); 46 + await mkdir(join(fullPath, ".."), { recursive: true }); 47 + await writeFile(fullPath, content); 48 + } 49 + 50 + async readFile(relativePath: string): Promise<string> { 51 + return readFile(join(this.path, relativePath), "utf-8"); 52 + } 53 + 54 + async fileExists(relativePath: string): Promise<boolean> { 55 + try { 56 + await stat(join(this.path, relativePath)); 57 + return true; 58 + } catch { 59 + return false; 60 + } 61 + } 62 + 63 + async readJson(relativePath: string): Promise<unknown> { 64 + const content = await this.readFile(relativePath); 65 + return JSON.parse(content); 66 + } 67 + 68 + async getDirectoryContents(relativePath: string = ""): Promise<string[]> { 69 + const fullPath = join(this.path, relativePath); 70 + try { 71 + return await readdir(fullPath); 72 + } catch { 73 + return []; 74 + } 75 + } 76 + 77 + async runCommand( 78 + command: string, 79 + args: string[], 80 + options: { input?: string; env?: Record<string, string>; cwd?: string } = {} 81 + ): Promise<{ stdout: string; stderr: string; exitCode: number; output: string }> { 82 + return new Promise((promiseResolve, promiseReject) => { 83 + // Add monorepo node_modules/.bin to PATH for tsp and other tools 84 + const monorepoRoot = resolve(__dirname, "../../../.."); 85 + const tspBinPath = join(monorepoRoot, "node_modules/.bin"); 86 + const envPath = options.env?.PATH || process.env.PATH || ""; 87 + const newPath = `${tspBinPath}:${envPath}`; 88 + 89 + const child = spawn(command, args, { 90 + cwd: options.cwd || this.path, 91 + env: { ...process.env, ...options.env, PATH: newPath }, 92 + }); 93 + 94 + let stdout = ""; 95 + let stderr = ""; 96 + 97 + child.stdout?.on("data", (data) => { 98 + stdout += data.toString(); 99 + }); 100 + 101 + child.stderr?.on("data", (data) => { 102 + stderr += data.toString(); 103 + }); 104 + 105 + if (options.input) { 106 + child.stdin?.write(options.input); 107 + child.stdin?.end(); 108 + } 109 + 110 + child.on("close", (exitCode) => { 111 + promiseResolve({ 112 + stdout, 113 + stderr, 114 + exitCode: exitCode ?? 0, 115 + output: stdout + stderr // Combined output for easier testing 116 + }); 117 + }); 118 + 119 + child.on("error", promiseReject); 120 + }); 121 + } 122 + 123 + async runTypelex(args: string[], options?: { input?: string; cwd?: string }): Promise<{ 124 + stdout: string; 125 + stderr: string; 126 + exitCode: number; 127 + output: string; // Combined stdout + stderr 128 + }> { 129 + // Use the local CLI from the monorepo 130 + const cliPath = resolve(__dirname, "../../dist/cli.js"); 131 + const result = await this.runCommand("node", [cliPath, ...args], options); 132 + return { 133 + ...result, 134 + output: result.stdout + result.stderr, 135 + }; 136 + } 137 + 138 + async compile(namespace: string, outDir: string = "./lexicons", options?: { cwd?: string }): Promise<void> { 139 + const result = await this.runTypelex(["compile", namespace, "--out", outDir], options); 140 + if (result.exitCode !== 0) { 141 + throw new Error(`Compilation failed: ${result.output}`); 142 + } 143 + } 144 + 145 + async init(namespace: string, options?: { cwd?: string }): Promise<void> { 146 + const result = await this.runTypelex(["init", "--setup"], { 147 + input: `${namespace}\n`, 148 + ...options, 149 + }); 150 + if (result.exitCode !== 0) { 151 + throw new Error(`Init failed: ${result.output}`); 152 + } 153 + } 154 + 155 + async runBuildScript(options?: { cwd?: string }): Promise<{stdout: string; stderr: string}> { 156 + const result = await this.runCommand("npm", ["run", "build:typelex"], options); 157 + if (result.exitCode !== 0) { 158 + throw new Error(`Build failed with exit code ${result.exitCode}:\n${result.output}`); 159 + } 160 + return { stdout: result.stdout, stderr: result.stderr }; 161 + } 162 + 163 + async expectBuildToFail(options?: { cwd?: string }): Promise<{stdout: string; stderr: string; output: string}> { 164 + const result = await this.runCommand("npm", ["run", "build:typelex"], options); 165 + if (result.exitCode === 0) { 166 + throw new Error(`Expected build to fail but it succeeded`); 167 + } 168 + return { stdout: result.stdout, stderr: result.stderr, output: result.output }; 169 + } 170 + 171 + /** 172 + * Compare files in the project against an expected directory 173 + * Only checks files that exist in expectedDir 174 + */ 175 + async compareTo(expectedSubdir: string = "expected"): Promise<void> { 176 + const { readdir } = await import("fs/promises"); 177 + 178 + if (!this.scenarioPath) { 179 + throw new Error("scenarioPath not set on TestProject"); 180 + } 181 + 182 + const expectedDir = join(this.scenarioPath, expectedSubdir); 183 + 184 + // Helper to recursively list all files in a directory 185 + async function listAllFiles(dir: string, prefix: string = ""): Promise<string[]> { 186 + const files: string[] = []; 187 + try { 188 + const entries = await readdir(dir, { withFileTypes: true }); 189 + for (const entry of entries) { 190 + const fullPath = join(dir, entry.name); 191 + const relPath = prefix ? join(prefix, entry.name) : entry.name; 192 + if (entry.isDirectory()) { 193 + files.push(...await listAllFiles(fullPath, relPath)); 194 + } else { 195 + files.push(relPath); 196 + } 197 + } 198 + } catch { 199 + // Directory doesn't exist 200 + } 201 + return files.sort(); 202 + } 203 + 204 + async function compareRecursive(relPath: string = "") { 205 + const expectedPath = join(expectedDir, relPath); 206 + const actualPath = join(this.path, relPath); 207 + 208 + const entries = await readdir(expectedPath, { withFileTypes: true }); 209 + 210 + for (const entry of entries) { 211 + const entryRelPath = join(relPath, entry.name); 212 + 213 + if (entry.isDirectory()) { 214 + await compareRecursive.call(this, entryRelPath); 215 + } else { 216 + const expected = await readFile(join(expectedDir, entryRelPath), "utf-8"); 217 + 218 + let actual: string; 219 + try { 220 + actual = await readFile(join(this.path, entryRelPath), "utf-8"); 221 + } catch (err) { 222 + if ((err as NodeJS.ErrnoException).code === "ENOENT") { 223 + // File is missing - show what files actually exist 224 + const actualFiles = await listAllFiles(this.path); 225 + throw new Error( 226 + `Expected file not found: ${entryRelPath}\n\n` + 227 + `Actual files in project:\n${actualFiles.map(f => ` ${f}`).join("\n") || " (none)"}` 228 + ); 229 + } 230 + throw err; 231 + } 232 + 233 + if (expected !== actual) { 234 + throw new Error( 235 + `File mismatch: ${entryRelPath}\n\nExpected:\n${expected}\n\nActual:\n${actual}` 236 + ); 237 + } 238 + } 239 + } 240 + } 241 + 242 + await compareRecursive.call(this); 243 + } 244 + 245 + /** 246 + * Mock npm/pnpm install by creating node_modules structure 247 + * Links to the real packages from the monorepo 248 + */ 249 + async mockInstall(): Promise<void> { 250 + const nodeModulesPath = join(this.path, "node_modules"); 251 + await mkdir(nodeModulesPath, { recursive: true }); 252 + await mkdir(join(nodeModulesPath, ".bin"), { recursive: true }); 253 + await mkdir(join(nodeModulesPath, "@typelex"), { recursive: true }); 254 + await mkdir(join(nodeModulesPath, "@typespec"), { recursive: true }); 255 + 256 + // Get paths to real packages in monorepo 257 + const monorepoRoot = resolve(__dirname, "../../../.."); 258 + const cliPackagePath = resolve(monorepoRoot, "packages/cli"); 259 + const emitterPackagePath = resolve(monorepoRoot, "packages/emitter"); 260 + const typespecCompilerPath = resolve(monorepoRoot, "node_modules/@typespec/compiler"); 261 + 262 + // Create symlinks to real packages 263 + const { symlink } = await import("fs/promises"); 264 + 265 + try { 266 + await symlink(cliPackagePath, join(nodeModulesPath, "@typelex/cli"), "dir"); 267 + } catch (err) { 268 + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; 269 + } 270 + 271 + try { 272 + await symlink(emitterPackagePath, join(nodeModulesPath, "@typelex/emitter"), "dir"); 273 + } catch (err) { 274 + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; 275 + } 276 + 277 + try { 278 + await symlink(typespecCompilerPath, join(nodeModulesPath, "@typespec/compiler"), "dir"); 279 + } catch (err) { 280 + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; 281 + } 282 + 283 + // Create bin symlink for typelex CLI 284 + const cliPath = resolve(cliPackagePath, "dist/cli.js"); 285 + try { 286 + await symlink(cliPath, join(nodeModulesPath, ".bin/typelex"), "file"); 287 + } catch (err) { 288 + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; 289 + } 290 + } 291 + }
+123
packages/cli/test/scenarios/README.md
··· 1 + # Test Scenarios 2 + 3 + This directory contains declarative test scenarios for the typelex CLI. 4 + 5 + ## Philosophy 6 + 7 + **These tests focus on CLI workflows, NOT language features.** 8 + 9 + The CLI's job is to: 10 + 1. Find/create lexicons directories (`./lexicons`, `../lexicons`) 11 + 2. Read existing JSON lexicons from disk 12 + 3. Generate `externals.tsp` from those JSON files 13 + 4. Run compilation while preserving external lexicons 14 + 5. Manage paths and directory structures correctly 15 + 16 + Language features (syntax, types, decorators) are tested in the emitter package. 17 + 18 + ## Test Coverage 19 + 20 + All non-trivial branches in the CLI code are tested. Each test was verified by: 21 + 1. Breaking the code (commenting out the condition) 22 + 2. Verifying the test fails 23 + 3. Fixing the code and verifying the test passes 24 + 25 + ### Current Scenarios (8 total) 26 + 27 + **External Lexicon Workflows** (The Core CLI Functionality): 28 + - `compile-with-external-atproto` - Real JSONโ†’TSPโ†’JSON cycle, externals preserved 29 + - `compile-to-parent-lexicons` - Compile with `../lexicons` directory 30 + - `compile-idempotent` - Deterministic output across runs 31 + 32 + **Init Workflows** (Directory Detection & File Management): 33 + - `init-finds-current-lexicons` - Detects `./lexicons`, no `--out` flag 34 + - `init-finds-parent-lexicons` - Detects `../lexicons`, adds `--out ../lexicons` 35 + - `init-overwrites-empty-main` - Empty `main.tsp` gets overwritten 36 + - `init-preserves-build-script` - Existing `build:typelex` not overwritten 37 + 38 + **Validation** (Error Handling): 39 + - `validation-errors` - Namespace format, path validation, file structure 40 + 41 + ### Branch Coverage Matrix 42 + 43 + | File | Line | Branch | Tested By | 44 + |------|------|--------|-----------| 45 + | compile.ts | 21 | Path validation | validation-errors | 46 + | ensure-imports.ts | 20 | First line check | validation-errors | 47 + | ensure-imports.ts | 26 | Second line check | validation-errors | 48 + | ensure-imports.ts | 32 | File not found | validation-errors | 49 + | externals-generator.ts | 87 | No externals case | All compile scenarios | 50 + | init.ts | 194 | Local lexicons dir | init-finds-current-lexicons | 51 + | init.ts | 203 | Parent lexicons dir | init-finds-parent-lexicons | 52 + | init.ts | 231 | Empty main.tsp | init-overwrites-empty-main | 53 + | init.ts | 252 | No scripts object | All init scenarios (crashes without) | 54 + | init.ts | 255 | Script exists | init-preserves-build-script | 55 + 56 + ## Structure 57 + 58 + Each scenario directory contains: 59 + 60 + ``` 61 + scenario-name/ 62 + project/ # Realistic project structure 63 + package.json 64 + typelex/ 65 + main.tsp # Input TypeSpec 66 + externals.tsp # Boilerplate or generated 67 + lexicons/ # REAL JSON FILES (not mocked!) 68 + com/atproto/... # Checked-in external lexicons 69 + expected/ # Expected outputs (optional) 70 + lexicons/ 71 + com/myapp/... 72 + test.ts # Test logic with run() function 73 + ``` 74 + 75 + ## Writing Tests 76 + 77 + The `test.ts` exports a `run()` function that performs assertions: 78 + 79 + ```typescript 80 + import { expect } from "vitest"; 81 + 82 + export const namespace = "com.myapp.*"; 83 + 84 + export async function run(project, scenarioPath) { 85 + // Compile 86 + await project.compile(namespace); 87 + 88 + // Assert on behavior 89 + const externals = await project.readFile("typelex/externals.tsp"); 90 + expect(externals).toContain("namespace com.atproto.label.defs"); 91 + 92 + // Verify files match expected 93 + await verifyExpectedFiles(join(scenarioPath, "expected"), project); 94 + } 95 + ``` 96 + 97 + Available exports: 98 + - `namespace` - Default namespace 99 + - `packageManager` - "npm" or "pnpm" 100 + - `lexiconsDirLocation` - "current", "parent" 101 + - `run(project, scenarioPath)` - Test logic 102 + 103 + Available helpers: 104 + - `project.compile(namespace, outDir?)` - Compile (throws on error) 105 + - `project.init(namespace)` - Run init (throws on error) 106 + - `project.runTypelex(args, options?)` - Run any command 107 + - `project.writeFile/readFile/readJson/fileExists` 108 + - `verifyExpectedFiles(expectedDir, project)` - Match expected outputs 109 + 110 + ## Key Insight 111 + 112 + Most tests should have **real lexicons/ folders with JSON files**. This tests the actual CLI behavior: reading JSON from disk, generating externals.tsp, and emitting new JSON that correctly references external lexicons. 113 + 114 + Don't test language features here - test file I/O, directory management, and the JSONโ†”TSPโ†”JSON workflow. 115 + 116 + ## Adding New Tests 117 + 118 + When adding a new scenario, verify it catches bugs: 119 + 1. Write the test 120 + 2. Break the corresponding code 121 + 3. Run tests - should FAIL 122 + 4. Fix the code 123 + 5. Run tests - should PASS
+27
packages/cli/test/scenarios/basic/expected/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+21
packages/cli/test/scenarios/basic/expected/lexicons/com/test/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.test.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + } 16 + } 17 + }, 18 + "description": "My profile." 19 + } 20 + } 21 + }
+8
packages/cli/test/scenarios/basic/expected/package.json
··· 1 + { 2 + "name": "test-idempotent", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.test.*" 7 + } 8 + }
+10
packages/cli/test/scenarios/basic/expected/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.test.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.atproto.label.defs { 8 + model SelfLabel { } 9 + model SelfLabels { } 10 + }
+12
packages/cli/test/scenarios/basic/expected/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.test.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + } 12 + }
+27
packages/cli/test/scenarios/basic/project/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+1
packages/cli/test/scenarios/basic/project/package.json
··· 1 + {"name":"test-idempotent","version":"1.0.0","type":"module"}
+10
packages/cli/test/scenarios/basic/test.ts
··· 1 + export async function run(project) { 2 + await project.init("com.test.*"); 3 + 4 + await project.runBuildScript(); 5 + await project.compareTo("expected"); 6 + 7 + // Second build - verify idempotency 8 + await project.runBuildScript(); 9 + await project.compareTo("expected"); 10 + }
+25
packages/cli/test/scenarios/init-preserves-main/expected/lexicons/com/example/custom.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.example.custom", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "tid", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "foo": { 12 + "type": "string" 13 + }, 14 + "bar": { 15 + "type": "integer" 16 + } 17 + }, 18 + "required": [ 19 + "foo", 20 + "bar" 21 + ] 22 + } 23 + } 24 + } 25 + }
+8
packages/cli/test/scenarios/init-preserves-main/expected/package.json
··· 1 + { 2 + "name": "test-init-preserves-main", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.example.*" 7 + } 8 + }
+4
packages/cli/test/scenarios/init-preserves-main/expected/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.example.*) 4 + // No external lexicons found
+10
packages/cli/test/scenarios/init-preserves-main/expected/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.example.custom { 5 + @rec("tid") 6 + model Main { 7 + @required foo: string; 8 + @required bar: integer; 9 + } 10 + }
+1
packages/cli/test/scenarios/init-preserves-main/project/package.json
··· 1 + {"name":"test-init-preserves-main","version":"1.0.0","type":"module"}
+10
packages/cli/test/scenarios/init-preserves-main/project/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.example.custom { 5 + @rec("tid") 6 + model Main { 7 + @required foo: string; 8 + @required bar: integer; 9 + } 10 + }
+9
packages/cli/test/scenarios/init-preserves-main/test.ts
··· 1 + export async function run(project) { 2 + await project.init("com.example.*"); 3 + await project.runBuildScript(); 4 + await project.compareTo("expected"); 5 + 6 + // Second build - verify idempotency 7 + await project.runBuildScript(); 8 + await project.compareTo("expected"); 9 + }
+21
packages/cli/test/scenarios/missing-dependency/expected/lexicons/com/external/media/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.external.media.defs", 4 + "defs": { 5 + "video": { 6 + "type": "object", 7 + "properties": { 8 + "url": { 9 + "type": "string", 10 + "format": "uri" 11 + }, 12 + "mimeType": { 13 + "type": "string" 14 + } 15 + }, 16 + "required": [ 17 + "url" 18 + ] 19 + } 20 + } 21 + }
+25
packages/cli/test/scenarios/missing-dependency/expected/lexicons/com/myapp/post.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myapp.post", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "tid", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "text": { 12 + "type": "string" 13 + }, 14 + "video": { 15 + "type": "ref", 16 + "ref": "com.external.media.defs#video" 17 + } 18 + }, 19 + "required": [ 20 + "text" 21 + ] 22 + } 23 + } 24 + } 25 + }
+8
packages/cli/test/scenarios/missing-dependency/expected/package.json
··· 1 + { 2 + "name": "test-missing-dependency", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myapp.*" 7 + } 8 + }
+9
packages/cli/test/scenarios/missing-dependency/expected/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.myapp.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.external.media.defs { 8 + model Video { } 9 + }
+10
packages/cli/test/scenarios/missing-dependency/expected/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myapp.post { 5 + @rec("tid") 6 + model Main { 7 + @required text: string; 8 + video?: com.external.media.defs.Video; 9 + } 10 + }
+1
packages/cli/test/scenarios/missing-dependency/project/package.json
··· 1 + {"name":"test-missing-dependency","version":"1.0.0","type":"module"}
+51
packages/cli/test/scenarios/missing-dependency/test.ts
··· 1 + export async function run(project) { 2 + await project.init("com.myapp.*"); 3 + 4 + // Edit main.tsp to reference a missing external lexicon 5 + await project.writeFile("typelex/main.tsp", `import "@typelex/emitter"; 6 + import "./externals.tsp"; 7 + 8 + namespace com.myapp.post { 9 + @rec("tid") 10 + model Main { 11 + @required text: string; 12 + video?: com.external.media.defs.Video; 13 + } 14 + } 15 + `); 16 + 17 + // Build should fail because com.external.media.defs doesn't exist 18 + const failure = await project.expectBuildToFail(); 19 + if (!failure.output.includes("com.external.media.defs")) { 20 + throw new Error(`Expected error about missing com.external.media.defs, got: ${failure.output}`); 21 + } 22 + 23 + // Add the missing external lexicon 24 + await project.writeFile("lexicons/com/external/media/defs.json", JSON.stringify({ 25 + "lexicon": 1, 26 + "id": "com.external.media.defs", 27 + "defs": { 28 + "video": { 29 + "type": "object", 30 + "properties": { 31 + "url": { 32 + "type": "string", 33 + "format": "uri" 34 + }, 35 + "mimeType": { 36 + "type": "string" 37 + } 38 + }, 39 + "required": ["url"] 40 + } 41 + } 42 + }, null, 2) + "\n"); 43 + 44 + // Now build should succeed 45 + await project.runBuildScript(); 46 + await project.compareTo("expected"); 47 + 48 + // Verify idempotency 49 + await project.runBuildScript(); 50 + await project.compareTo("expected"); 51 + }
+21
packages/cli/test/scenarios/nested-init/expected/lexicons/com/myservice/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myservice.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + } 16 + } 17 + }, 18 + "description": "My profile." 19 + } 20 + } 21 + }
+8
packages/cli/test/scenarios/nested-init/expected/package.json
··· 1 + { 2 + "name": "test-nested-init", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myservice.*" 7 + } 8 + }
+4
packages/cli/test/scenarios/nested-init/expected/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.myservice.*) 4 + // No external lexicons found
+12
packages/cli/test/scenarios/nested-init/expected/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myservice.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + } 12 + }
+1
packages/cli/test/scenarios/nested-init/project/package.json
··· 1 + {"name":"test-nested-init","version":"1.0.0","type":"module"}
+16
packages/cli/test/scenarios/nested-init/test.ts
··· 1 + import { join } from "path"; 2 + 3 + export async function run(project) { 4 + const apiDir = join(project.path, "src/api"); 5 + 6 + // Init at root (where package.json is) 7 + await project.init("com.myservice.*"); 8 + 9 + // Build from nested directory should work (this is what we're testing) 10 + await project.runBuildScript({ cwd: apiDir }); 11 + await project.compareTo("expected"); 12 + 13 + // Verify idempotency 14 + await project.runBuildScript({ cwd: apiDir }); 15 + await project.compareTo("expected"); 16 + }
+8
packages/cli/test/scenarios/parent-lexicons/expected1/app/package.json
··· 1 + { 2 + "name": "test-parent-lexicons", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myapp.* --out ../lexicons" 7 + } 8 + }
+10
packages/cli/test/scenarios/parent-lexicons/expected1/app/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ../lexicons (excluding com.myapp.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.atproto.label.defs { 8 + model SelfLabel { } 9 + model SelfLabels { } 10 + }
+12
packages/cli/test/scenarios/parent-lexicons/expected1/app/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myapp.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + } 12 + }
+27
packages/cli/test/scenarios/parent-lexicons/expected1/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+21
packages/cli/test/scenarios/parent-lexicons/expected1/lexicons/com/myapp/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myapp.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + } 16 + } 17 + }, 18 + "description": "My profile." 19 + } 20 + } 21 + }
+8
packages/cli/test/scenarios/parent-lexicons/expected2/app/package.json
··· 1 + { 2 + "name": "test-parent-lexicons", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myapp.* --out ../lexicons" 7 + } 8 + }
+10
packages/cli/test/scenarios/parent-lexicons/expected2/app/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ../lexicons (excluding com.myapp.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.atproto.label.defs { 8 + model SelfLabel { } 9 + model SelfLabels { } 10 + }
+13
packages/cli/test/scenarios/parent-lexicons/expected2/app/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myapp.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + labels?: com.atproto.label.defs.SelfLabels; 12 + } 13 + }
+27
packages/cli/test/scenarios/parent-lexicons/expected2/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+25
packages/cli/test/scenarios/parent-lexicons/expected2/lexicons/com/myapp/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myapp.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + }, 16 + "labels": { 17 + "type": "ref", 18 + "ref": "com.atproto.label.defs#selfLabels" 19 + } 20 + } 21 + }, 22 + "description": "My profile." 23 + } 24 + } 25 + }
+1
packages/cli/test/scenarios/parent-lexicons/project/app/package.json
··· 1 + {"name":"test-parent-lexicons","version":"1.0.0","type":"module"}
+27
packages/cli/test/scenarios/parent-lexicons/project/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+45
packages/cli/test/scenarios/parent-lexicons/test.ts
··· 1 + import { join } from "path"; 2 + 3 + export async function run(project) { 4 + const appDir = join(project.path, "app"); 5 + 6 + await project.init("com.myapp.*", { cwd: appDir }); 7 + 8 + // Verify init generated externals.tsp with existing external lexicons (before build) 9 + const externals = await project.readFile("app/typelex/externals.tsp"); 10 + if (!externals.includes("com.atproto.label.defs")) { 11 + throw new Error( 12 + "externals.tsp should contain external lexicons after init", 13 + ); 14 + } 15 + 16 + // Verify init created a working project with default main.tsp 17 + await project.runBuildScript({ cwd: appDir }); 18 + await project.compareTo("expected1"); 19 + 20 + // Edit main.tsp to add labels (simulates user editing the file) 21 + await project.writeFile( 22 + "app/typelex/main.tsp", 23 + `import "@typelex/emitter"; 24 + import "./externals.tsp"; 25 + 26 + namespace com.myapp.example.profile { 27 + /** My profile. */ 28 + @rec("literal:self") 29 + model Main { 30 + /** Free-form profile description.*/ 31 + @maxGraphemes(256) 32 + description?: string; 33 + labels?: com.atproto.label.defs.SelfLabels; 34 + } 35 + } 36 + `, 37 + ); 38 + 39 + await project.runBuildScript({ cwd: appDir }); 40 + await project.compareTo("expected2"); 41 + 42 + // Third build - verify idempotency 43 + await project.runBuildScript({ cwd: appDir }); 44 + await project.compareTo("expected2"); 45 + }
+14
packages/cli/test/scenarios/reserved-keywords/expected/lexicons/app/bsky/feed/post/record.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "app.bsky.feed.post.record", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "text": { 9 + "type": "string" 10 + } 11 + } 12 + } 13 + } 14 + }
+14
packages/cli/test/scenarios/reserved-keywords/expected/lexicons/com/atproto/server/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.server.defs", 4 + "defs": { 5 + "inviteCode": { 6 + "type": "object", 7 + "properties": { 8 + "code": { 9 + "type": "string" 10 + } 11 + } 12 + } 13 + } 14 + }
+21
packages/cli/test/scenarios/reserved-keywords/expected/lexicons/pub/leaflet/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "pub.leaflet.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + } 16 + } 17 + }, 18 + "description": "My profile." 19 + } 20 + } 21 + }
+7
packages/cli/test/scenarios/reserved-keywords/expected/package.json
··· 1 + { 2 + "name": "reserved-keywords-test", 3 + "type": "module", 4 + "scripts": { 5 + "build:typelex": "typelex compile pub.leaflet.*" 6 + } 7 + }
+14
packages/cli/test/scenarios/reserved-keywords/expected/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding pub.leaflet.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace app.bsky.feed.post.`record` { 8 + model Main { } 9 + } 10 + 11 + @external 12 + namespace com.atproto.server.defs { 13 + model InviteCode { } 14 + }
+12
packages/cli/test/scenarios/reserved-keywords/expected/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace `pub`.leaflet.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + } 12 + }
+14
packages/cli/test/scenarios/reserved-keywords/project/lexicons/app/bsky/feed/post/record.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "app.bsky.feed.post.record", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "text": { 9 + "type": "string" 10 + } 11 + } 12 + } 13 + } 14 + }
+14
packages/cli/test/scenarios/reserved-keywords/project/lexicons/com/atproto/server/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.server.defs", 4 + "defs": { 5 + "inviteCode": { 6 + "type": "object", 7 + "properties": { 8 + "code": { 9 + "type": "string" 10 + } 11 + } 12 + } 13 + } 14 + }
+4
packages/cli/test/scenarios/reserved-keywords/project/package.json
··· 1 + { 2 + "name": "reserved-keywords-test", 3 + "type": "module" 4 + }
+10
packages/cli/test/scenarios/reserved-keywords/test.ts
··· 1 + export async function run(project) { 2 + await project.init("pub.leaflet.*"); 3 + 4 + await project.runBuildScript(); 5 + await project.compareTo("expected"); 6 + 7 + // Second build - verify idempotency 8 + await project.runBuildScript(); 9 + await project.compareTo("expected"); 10 + }
+1
packages/cli/test/scenarios/validation-errors/project/package.json
··· 1 + {"name":"test-validation","version":"1.0.0","type":"module"}
+35
packages/cli/test/scenarios/validation-errors/test.ts
··· 1 + import { expect } from "vitest"; 2 + 3 + export async function run(project) { 4 + // Test: Namespace must end with .* 5 + let result = await project.runTypelex(["compile", "com.example"]); 6 + expect(result.exitCode).not.toBe(0); 7 + expect(result.output).toContain("namespace must end with .*"); 8 + 9 + // Test: Output path must end with 'lexicons' 10 + await project.writeFile("typelex/main.tsp", `import "@typelex/emitter";\nimport "./externals.tsp";\n`); 11 + await project.writeFile("typelex/externals.tsp", `import "@typelex/emitter";\n`); 12 + 13 + result = await project.runTypelex(["compile", "com.test.*", "--out", "./output"]); 14 + expect(result.exitCode).not.toBe(0); 15 + expect(result.output).toContain("Output directory must end with 'lexicons'"); 16 + 17 + // Test: main.tsp must exist 18 + await project.runCommand("rm", ["-rf", "typelex"]); 19 + result = await project.runTypelex(["compile", "com.test.*"]); 20 + expect(result.exitCode).not.toBe(0); 21 + expect(result.output).toContain("main.tsp not found"); 22 + 23 + // Test: main.tsp first line must be import "@typelex/emitter" 24 + await project.writeFile("typelex/main.tsp", `// wrong first line\nimport "./externals.tsp";\n`); 25 + await project.writeFile("typelex/externals.tsp", `import "@typelex/emitter";\n`); 26 + result = await project.runTypelex(["compile", "com.test.*"]); 27 + expect(result.exitCode).not.toBe(0); 28 + expect(result.output).toContain('main.tsp must start with: import "@typelex/emitter"'); 29 + 30 + // Test: main.tsp second line must be import "./externals.tsp" 31 + await project.writeFile("typelex/main.tsp", `import "@typelex/emitter";\n// wrong second line\n`); 32 + result = await project.runTypelex(["compile", "com.test.*"]); 33 + expect(result.exitCode).not.toBe(0); 34 + expect(result.output).toContain('Line 2 of main.tsp must be: import "./externals.tsp"'); 35 + }
+27
packages/cli/test/scenarios/with-external-lexicons/expected1/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+21
packages/cli/test/scenarios/with-external-lexicons/expected1/lexicons/com/myapp/example/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myapp.example.profile", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "key": "literal:self", 8 + "record": { 9 + "type": "object", 10 + "properties": { 11 + "description": { 12 + "type": "string", 13 + "maxGraphemes": 256, 14 + "description": "Free-form profile description." 15 + } 16 + } 17 + }, 18 + "description": "My profile." 19 + } 20 + } 21 + }
+8
packages/cli/test/scenarios/with-external-lexicons/expected1/package.json
··· 1 + { 2 + "name": "test-external-lexicons", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myapp.*" 7 + } 8 + }
+10
packages/cli/test/scenarios/with-external-lexicons/expected1/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.myapp.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.atproto.label.defs { 8 + model SelfLabel { } 9 + model SelfLabels { } 10 + }
+12
packages/cli/test/scenarios/with-external-lexicons/expected1/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myapp.example.profile { 5 + /** My profile. */ 6 + @rec("literal:self") 7 + model Main { 8 + /** Free-form profile description.*/ 9 + @maxGraphemes(256) 10 + description?: string; 11 + } 12 + }
+27
packages/cli/test/scenarios/with-external-lexicons/expected2/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+30
packages/cli/test/scenarios/with-external-lexicons/expected2/lexicons/com/myapp/profile.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.myapp.profile", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "did": { 9 + "type": "string", 10 + "format": "did" 11 + }, 12 + "handle": { 13 + "type": "string", 14 + "format": "handle" 15 + }, 16 + "displayName": { 17 + "type": "string" 18 + }, 19 + "labels": { 20 + "type": "ref", 21 + "ref": "com.atproto.label.defs#selfLabels" 22 + } 23 + }, 24 + "required": [ 25 + "did", 26 + "handle" 27 + ] 28 + } 29 + } 30 + }
+8
packages/cli/test/scenarios/with-external-lexicons/expected2/package.json
··· 1 + { 2 + "name": "test-external-lexicons", 3 + "version": "1.0.0", 4 + "type": "module", 5 + "scripts": { 6 + "build:typelex": "typelex compile com.myapp.*" 7 + } 8 + }
+10
packages/cli/test/scenarios/with-external-lexicons/expected2/typelex/externals.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + // Generated by typelex from ./lexicons (excluding com.myapp.*) 4 + // This file is auto-generated. Do not edit manually. 5 + 6 + @external 7 + namespace com.atproto.label.defs { 8 + model SelfLabel { } 9 + model SelfLabels { } 10 + }
+13
packages/cli/test/scenarios/with-external-lexicons/expected2/typelex/main.tsp
··· 1 + import "@typelex/emitter"; 2 + import "./externals.tsp"; 3 + 4 + namespace com.myapp.profile { 5 + model Main { 6 + @required did: did; 7 + @required handle: handle; 8 + displayName?: string; 9 + 10 + // Reference to external lexicon 11 + labels?: com.atproto.label.defs.SelfLabels; 12 + } 13 + }
+27
packages/cli/test/scenarios/with-external-lexicons/project/lexicons/com/atproto/label/defs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.atproto.label.defs", 4 + "defs": { 5 + "selfLabels": { 6 + "type": "object", 7 + "properties": { 8 + "values": { 9 + "type": "array", 10 + "items": { "type": "ref", "ref": "#selfLabel" }, 11 + "maxLength": 10 12 + } 13 + }, 14 + "required": ["values"] 15 + }, 16 + "selfLabel": { 17 + "type": "object", 18 + "properties": { 19 + "val": { 20 + "type": "string", 21 + "maxLength": 128 22 + } 23 + }, 24 + "required": ["val"] 25 + } 26 + } 27 + }
+1
packages/cli/test/scenarios/with-external-lexicons/project/package.json
··· 1 + {"name":"test-external-lexicons","version":"1.0.0","type":"module"}
+36
packages/cli/test/scenarios/with-external-lexicons/test.ts
··· 1 + export async function run(project) { 2 + await project.init("com.myapp.*"); 3 + 4 + // Verify init generated externals.tsp with existing external lexicons (before build) 5 + const externals = await project.readFile("typelex/externals.tsp"); 6 + if (!externals.includes("com.atproto.label.defs")) { 7 + throw new Error("externals.tsp should contain external lexicons after init"); 8 + } 9 + 10 + // Verify init created a working project with default main.tsp 11 + await project.runBuildScript(); 12 + await project.compareTo("expected1"); 13 + 14 + // Edit main.tsp to add a profile schema (simulates user editing the file) 15 + await project.writeFile("typelex/main.tsp", `import "@typelex/emitter"; 16 + import "./externals.tsp"; 17 + 18 + namespace com.myapp.profile { 19 + model Main { 20 + @required did: did; 21 + @required handle: handle; 22 + displayName?: string; 23 + 24 + // Reference to external lexicon 25 + labels?: com.atproto.label.defs.SelfLabels; 26 + } 27 + } 28 + `); 29 + 30 + await project.runBuildScript(); 31 + await project.compareTo("expected2"); 32 + 33 + // Third build - verify idempotency 34 + await project.runBuildScript(); 35 + await project.compareTo("expected2"); 36 + }
+77
packages/cli/test/scenarios.test.ts
··· 1 + import { describe, it, afterEach } from "vitest"; 2 + import { readdirSync, statSync, existsSync } from "fs"; 3 + import { readFile, readdir } from "fs/promises"; 4 + import { join, dirname, relative } from "path"; 5 + import { fileURLToPath } from "url"; 6 + import { TestProject } from "./helpers/test-project.js"; 7 + 8 + const __filename = fileURLToPath(import.meta.url); 9 + const __dirname = dirname(__filename); 10 + 11 + const SCENARIOS_DIR = join(__dirname, "scenarios"); 12 + 13 + async function copyDirRecursive(src: string, dest: string, project: TestProject) { 14 + const { mkdir } = await import("fs/promises"); 15 + const entries = await readdir(src, { withFileTypes: true }); 16 + 17 + for (const entry of entries) { 18 + const srcPath = join(src, entry.name); 19 + const destPath = join(dest, entry.name); 20 + 21 + if (entry.isDirectory()) { 22 + // Create the directory in destination (even if empty) 23 + const relativePath = relative(project.path, destPath); 24 + await mkdir(join(project.path, relativePath), { recursive: true }); 25 + await copyDirRecursive(srcPath, destPath, project); 26 + } else { 27 + const content = await readFile(srcPath, "utf-8"); 28 + const relativePath = relative(project.path, destPath); 29 + await project.writeFile(relativePath, content); 30 + } 31 + } 32 + } 33 + 34 + describe("CLI scenarios", () => { 35 + let project: TestProject; 36 + 37 + afterEach(async () => { 38 + if (project) { 39 + await project.cleanup(); 40 + } 41 + }); 42 + 43 + // Auto-discover scenario directories 44 + const scenarios = readdirSync(SCENARIOS_DIR) 45 + .map((name) => join(SCENARIOS_DIR, name)) 46 + .filter((path) => statSync(path).isDirectory()) 47 + .filter((path) => existsSync(join(path, "test.ts"))); 48 + 49 + for (const scenarioPath of scenarios) { 50 + const scenarioName = scenarioPath.split("/").pop()!; 51 + 52 + it(scenarioName, async () => { 53 + // Load test module to get config 54 + const testModule = await import(join(scenarioPath, "test.ts")); 55 + if (typeof testModule.run !== "function") { 56 + throw new Error(`${scenarioName}/test.ts must export a run() function`); 57 + } 58 + 59 + // Create project 60 + project = await TestProject.create({ 61 + packageManager: testModule.packageManager || "npm", 62 + }); 63 + project.scenarioPath = scenarioPath; 64 + 65 + // Copy project files 66 + const projectDir = join(scenarioPath, "project"); 67 + if (existsSync(projectDir)) { 68 + await copyDirRecursive(projectDir, project.path, project); 69 + } 70 + 71 + await project.mockInstall(); 72 + 73 + // Run the scenario 74 + await testModule.run(project); 75 + }); 76 + } 77 + });
+10
packages/cli/vitest.config.ts
··· 1 + import { defineConfig } from 'vitest/config'; 2 + 3 + export default defineConfig({ 4 + test: { 5 + globals: true, 6 + environment: 'node', 7 + testTimeout: 60000, // CLI operations can take time 8 + hookTimeout: 60000, 9 + }, 10 + });
+65
packages/emitter/lib/decorators.tsp
··· 163 163 extern dec errors(target: unknown, ...errors: unknown[]); 164 164 165 165 /** 166 + * Forces a model, scalar, or union to be inlined instead of creating a standalone def. 167 + * By default, named types create separate definitions with references. 168 + * Use @inline to expand the type inline at each usage site. 169 + * 170 + * @example Inline model 171 + * ```typespec 172 + * @inline 173 + * model Caption { 174 + * text?: string; 175 + * } 176 + * 177 + * model Main { 178 + * captions?: Caption[]; // Expands inline, no separate "caption" def 179 + * } 180 + * ``` 181 + * 182 + * @example Inline scalar 183 + * ```typespec 184 + * @inline 185 + * @maxLength(50) 186 + * scalar Handle extends string; 187 + * 188 + * model Main { 189 + * handle?: Handle; // Expands to { type: "string", maxLength: 50 } 190 + * } 191 + * ``` 192 + * 193 + * @example Inline union 194 + * ```typespec 195 + * @inline 196 + * union Status { "active", "inactive", string } 197 + * 198 + * model Main { 199 + * status?: Status; // Expands inline with knownValues 200 + * } 201 + * ``` 202 + */ 203 + extern dec inline(target: unknown); 204 + 205 + /** 206 + * Specifies a default value for a scalar or union definition. 207 + * Only valid on standalone scalar or union defs (not @inline). 208 + * The value must match the underlying type (string, integer, or boolean). 209 + * For unions with token refs, you can pass a model reference directly. 210 + * 211 + * @param value - The default value (literal or model reference for tokens) 212 + * 213 + * @example Scalar with default 214 + * ```typespec 215 + * @default("standard") 216 + * scalar Mode extends string; 217 + * ``` 218 + * 219 + * @example Union with token default 220 + * ```typespec 221 + * @default(Inperson) 222 + * union EventMode { Hybrid, Inperson, Virtual, string } 223 + * 224 + * @token 225 + * model Inperson {} 226 + * ``` 227 + */ 228 + extern dec `default`(target: unknown, value: unknown); 229 + 230 + /** 166 231 * Marks a namespace as external, preventing it from emitting JSON output. 167 232 * This decorator can only be applied to namespaces. 168 233 * Useful for importing definitions from other lexicons without re-emitting them.
+1 -1
packages/emitter/package.json
··· 1 1 { 2 2 "name": "@typelex/emitter", 3 - "version": "0.2.0", 3 + "version": "0.3.1", 4 4 "description": "TypeSpec emitter for ATProto Lexicon definitions", 5 5 "main": "dist/index.js", 6 6 "type": "module",
+17
packages/emitter/src/decorators.ts
··· 25 25 const maxBytesKey = Symbol("maxBytes"); 26 26 const minBytesKey = Symbol("minBytes"); 27 27 const externalKey = Symbol("external"); 28 + const defaultKey = Symbol("default"); 28 29 29 30 /** 30 31 * @maxBytes decorator for maximum length of bytes type ··· 294 295 295 296 export function isReadOnly(program: Program, target: Type): boolean { 296 297 return program.stateSet(readOnlyKey).has(target); 298 + } 299 + 300 + /** 301 + * @default decorator for setting default values on scalars and unions 302 + * The value can be a literal (string, number, boolean) or a model reference for tokens 303 + */ 304 + export function $default(context: DecoratorContext, target: Type, value: any) { 305 + // Just store the raw value - let the emitter handle unwrapping and validation 306 + context.program.stateMap(defaultKey).set(target, value); 307 + } 308 + 309 + export function getDefault( 310 + program: Program, 311 + target: Type, 312 + ): any | undefined { 313 + return program.stateMap(defaultKey).get(target); 297 314 } 298 315 299 316 /**
+286 -22
packages/emitter/src/emitter.ts
··· 48 48 LexCidLink, 49 49 LexRefVariant, 50 50 LexToken, 51 + LexBoolean, 52 + LexInteger, 53 + LexString, 51 54 } from "./types.js"; 52 55 53 56 import { ··· 68 71 getMaxBytes, 69 72 getMinBytes, 70 73 isExternal, 74 + getDefault, 71 75 } from "./decorators.js"; 72 76 73 77 export interface EmitterOptions { ··· 97 101 private program: Program, 98 102 private options: EmitterOptions, 99 103 ) {} 104 + 105 + /** 106 + * Process the raw default value from the decorator, unwrapping TypeSpec value objects 107 + * and returning either a primitive (string, number, boolean) or a Type (for model references) 108 + */ 109 + private processDefaultValue(rawValue: any): string | number | boolean | Type | undefined { 110 + if (rawValue === undefined) return undefined; 111 + 112 + // TypeSpec may wrap values - check if this is a value object first 113 + if (rawValue && typeof rawValue === 'object' && rawValue.valueKind) { 114 + if (rawValue.valueKind === "StringValue") { 115 + return rawValue.value; 116 + } else if (rawValue.valueKind === "NumericValue" || rawValue.valueKind === "NumberValue") { 117 + return rawValue.value; 118 + } else if (rawValue.valueKind === "BooleanValue") { 119 + return rawValue.value; 120 + } 121 + return undefined; // Unsupported valueKind 122 + } 123 + 124 + // Check if it's a Type object (Model, String, Number, Boolean literals) 125 + if (rawValue && typeof rawValue === 'object' && rawValue.kind) { 126 + if (rawValue.kind === "String") { 127 + return (rawValue as StringLiteral).value; 128 + } else if (rawValue.kind === "Number") { 129 + return (rawValue as NumericLiteral).value; 130 + } else if (rawValue.kind === "Boolean") { 131 + return (rawValue as BooleanLiteral).value; 132 + } else if (rawValue.kind === "Model") { 133 + // Return the model itself for token references 134 + return rawValue as Model; 135 + } 136 + return undefined; // Unsupported kind 137 + } 138 + 139 + // Direct primitive value 140 + if (typeof rawValue === 'string' || typeof rawValue === 'number' || typeof rawValue === 'boolean') { 141 + return rawValue; 142 + } 143 + 144 + return undefined; 145 + } 100 146 101 147 async emit() { 102 148 const globalNs = this.program.getGlobalNamespaceType(); ··· 356 402 } 357 403 358 404 private addScalarToDefs(lexicon: LexiconDoc, scalar: Scalar) { 405 + // Only skip if the scalar itself is in TypeSpec namespace (built-in scalars) 359 406 if (scalar.namespace?.name === "TypeSpec") return; 360 - if (scalar.baseScalar?.namespace?.name === "TypeSpec") return; 361 407 362 408 // Skip @inline scalars - they should be inlined, not defined separately 363 409 if (isInline(this.program, scalar)) { ··· 368 414 const scalarDef = this.scalarToLexiconPrimitive(scalar, undefined); 369 415 if (scalarDef) { 370 416 const description = getDoc(this.program, scalar); 371 - lexicon.defs[defName] = { ...scalarDef, description } as LexUserType; 417 + 418 + // Apply @default decorator if present 419 + const rawDefault = getDefault(this.program, scalar); 420 + const defaultValue = this.processDefaultValue(rawDefault); 421 + let defWithDefault: LexObjectProperty = { ...scalarDef }; 422 + 423 + if (defaultValue !== undefined) { 424 + // Check if it's a Type (model reference for tokens) 425 + if (typeof defaultValue === 'object' && 'kind' in defaultValue) { 426 + // For model references, we need to resolve to NSID 427 + // This shouldn't happen for scalars, only unions support token refs 428 + this.program.reportDiagnostic({ 429 + code: "invalid-default-on-scalar", 430 + severity: "error", 431 + message: "@default on scalars must be a literal value (string, number, or boolean), not a model reference", 432 + target: scalar, 433 + }); 434 + } else { 435 + // Validate that the default value matches the type 436 + this.assertValidValueForType(scalarDef.type, defaultValue, scalar); 437 + // Type-safe narrowing based on both the type discriminator and value type 438 + if (scalarDef.type === "boolean" && typeof defaultValue === "boolean") { 439 + (defWithDefault as LexBoolean).default = defaultValue; 440 + } else if (scalarDef.type === "integer" && typeof defaultValue === "number") { 441 + (defWithDefault as LexInteger).default = defaultValue; 442 + } else if (scalarDef.type === "string" && typeof defaultValue === "string") { 443 + (defWithDefault as LexString).default = defaultValue; 444 + } 445 + } 446 + } 447 + 448 + // Apply integer constraints for standalone scalar defs 449 + if (scalarDef.type === "integer") { 450 + const minValue = getMinValue(this.program, scalar); 451 + if (minValue !== undefined) { 452 + (defWithDefault as LexInteger).minimum = minValue; 453 + } 454 + const maxValue = getMaxValue(this.program, scalar); 455 + if (maxValue !== undefined) { 456 + (defWithDefault as LexInteger).maximum = maxValue; 457 + } 458 + } 459 + 460 + lexicon.defs[defName] = { ...defWithDefault, description } as LexUserType; 372 461 } 373 462 } 374 463 ··· 391 480 if (unionDef.type === "string" && (unionDef.knownValues || unionDef.enum)) { 392 481 const defName = name.charAt(0).toLowerCase() + name.slice(1); 393 482 const description = getDoc(this.program, union); 394 - lexicon.defs[defName] = { ...unionDef, description }; 483 + 484 + // Apply @default decorator if present 485 + const rawDefault = getDefault(this.program, union); 486 + const defaultValue = this.processDefaultValue(rawDefault); 487 + let defWithDefault: LexString = { ...unionDef as LexString }; 488 + 489 + if (defaultValue !== undefined) { 490 + // Check if it's a Type (model reference for tokens) 491 + if (typeof defaultValue === 'object' && 'kind' in defaultValue) { 492 + // Resolve the model reference to its NSID 493 + const tokenModel = defaultValue as Model; 494 + const tokenRef = this.getModelReference(tokenModel, true); // fullyQualified=true 495 + if (tokenRef) { 496 + defWithDefault = { ...defWithDefault, default: tokenRef }; 497 + } else { 498 + this.program.reportDiagnostic({ 499 + code: "invalid-default-token", 500 + severity: "error", 501 + message: "@default value must be a valid token model reference", 502 + target: union, 503 + }); 504 + } 505 + } else { 506 + // Literal value - validate it matches the union type 507 + if (typeof defaultValue !== "string") { 508 + this.program.reportDiagnostic({ 509 + code: "invalid-default-value-type", 510 + severity: "error", 511 + message: `Default value type mismatch: expected string, got ${typeof defaultValue}`, 512 + target: union, 513 + }); 514 + } else { 515 + defWithDefault = { ...defWithDefault, default: defaultValue }; 516 + } 517 + } 518 + } 519 + 520 + lexicon.defs[defName] = { ...defWithDefault, description }; 395 521 } else if (unionDef.type === "union") { 396 522 this.program.reportDiagnostic({ 397 523 code: "union-refs-not-allowed-as-def", ··· 401 527 `Use @inline to inline them at usage sites, use @token models for known values, or use string literals.`, 402 528 target: union, 403 529 }); 530 + } else if (unionDef.type === "integer" && (unionDef as LexInteger).enum) { 531 + // Integer enums can also be defs 532 + const defName = name.charAt(0).toLowerCase() + name.slice(1); 533 + const description = getDoc(this.program, union); 534 + 535 + // Apply @default decorator if present 536 + const rawDefault = getDefault(this.program, union); 537 + const defaultValue = this.processDefaultValue(rawDefault); 538 + let defWithDefault: LexInteger = { ...unionDef as LexInteger }; 539 + 540 + if (defaultValue !== undefined) { 541 + if (typeof defaultValue === "number") { 542 + defWithDefault = { ...defWithDefault, default: defaultValue }; 543 + } else { 544 + this.program.reportDiagnostic({ 545 + code: "invalid-default-value-type", 546 + severity: "error", 547 + message: `Default value type mismatch: expected integer, got ${typeof defaultValue}`, 548 + target: union, 549 + }); 550 + } 551 + } 552 + 553 + lexicon.defs[defName] = { ...defWithDefault, description }; 404 554 } 405 555 } 406 556 ··· 501 651 isClosed(this.program, unionType) 502 652 ) { 503 653 const propDesc = prop ? getDoc(this.program, prop) : undefined; 504 - const defaultValue = prop?.defaultValue 505 - ? serializeValueAsJson(this.program, prop.defaultValue, prop) 506 - : undefined; 654 + 655 + // Check for default value: property default takes precedence, then union's @default 656 + let defaultValue: string | number | boolean | undefined; 657 + if (prop?.defaultValue !== undefined) { 658 + defaultValue = serializeValueAsJson(this.program, prop.defaultValue, prop) as string | number | boolean; 659 + } else { 660 + // If no property default, check union's @default decorator 661 + const rawUnionDefault = getDefault(this.program, unionType); 662 + const unionDefault = this.processDefaultValue(rawUnionDefault); 663 + if (unionDefault !== undefined && typeof unionDefault === 'number') { 664 + defaultValue = unionDefault; 665 + } 666 + } 667 + 507 668 return { 508 669 type: "integer", 509 670 enum: variants.numericLiterals, ··· 526 687 ) { 527 688 const isClosedUnion = isClosed(this.program, unionType); 528 689 const propDesc = prop ? getDoc(this.program, prop) : undefined; 529 - const defaultValue = prop?.defaultValue 530 - ? serializeValueAsJson(this.program, prop.defaultValue, prop) 531 - : undefined; 690 + 691 + // Check for default value: property default takes precedence, then union's @default 692 + let defaultValue: string | number | boolean | undefined; 693 + if (prop?.defaultValue !== undefined) { 694 + defaultValue = serializeValueAsJson(this.program, prop.defaultValue, prop) as string | number | boolean; 695 + } else { 696 + // If no property default, check union's @default decorator 697 + const rawUnionDefault = getDefault(this.program, unionType); 698 + const unionDefault = this.processDefaultValue(rawUnionDefault); 699 + 700 + if (unionDefault !== undefined) { 701 + // Check if it's a Type (model reference for tokens) 702 + if (typeof unionDefault === 'object' && 'kind' in unionDefault && unionDefault.kind === 'Model') { 703 + // Resolve the model reference to its NSID 704 + const tokenModel = unionDefault as Model; 705 + const tokenRef = this.getModelReference(tokenModel, true); // fullyQualified=true 706 + if (tokenRef) { 707 + defaultValue = tokenRef; 708 + } 709 + } else if (typeof unionDefault === 'string') { 710 + defaultValue = unionDefault; 711 + } 712 + } 713 + } 714 + 532 715 const maxLength = getMaxLength(this.program, unionType); 533 716 const minLength = getMinLength(this.program, unionType); 534 717 const maxGraphemes = getMaxGraphemes(this.program, unionType); ··· 1158 1341 prop?: ModelProperty, 1159 1342 propDesc?: string, 1160 1343 ): LexObjectProperty | null { 1344 + // Check if this scalar should be referenced instead of inlined 1345 + const scalarRef = this.getScalarReference(scalar); 1346 + if (scalarRef) { 1347 + // Check if property has a default value that would conflict with the scalar's @default 1348 + if (prop?.defaultValue !== undefined) { 1349 + const scalarDefaultRaw = getDefault(this.program, scalar); 1350 + const scalarDefault = this.processDefaultValue(scalarDefaultRaw); 1351 + const propDefault = serializeValueAsJson(this.program, prop.defaultValue, prop); 1352 + 1353 + // If the scalar has a different default, or if the property has a default but the scalar doesn't, error 1354 + if (scalarDefault !== propDefault) { 1355 + this.program.reportDiagnostic({ 1356 + code: "conflicting-defaults", 1357 + severity: "error", 1358 + message: scalarDefault !== undefined 1359 + ? `Property default value conflicts with scalar's @default decorator. The scalar "${scalar.name}" has @default(${JSON.stringify(scalarDefault)}) but property has default value ${JSON.stringify(propDefault)}. Either remove the property default, mark the scalar @inline, or make the defaults match.` 1360 + : `Property has a default value but the referenced scalar "${scalar.name}" does not. Either add @default to the scalar, mark it @inline to allow property-level defaults, or remove the property default.`, 1361 + target: prop, 1362 + }); 1363 + } 1364 + } 1365 + 1366 + return { type: "ref" as const, ref: scalarRef, description: propDesc }; 1367 + } 1368 + 1369 + // Inline the scalar 1161 1370 const primitive = this.scalarToLexiconPrimitive(scalar, prop); 1162 1371 if (!primitive) return null; 1163 1372 ··· 1246 1455 if (!isDefining) { 1247 1456 const unionRef = this.getUnionReference(unionType); 1248 1457 if (unionRef) { 1458 + // Check if property has a default value that would conflict with the union's @default 1459 + if (prop?.defaultValue !== undefined) { 1460 + const unionDefaultRaw = getDefault(this.program, unionType); 1461 + const unionDefault = this.processDefaultValue(unionDefaultRaw); 1462 + const propDefault = serializeValueAsJson(this.program, prop.defaultValue, prop); 1463 + 1464 + // For union defaults that are model references, we need to resolve them for comparison 1465 + let resolvedUnionDefault: string | number | boolean | undefined; 1466 + if (unionDefault && typeof unionDefault === 'object' && 'kind' in unionDefault && unionDefault.kind === 'Model') { 1467 + const ref = this.getModelReference(unionDefault as Model, true); 1468 + resolvedUnionDefault = ref || undefined; 1469 + } else { 1470 + resolvedUnionDefault = unionDefault as string | number | boolean; 1471 + } 1472 + 1473 + // If the union has a different default, or if the property has a default but the union doesn't, error 1474 + if (resolvedUnionDefault !== propDefault) { 1475 + this.program.reportDiagnostic({ 1476 + code: "conflicting-defaults", 1477 + severity: "error", 1478 + message: unionDefault !== undefined 1479 + ? `Property default value conflicts with union's @default decorator. The union "${unionType.name}" has @default(${JSON.stringify(resolvedUnionDefault)}) but property has default value ${JSON.stringify(propDefault)}. Either remove the property default, mark the union @inline, or make the defaults match.` 1480 + : `Property has a default value but the referenced union "${unionType.name}" does not. Either add @default to the union, mark it @inline to allow property-level defaults, or remove the property default.`, 1481 + target: prop, 1482 + }); 1483 + } 1484 + } 1485 + 1249 1486 return { type: "ref" as const, ref: unionRef, description: propDesc }; 1250 1487 } 1251 1488 } ··· 1271 1508 // Check if this scalar (or its base) is bytes type 1272 1509 if (this.isScalarOfType(scalar, "bytes")) { 1273 1510 const byteDef: LexBytes = { type: "bytes" }; 1274 - const target = prop || scalar; 1275 1511 1276 - const minLength = getMinBytes(this.program, target); 1512 + // Check scalar first for its own constraints, then property overrides 1513 + const minLength = getMinBytes(this.program, scalar) ?? (prop ? getMinBytes(this.program, prop) : undefined); 1277 1514 if (minLength !== undefined) { 1278 1515 byteDef.minLength = minLength; 1279 1516 } 1280 1517 1281 - const maxLength = getMaxBytes(this.program, target); 1518 + const maxLength = getMaxBytes(this.program, scalar) ?? (prop ? getMaxBytes(this.program, prop) : undefined); 1282 1519 if (maxLength !== undefined) { 1283 1520 byteDef.maxLength = maxLength; 1284 1521 } ··· 1310 1547 1311 1548 // Apply string constraints 1312 1549 if (primitive.type === "string") { 1313 - const target = prop || scalar; 1314 - const maxLength = getMaxLength(this.program, target); 1550 + // Check scalar first for its own constraints, then property overrides 1551 + const maxLength = getMaxLength(this.program, scalar) ?? (prop ? getMaxLength(this.program, prop) : undefined); 1315 1552 if (maxLength !== undefined) { 1316 1553 primitive.maxLength = maxLength; 1317 1554 } 1318 - const minLength = getMinLength(this.program, target); 1555 + const minLength = getMinLength(this.program, scalar) ?? (prop ? getMinLength(this.program, prop) : undefined); 1319 1556 if (minLength !== undefined) { 1320 1557 primitive.minLength = minLength; 1321 1558 } 1322 - const maxGraphemes = getMaxGraphemes(this.program, target); 1559 + const maxGraphemes = getMaxGraphemes(this.program, scalar) ?? (prop ? getMaxGraphemes(this.program, prop) : undefined); 1323 1560 if (maxGraphemes !== undefined) { 1324 1561 primitive.maxGraphemes = maxGraphemes; 1325 1562 } 1326 - const minGraphemes = getMinGraphemes(this.program, target); 1563 + const minGraphemes = getMinGraphemes(this.program, scalar) ?? (prop ? getMinGraphemes(this.program, prop) : undefined); 1327 1564 if (minGraphemes !== undefined) { 1328 1565 primitive.minGraphemes = minGraphemes; 1329 1566 } 1330 1567 } 1331 1568 1332 1569 // Apply numeric constraints 1333 - if (prop && primitive.type === "integer") { 1334 - const minValue = getMinValue(this.program, prop); 1570 + if (primitive.type === "integer") { 1571 + // Check scalar first for its own constraints, then property overrides 1572 + const minValue = getMinValue(this.program, scalar) ?? (prop ? getMinValue(this.program, prop) : undefined); 1335 1573 if (minValue !== undefined) { 1336 1574 primitive.minimum = minValue; 1337 1575 } 1338 - const maxValue = getMaxValue(this.program, prop); 1576 + const maxValue = getMaxValue(this.program, scalar) ?? (prop ? getMaxValue(this.program, prop) : undefined); 1339 1577 if (maxValue !== undefined) { 1340 1578 primitive.maximum = maxValue; 1341 1579 } ··· 1431 1669 private assertValidValueForType( 1432 1670 primitiveType: string, 1433 1671 value: unknown, 1434 - prop: ModelProperty, 1672 + target: ModelProperty | Scalar | Union, 1435 1673 ): void { 1436 1674 const valid = 1437 1675 (primitiveType === "boolean" && typeof value === "boolean") || ··· 1442 1680 code: "invalid-default-value-type", 1443 1681 severity: "error", 1444 1682 message: `Default value type mismatch: expected ${primitiveType}, got ${typeof value}`, 1445 - target: prop, 1683 + target: target, 1446 1684 }); 1447 1685 } 1448 1686 } ··· 1507 1745 1508 1746 private getUnionReference(union: Union): string | null { 1509 1747 return this.getReference(union, union.name, union.namespace); 1748 + } 1749 + 1750 + private getScalarReference(scalar: Scalar): string | null { 1751 + // Built-in TypeSpec scalars (string, integer, boolean themselves) should not be referenced 1752 + if (scalar.namespace?.name === "TypeSpec") return null; 1753 + 1754 + // @inline scalars should be inlined, not referenced 1755 + if (isInline(this.program, scalar)) return null; 1756 + 1757 + // Scalars without names or namespace can't be referenced 1758 + if (!scalar.name || !scalar.namespace) return null; 1759 + 1760 + const defName = scalar.name.charAt(0).toLowerCase() + scalar.name.slice(1); 1761 + const namespaceName = getNamespaceFullName(scalar.namespace); 1762 + if (!namespaceName) return null; 1763 + 1764 + // Local reference (same namespace) - use short ref 1765 + if ( 1766 + this.currentLexiconId === namespaceName || 1767 + this.currentLexiconId === `${namespaceName}.defs` 1768 + ) { 1769 + return `#${defName}`; 1770 + } 1771 + 1772 + // Cross-namespace reference 1773 + return `${namespaceName}#${defName}`; 1510 1774 } 1511 1775 1512 1776 private modelToLexiconArray(
+2
packages/emitter/src/tsp-index.ts
··· 15 15 $maxBytes, 16 16 $minBytes, 17 17 $external, 18 + $default, 18 19 } from "./decorators.js"; 19 20 20 21 /** @internal */ ··· 36 37 maxBytes: $maxBytes, 37 38 minBytes: $minBytes, 38 39 external: $external, 40 + default: $default, 39 41 }, 40 42 };
+2
packages/emitter/test/integration/atproto/input/app/bsky/actor/defs.tsp
··· 232 232 prioritizeFollowedUsers?: boolean; 233 233 } 234 234 235 + @inline 235 236 @maxLength(640) 236 237 @maxGraphemes(64) 237 238 scalar InterestTag extends string; ··· 292 293 @required did: did; 293 294 } 294 295 296 + @inline 295 297 @maxLength(100) 296 298 scalar NudgeToken extends string; 297 299
+14
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/bookmarks/bookmark.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.bookmarks.bookmark { 4 + /** Record bookmarking a link to come back to later. */ 5 + @rec("tid") 6 + model Main { 7 + @required subject: uri; 8 + 9 + @required createdAt: datetime; 10 + 11 + /** Tags for content the bookmark may be related to, for example 'news' or 'funny videos' */ 12 + tags?: string[]; 13 + } 14 + }
+27
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/bookmarks/getActorBookmarks.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.bookmarks.getActorBookmarks { 4 + /** Get a list of bookmarks by actor. Optionally add a list of tags to include, default will be all bookmarks. Requires auth, actor must be the requesting account. */ 5 + @query 6 + op main( 7 + tags?: string[], 8 + 9 + @minValue(1) 10 + @maxValue(100) 11 + limit?: int32 = 50, 12 + 13 + cursor?: string, 14 + ): { 15 + @required 16 + bookmarks: community.lexicon.bookmarks.bookmark.Main[]; 17 + 18 + cursor?: string; 19 + }; 20 + } 21 + 22 + // --- Externals --- 23 + 24 + @external 25 + namespace community.lexicon.bookmarks.bookmark { 26 + model Main {} 27 + }
+125
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/calendar/event.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.calendar.event { 4 + /** A calendar event. */ 5 + @rec("tid") 6 + model Main { 7 + /** The name of the event. */ 8 + @required 9 + name: string; 10 + 11 + /** The description of the event. */ 12 + description?: string; 13 + 14 + /** Client-declared timestamp when the event was created. */ 15 + @required 16 + createdAt: datetime; 17 + 18 + /** Client-declared timestamp when the event starts. */ 19 + startsAt?: datetime; 20 + 21 + /** Client-declared timestamp when the event ends. */ 22 + endsAt?: datetime; 23 + 24 + /** The attendance mode of the event. */ 25 + mode?: Mode; 26 + 27 + /** The status of the event. */ 28 + status?: Status; 29 + 30 + /** The locations where the event takes place. */ 31 + locations?: ( 32 + | Uri 33 + | community.lexicon.location.address.Main 34 + | community.lexicon.location.fsq.Main 35 + | community.lexicon.location.geo.Main 36 + | community.lexicon.location.hthree.Main 37 + )[]; 38 + 39 + /** URIs associated with the event. */ 40 + uris?: Uri[]; 41 + } 42 + 43 + /** The mode of the event. */ 44 + @default(Inperson) 45 + union Mode { 46 + Hybrid, 47 + Inperson, 48 + Virtual, 49 + string, 50 + } 51 + 52 + /** A virtual event that takes place online. */ 53 + @token 54 + model Virtual {} 55 + 56 + /** An in-person event that takes place offline. */ 57 + @token 58 + model Inperson {} 59 + 60 + /** A hybrid event that takes place both online and offline. */ 61 + @token 62 + model Hybrid {} 63 + 64 + /** The status of the event. */ 65 + @default(Scheduled) 66 + union Status { 67 + Cancelled, 68 + Planned, 69 + Postponed, 70 + Rescheduled, 71 + Scheduled, 72 + string, 73 + } 74 + 75 + /** The event has been created, but not finalized. */ 76 + @token 77 + model Planned {} 78 + 79 + /** The event has been created and scheduled. */ 80 + @token 81 + model Scheduled {} 82 + 83 + /** The event has been rescheduled. */ 84 + @token 85 + model Rescheduled {} 86 + 87 + /** The event has been cancelled. */ 88 + @token 89 + model Cancelled {} 90 + 91 + /** The event has been postponed and a new start date has not been set. */ 92 + @token 93 + model Postponed {} 94 + 95 + /** A URI associated with the event. */ 96 + model Uri { 97 + @required 98 + uri: uri; 99 + 100 + /** The display name of the URI. */ 101 + name?: string; 102 + } 103 + } 104 + 105 + // --- Externals --- 106 + 107 + @external 108 + namespace community.lexicon.location.address { 109 + model Main {} 110 + } 111 + 112 + @external 113 + namespace community.lexicon.location.fsq { 114 + model Main {} 115 + } 116 + 117 + @external 118 + namespace community.lexicon.location.geo { 119 + model Main {} 120 + } 121 + 122 + @external 123 + namespace community.lexicon.location.hthree { 124 + model Main {} 125 + }
+41
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/calendar/rsvp.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.calendar.rsvp { 4 + /** An RSVP for an event. */ 5 + @rec("tid") 6 + model Main { 7 + @required 8 + subject: `com`.atproto.repo.strongRef.Main; 9 + 10 + @required 11 + status: Status; 12 + } 13 + 14 + @inline 15 + @default(Going) 16 + union Status { 17 + Interested, 18 + Going, 19 + Notgoing, 20 + string, 21 + } 22 + 23 + /** Interested in the event */ 24 + @token 25 + model Interested {} 26 + 27 + /** Going to the event */ 28 + @token 29 + model Going {} 30 + 31 + /** Not going to the event */ 32 + @token 33 + model Notgoing {} 34 + } 35 + 36 + // --- Externals --- 37 + 38 + @external 39 + namespace `com`.atproto.repo.strongRef { 40 + model Main {} 41 + }
+20
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/interaction/like.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.interaction.like { 4 + /** A 'like' interaction with another AT Protocol record. */ 5 + @rec("tid") 6 + model Main { 7 + @required 8 + subject: com.atproto.repo.strongRef.Main; 9 + 10 + @required 11 + createdAt: datetime; 12 + } 13 + } 14 + 15 + // --- Externals --- 16 + 17 + @external 18 + namespace com.atproto.repo.strongRef { 19 + model Main {} 20 + }
+27
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/location/address.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.location.address { 4 + /** A physical location in the form of a street address. */ 5 + model Main { 6 + /** The ISO 3166 country code. Preferably the 2-letter code. */ 7 + @required 8 + @minLength(2) 9 + @maxLength(10) 10 + country: string; 11 + 12 + /** The postal code of the location. */ 13 + postalCode?: string; 14 + 15 + /** The administrative region of the country. For example, a state in the USA. */ 16 + region?: string; 17 + 18 + /** The locality of the region. For example, a city in the USA. */ 19 + locality?: string; 20 + 21 + /** The street address. */ 22 + street?: string; 23 + 24 + /** The name of the location. */ 25 + name?: string; 26 + } 27 + }
+15
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/location/fsq.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.location.fsq { 4 + /** A physical location contained in the Foursquare Open Source Places dataset. */ 5 + model Main { 6 + /** The unique identifier of a Foursquare POI. */ 7 + @required fsq_place_id: string; 8 + 9 + latitude?: string; 10 + longitude?: string; 11 + 12 + /** The name of the location. */ 13 + name?: string; 14 + } 15 + }
+13
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/location/geo.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.location.geo { 4 + /** A physical location in the form of a WGS84 coordinate. */ 5 + model Main { 6 + @required latitude: string; 7 + @required longitude: string; 8 + altitude?: string; 9 + 10 + /** The name of the location. */ 11 + name?: string; 12 + } 13 + }
+12
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/location/hthree.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace community.lexicon.location.hthree { 4 + /** A physical location in the form of a H3 encoded location. */ 5 + model Main { 6 + /** The h3 encoded location. */ 7 + @required value: string; 8 + 9 + /** The name of the location. */ 10 + name?: string; 11 + } 12 + }
+14
packages/emitter/test/integration/lexicon-examples/input/community/lexicon/payments/webMonetization.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + /** Web Monetization integration: https://webmonetization.org/ */ 4 + namespace community.lexicon.payments.webMonetization { 5 + /** Web Monetization wallet. */ 6 + @rec("any") 7 + model Main { 8 + /** Wallet address. */ 9 + @required address: uri; 10 + 11 + /** Short, human-readable description of how this wallet is related to this account. */ 12 + note?: string; 13 + } 14 + }
+35
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/bookmarks/bookmark.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.bookmarks.bookmark", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "description": "Record bookmarking a link to come back to later.", 8 + "key": "tid", 9 + "record": { 10 + "type": "object", 11 + "required": [ 12 + "subject", 13 + "createdAt" 14 + ], 15 + "properties": { 16 + "subject": { 17 + "type": "string", 18 + "format": "uri" 19 + }, 20 + "createdAt": { 21 + "type": "string", 22 + "format": "datetime" 23 + }, 24 + "tags": { 25 + "type": "array", 26 + "description": "Tags for content the bookmark may be related to, for example 'news' or 'funny videos'", 27 + "items": { 28 + "type": "string" 29 + } 30 + } 31 + } 32 + } 33 + } 34 + } 35 + }
+51
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/bookmarks/getActorBookmarks.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.bookmarks.getActorBookmarks", 4 + "defs": { 5 + "main": { 6 + "type": "query", 7 + "description": "Get a list of bookmarks by actor. Optionally add a list of tags to include, default will be all bookmarks. Requires auth, actor must be the requesting account.", 8 + "parameters": { 9 + "type": "params", 10 + "properties": { 11 + "tags": { 12 + "type": "array", 13 + "items": { 14 + "type": "string" 15 + } 16 + }, 17 + "limit": { 18 + "type": "integer", 19 + "minimum": 1, 20 + "maximum": 100, 21 + "default": 50 22 + }, 23 + "cursor": { 24 + "type": "string" 25 + } 26 + } 27 + }, 28 + "output": { 29 + "encoding": "application/json", 30 + "schema": { 31 + "type": "object", 32 + "required": [ 33 + "bookmarks" 34 + ], 35 + "properties": { 36 + "cursor": { 37 + "type": "string" 38 + }, 39 + "bookmarks": { 40 + "type": "array", 41 + "items": { 42 + "type": "ref", 43 + "ref": "community.lexicon.bookmarks.bookmark" 44 + } 45 + } 46 + } 47 + } 48 + } 49 + } 50 + } 51 + }
+146
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/calendar/event.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.calendar.event", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "description": "A calendar event.", 8 + "key": "tid", 9 + "record": { 10 + "type": "object", 11 + "required": [ 12 + "name", 13 + "createdAt" 14 + ], 15 + "properties": { 16 + "name": { 17 + "type": "string", 18 + "description": "The name of the event." 19 + }, 20 + "description": { 21 + "type": "string", 22 + "description": "The description of the event." 23 + }, 24 + "createdAt": { 25 + "type": "string", 26 + "format": "datetime", 27 + "description": "Client-declared timestamp when the event was created." 28 + }, 29 + "startsAt": { 30 + "type": "string", 31 + "format": "datetime", 32 + "description": "Client-declared timestamp when the event starts." 33 + }, 34 + "endsAt": { 35 + "type": "string", 36 + "format": "datetime", 37 + "description": "Client-declared timestamp when the event ends." 38 + }, 39 + "mode": { 40 + "type": "ref", 41 + "ref": "#mode", 42 + "description": "The attendance mode of the event." 43 + }, 44 + "status": { 45 + "type": "ref", 46 + "ref": "#status", 47 + "description": "The status of the event." 48 + }, 49 + "locations": { 50 + "type": "array", 51 + "description": "The locations where the event takes place.", 52 + "items": { 53 + "type": "union", 54 + "refs": [ 55 + "#uri", 56 + "community.lexicon.location.address", 57 + "community.lexicon.location.fsq", 58 + "community.lexicon.location.geo", 59 + "community.lexicon.location.hthree" 60 + ] 61 + } 62 + }, 63 + "uris": { 64 + "type": "array", 65 + "description": "URIs associated with the event.", 66 + "items": { 67 + "type": "ref", 68 + "ref": "#uri" 69 + } 70 + } 71 + } 72 + } 73 + }, 74 + "mode": { 75 + "type": "string", 76 + "description": "The mode of the event.", 77 + "default": "community.lexicon.calendar.event#inperson", 78 + "knownValues": [ 79 + "community.lexicon.calendar.event#hybrid", 80 + "community.lexicon.calendar.event#inperson", 81 + "community.lexicon.calendar.event#virtual" 82 + ] 83 + }, 84 + "virtual": { 85 + "type": "token", 86 + "description": "A virtual event that takes place online." 87 + }, 88 + "inperson": { 89 + "type": "token", 90 + "description": "An in-person event that takes place offline." 91 + }, 92 + "hybrid": { 93 + "type": "token", 94 + "description": "A hybrid event that takes place both online and offline." 95 + }, 96 + "status": { 97 + "type": "string", 98 + "description": "The status of the event.", 99 + "default": "community.lexicon.calendar.event#scheduled", 100 + "knownValues": [ 101 + "community.lexicon.calendar.event#cancelled", 102 + "community.lexicon.calendar.event#planned", 103 + "community.lexicon.calendar.event#postponed", 104 + "community.lexicon.calendar.event#rescheduled", 105 + "community.lexicon.calendar.event#scheduled" 106 + ] 107 + }, 108 + "planned": { 109 + "type": "token", 110 + "description": "The event has been created, but not finalized." 111 + }, 112 + "scheduled": { 113 + "type": "token", 114 + "description": "The event has been created and scheduled." 115 + }, 116 + "rescheduled": { 117 + "type": "token", 118 + "description": "The event has been rescheduled." 119 + }, 120 + "cancelled": { 121 + "type": "token", 122 + "description": "The event has been cancelled." 123 + }, 124 + "postponed": { 125 + "type": "token", 126 + "description": "The event has been postponed and a new start date has not been set." 127 + }, 128 + "uri": { 129 + "type": "object", 130 + "description": "A URI associated with the event.", 131 + "required": [ 132 + "uri" 133 + ], 134 + "properties": { 135 + "uri": { 136 + "type": "string", 137 + "format": "uri" 138 + }, 139 + "name": { 140 + "type": "string", 141 + "description": "The display name of the URI." 142 + } 143 + } 144 + } 145 + } 146 + }
+45
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/calendar/rsvp.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.calendar.rsvp", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "description": "An RSVP for an event.", 8 + "key": "tid", 9 + "record": { 10 + "type": "object", 11 + "required": [ 12 + "subject", 13 + "status" 14 + ], 15 + "properties": { 16 + "subject": { 17 + "type": "ref", 18 + "ref": "com.atproto.repo.strongRef" 19 + }, 20 + "status": { 21 + "type": "string", 22 + "default": "community.lexicon.calendar.rsvp#going", 23 + "knownValues": [ 24 + "community.lexicon.calendar.rsvp#interested", 25 + "community.lexicon.calendar.rsvp#going", 26 + "community.lexicon.calendar.rsvp#notgoing" 27 + ] 28 + } 29 + } 30 + } 31 + }, 32 + "interested": { 33 + "type": "token", 34 + "description": "Interested in the event" 35 + }, 36 + "going": { 37 + "type": "token", 38 + "description": "Going to the event" 39 + }, 40 + "notgoing": { 41 + "type": "token", 42 + "description": "Not going to the event" 43 + } 44 + } 45 + }
+28
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/interaction/like.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.interaction.like", 4 + "defs": { 5 + "main": { 6 + "type": "record", 7 + "description": "A 'like' interaction with another AT Protocol record.", 8 + "key": "tid", 9 + "record": { 10 + "type": "object", 11 + "required": [ 12 + "subject", 13 + "createdAt" 14 + ], 15 + "properties": { 16 + "subject": { 17 + "type": "ref", 18 + "ref": "com.atproto.repo.strongRef" 19 + }, 20 + "createdAt": { 21 + "type": "string", 22 + "format": "datetime" 23 + } 24 + } 25 + } 26 + } 27 + } 28 + }
+41
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/location/address.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.location.address", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "description": "A physical location in the form of a street address.", 8 + "required": [ 9 + "country" 10 + ], 11 + "properties": { 12 + "country": { 13 + "type": "string", 14 + "description": "The ISO 3166 country code. Preferably the 2-letter code.", 15 + "minLength": 2, 16 + "maxLength": 10 17 + }, 18 + "postalCode": { 19 + "type": "string", 20 + "description": "The postal code of the location." 21 + }, 22 + "region": { 23 + "type": "string", 24 + "description": "The administrative region of the country. For example, a state in the USA." 25 + }, 26 + "locality": { 27 + "type": "string", 28 + "description": "The locality of the region. For example, a city in the USA." 29 + }, 30 + "street": { 31 + "type": "string", 32 + "description": "The street address." 33 + }, 34 + "name": { 35 + "type": "string", 36 + "description": "The name of the location." 37 + } 38 + } 39 + } 40 + } 41 + }
+29
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/location/fsq.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.location.fsq", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "description": "A physical location contained in the Foursquare Open Source Places dataset.", 8 + "required": [ 9 + "fsq_place_id" 10 + ], 11 + "properties": { 12 + "fsq_place_id": { 13 + "type": "string", 14 + "description": "The unique identifier of a Foursquare POI." 15 + }, 16 + "latitude": { 17 + "type": "string" 18 + }, 19 + "longitude": { 20 + "type": "string" 21 + }, 22 + "name": { 23 + "type": "string", 24 + "description": "The name of the location." 25 + } 26 + } 27 + } 28 + } 29 + }
+29
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/location/geo.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.location.geo", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "description": "A physical location in the form of a WGS84 coordinate.", 8 + "required": [ 9 + "latitude", 10 + "longitude" 11 + ], 12 + "properties": { 13 + "latitude": { 14 + "type": "string" 15 + }, 16 + "longitude": { 17 + "type": "string" 18 + }, 19 + "altitude": { 20 + "type": "string" 21 + }, 22 + "name": { 23 + "type": "string", 24 + "description": "The name of the location." 25 + } 26 + } 27 + } 28 + } 29 + }
+23
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/location/hthree.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.location.hthree", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "description": "A physical location in the form of a H3 encoded location.", 8 + "required": [ 9 + "value" 10 + ], 11 + "properties": { 12 + "value": { 13 + "type": "string", 14 + "description": "The h3 encoded location." 15 + }, 16 + "name": { 17 + "type": "string", 18 + "description": "The name of the location." 19 + } 20 + } 21 + } 22 + } 23 + }
+27
packages/emitter/test/integration/lexicon-examples/output/community/lexicon/payments/webMonetization.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "community.lexicon.payments.webMonetization", 4 + "description": "Web Monetization integration: https://webmonetization.org/", 5 + "defs": { 6 + "main": { 7 + "type": "record", 8 + "description": "Web Monetization wallet.", 9 + "key": "any", 10 + "record": { 11 + "type": "object", 12 + "required": ["address"], 13 + "properties": { 14 + "address": { 15 + "type": "string", 16 + "format": "uri", 17 + "description": "Wallet address." 18 + }, 19 + "note": { 20 + "type": "string", 21 + "description": "Short, human-readable description of how this wallet is related to this account." 22 + } 23 + } 24 + } 25 + } 26 + } 27 + }
+30
packages/emitter/test/spec/basic/input/com/example/scalarDefaults.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace com.example.scalarDefaults { 4 + /** Test default decorator on scalars */ 5 + model Main { 6 + /** Uses string scalar with default */ 7 + mode?: Mode; 8 + 9 + /** Uses integer scalar with default */ 10 + limit?: Limit; 11 + 12 + /** Uses boolean scalar with default */ 13 + enabled?: Enabled; 14 + } 15 + 16 + /** A string type with a default value */ 17 + @default("standard") 18 + @maxLength(50) 19 + scalar Mode extends string; 20 + 21 + /** An integer type with a default value */ 22 + @default(50) 23 + @minValue(1) 24 + @maxValue(100) 25 + scalar Limit extends integer; 26 + 27 + /** A boolean type with a default value */ 28 + @default(true) 29 + scalar Enabled extends boolean; 30 + }
+22
packages/emitter/test/spec/basic/input/com/example/scalarDefs.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace com.example.scalarDefs { 4 + /** Scalar defs should create standalone defs like models and unions */ 5 + model Main { 6 + /** Uses a custom string scalar with constraints */ 7 + tag?: Tag; 8 + 9 + /** Uses a custom integer scalar with constraints */ 10 + count?: Count; 11 + } 12 + 13 + /** A custom string type with length constraints */ 14 + @maxLength(100) 15 + @maxGraphemes(50) 16 + scalar Tag extends string; 17 + 18 + /** A custom integer type with value constraints */ 19 + @minValue(1) 20 + @maxValue(100) 21 + scalar Count extends integer; 22 + }
+22
packages/emitter/test/spec/basic/input/com/example/scalarInline.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace com.example.scalarInline { 4 + /** Test inline decorator on scalars */ 5 + model Main { 6 + /** Inline scalar - should not create a def */ 7 + tag?: Tag; 8 + 9 + /** Non-inline scalar - should create a def */ 10 + category?: Category; 11 + } 12 + 13 + /** An inline scalar should be inlined at usage sites */ 14 + @inline 15 + @maxLength(50) 16 + @maxGraphemes(25) 17 + scalar Tag extends string; 18 + 19 + /** A regular scalar should create a standalone def */ 20 + @maxLength(100) 21 + scalar Category extends string; 22 + }
+53
packages/emitter/test/spec/basic/input/com/example/unionDefaults.tsp
··· 1 + import "@typelex/emitter"; 2 + 3 + namespace com.example.unionDefaults { 4 + /** Test default decorator on unions */ 5 + model Main { 6 + /** Union with token refs and default */ 7 + eventMode?: EventMode; 8 + 9 + /** Union with string literals and default */ 10 + sortOrder?: SortOrder; 11 + 12 + /** Union with integer literals and default */ 13 + priority?: Priority; 14 + } 15 + 16 + /** Union of tokens with default pointing to a token */ 17 + @default(Inperson) 18 + union EventMode { 19 + Hybrid, 20 + Inperson, 21 + Virtual, 22 + string, 23 + } 24 + 25 + /** A hybrid event */ 26 + @token 27 + model Hybrid {} 28 + 29 + /** An in-person event */ 30 + @token 31 + model Inperson {} 32 + 33 + /** A virtual event */ 34 + @token 35 + model Virtual {} 36 + 37 + /** Union of string literals with default */ 38 + @default("asc") 39 + union SortOrder { 40 + "asc", 41 + "desc", 42 + string, 43 + } 44 + 45 + /** Union of integer literals with default (closed enum) */ 46 + @default(1) 47 + @closed 48 + union Priority { 49 + 1, 50 + 2, 51 + 3, 52 + } 53 + }
+45
packages/emitter/test/spec/basic/output/com/example/scalarDefaults.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.example.scalarDefaults", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "mode": { 9 + "type": "ref", 10 + "ref": "#mode", 11 + "description": "Uses string scalar with default" 12 + }, 13 + "limit": { 14 + "type": "ref", 15 + "ref": "#limit", 16 + "description": "Uses integer scalar with default" 17 + }, 18 + "enabled": { 19 + "type": "ref", 20 + "ref": "#enabled", 21 + "description": "Uses boolean scalar with default" 22 + } 23 + }, 24 + "description": "Test default decorator on scalars" 25 + }, 26 + "mode": { 27 + "type": "string", 28 + "maxLength": 50, 29 + "default": "standard", 30 + "description": "A string type with a default value" 31 + }, 32 + "limit": { 33 + "type": "integer", 34 + "minimum": 1, 35 + "maximum": 100, 36 + "default": 50, 37 + "description": "An integer type with a default value" 38 + }, 39 + "enabled": { 40 + "type": "boolean", 41 + "default": true, 42 + "description": "A boolean type with a default value" 43 + } 44 + } 45 + }
+34
packages/emitter/test/spec/basic/output/com/example/scalarDefs.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.example.scalarDefs", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "tag": { 9 + "type": "ref", 10 + "ref": "#tag", 11 + "description": "Uses a custom string scalar with constraints" 12 + }, 13 + "count": { 14 + "type": "ref", 15 + "ref": "#count", 16 + "description": "Uses a custom integer scalar with constraints" 17 + } 18 + }, 19 + "description": "Scalar defs should create standalone defs like models and unions" 20 + }, 21 + "tag": { 22 + "type": "string", 23 + "maxLength": 100, 24 + "maxGraphemes": 50, 25 + "description": "A custom string type with length constraints" 26 + }, 27 + "count": { 28 + "type": "integer", 29 + "minimum": 1, 30 + "maximum": 100, 31 + "description": "A custom integer type with value constraints" 32 + } 33 + } 34 + }
+28
packages/emitter/test/spec/basic/output/com/example/scalarInline.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.example.scalarInline", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "tag": { 9 + "type": "string", 10 + "maxLength": 50, 11 + "maxGraphemes": 25, 12 + "description": "Inline scalar - should not create a def" 13 + }, 14 + "category": { 15 + "type": "ref", 16 + "ref": "#category", 17 + "description": "Non-inline scalar - should create a def" 18 + } 19 + }, 20 + "description": "Test inline decorator on scalars" 21 + }, 22 + "category": { 23 + "type": "string", 24 + "maxLength": 100, 25 + "description": "A regular scalar should create a standalone def" 26 + } 27 + } 28 + }
+61
packages/emitter/test/spec/basic/output/com/example/unionDefaults.json
··· 1 + { 2 + "lexicon": 1, 3 + "id": "com.example.unionDefaults", 4 + "defs": { 5 + "main": { 6 + "type": "object", 7 + "properties": { 8 + "eventMode": { 9 + "type": "ref", 10 + "ref": "#eventMode", 11 + "description": "Union with token refs and default" 12 + }, 13 + "sortOrder": { 14 + "type": "ref", 15 + "ref": "#sortOrder", 16 + "description": "Union with string literals and default" 17 + }, 18 + "priority": { 19 + "type": "ref", 20 + "ref": "#priority", 21 + "description": "Union with integer literals and default" 22 + } 23 + }, 24 + "description": "Test default decorator on unions" 25 + }, 26 + "eventMode": { 27 + "type": "string", 28 + "knownValues": [ 29 + "com.example.unionDefaults#hybrid", 30 + "com.example.unionDefaults#inperson", 31 + "com.example.unionDefaults#virtual" 32 + ], 33 + "default": "com.example.unionDefaults#inperson", 34 + "description": "Union of tokens with default pointing to a token" 35 + }, 36 + "hybrid": { 37 + "type": "token", 38 + "description": "A hybrid event" 39 + }, 40 + "inperson": { 41 + "type": "token", 42 + "description": "An in-person event" 43 + }, 44 + "virtual": { 45 + "type": "token", 46 + "description": "A virtual event" 47 + }, 48 + "sortOrder": { 49 + "type": "string", 50 + "knownValues": ["asc", "desc"], 51 + "default": "asc", 52 + "description": "Union of string literals with default" 53 + }, 54 + "priority": { 55 + "type": "integer", 56 + "enum": [1, 2, 3], 57 + "default": 1, 58 + "description": "Union of integer literals with default (closed enum)" 59 + } 60 + } 61 + }
+1
packages/website/package.json
··· 1 1 { 2 2 "name": "website", 3 3 "type": "module", 4 + "private": true, 4 5 "version": "0.0.1", 5 6 "scripts": { 6 7 "dev": "astro dev",
+14
packages/website/src/components/CodeBlock.astro
··· 1 + --- 2 + import { highlightCode } from '../utils/shiki'; 3 + 4 + interface Props { 5 + lang: 'typespec' | 'json' | 'bash'; 6 + code?: string; 7 + } 8 + 9 + const { lang, code } = Astro.props; 10 + const codeContent = code || await Astro.slots.render('default'); 11 + const highlighted = await highlightCode(codeContent.trim(), lang); 12 + --- 13 + 14 + <pre set:html={highlighted} />
+62
packages/website/src/components/ComparisonBlock.astro
··· 1 + --- 2 + import { highlightCode } from '../utils/shiki'; 3 + import { compileToJson } from '../utils/compile'; 4 + import { createPlaygroundUrl } from '../utils/playground-url'; 5 + import stringify from 'json-stringify-pretty-compact'; 6 + import { mkdtempSync, writeFileSync, rmSync } from 'fs'; 7 + import { join } from 'path'; 8 + import { tmpdir } from 'os'; 9 + 10 + interface Props { 11 + code: string; 12 + hero?: boolean; 13 + } 14 + 15 + const { code, hero = false } = Astro.props; 16 + 17 + // Create temporary file for compilation 18 + const tmpDir = mkdtempSync(join(tmpdir(), 'typelex-')); 19 + const tmpFile = join(tmpDir, 'example.tsp'); 20 + writeFileSync(tmpFile, code); 21 + 22 + let lexiconJson: string; 23 + let lexicon: string; 24 + 25 + try { 26 + lexiconJson = await compileToJson(tmpFile); 27 + lexicon = stringify(JSON.parse(lexiconJson), { maxLength: hero ? 50 : 80 }); 28 + } finally { 29 + rmSync(tmpDir, { recursive: true, force: true }); 30 + } 31 + 32 + const typelexHtml = await highlightCode(code, 'typespec'); 33 + const lexiconHtml = await highlightCode(lexicon, 'json'); 34 + const playgroundUrl = createPlaygroundUrl(code); 35 + 36 + const panelClass = hero ? 'hero-panel' : 'code-panel'; 37 + const headerClass = hero ? 'hero-header' : 'code-header'; 38 + const blockClass = hero ? 'hero-code' : 'code-block'; 39 + --- 40 + 41 + <figure class:list={[hero ? 'hero-comparison' : 'comparison']}> 42 + <div class="comparison-content"> 43 + <div class={panelClass}> 44 + <p class={headerClass}> 45 + Typelex 46 + <a href={playgroundUrl} target="_blank" rel="noopener noreferrer" class="code-playground-link" aria-label="Open in playground"> 47 + <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> 48 + <path d="M6.5 3.5C6.5 3.22386 6.72386 3 7 3H13C13.2761 3 13.5 3.22386 13.5 3.5V9.5C13.5 9.77614 13.2761 10 13 10C12.7239 10 12.5 9.77614 12.5 9.5V4.70711L6.85355 10.3536C6.65829 10.5488 6.34171 10.5488 6.14645 10.3536C5.95118 10.1583 5.95118 9.84171 6.14645 9.64645L11.7929 4H7C6.72386 4 6.5 3.77614 6.5 3.5Z" fill="currentColor"/> 49 + <path d="M3 5.5C3 4.67157 3.67157 4 4.5 4H5C5.27614 4 5.5 4.22386 5.5 4.5C5.5 4.77614 5.27614 5 5 5H4.5C4.22386 5 4 5.22386 4 5.5V11.5C4 11.7761 4.22386 12 4.5 12H10.5C10.7761 12 11 11.7761 11 11.5V11C11 10.7239 11.2239 10.5 11.5 10.5C11.7761 10.5 12 10.7239 12 11V11.5C12 12.3284 11.3284 13 10.5 13H4.5C3.67157 13 3 12.3284 3 11.5V5.5Z" fill="currentColor"/> 50 + </svg> 51 + </a> 52 + </p> 53 + <div class={blockClass} set:html={typelexHtml} /> 54 + </div> 55 + <div class={panelClass}> 56 + <p class={headerClass}> 57 + Lexicon 58 + </p> 59 + <div class={blockClass} set:html={lexiconHtml} /> 60 + </div> 61 + </div> 62 + </figure>
+193
packages/website/src/layouts/BaseLayout.astro
··· 1 + --- 2 + interface Props { 3 + title: string; 4 + description?: string; 5 + transparentNav?: boolean; 6 + } 7 + 8 + const { 9 + title, 10 + description = "An experimental TypeSpec syntax for AT Protocol Lexicons. Write Lexicons in a more readable syntax using TypeSpec.", 11 + transparentNav = false 12 + } = Astro.props; 13 + --- 14 + 15 + <!DOCTYPE html> 16 + <html lang="en"> 17 + <head> 18 + <meta charset="utf-8" /> 19 + <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> 20 + <meta name="viewport" content="width=device-width, initial-scale=1" /> 21 + <meta name="generator" content={Astro.generator} /> 22 + <title>{title}</title> 23 + <meta name="description" content={description} /> 24 + 25 + <!-- Open Graph / Facebook --> 26 + <meta property="og:type" content="website" /> 27 + <meta property="og:url" content="https://typelex.org/" /> 28 + <meta property="og:title" content={title} /> 29 + <meta property="og:description" content={description} /> 30 + <meta property="og:image" content="https://typelex.org/og.png" /> 31 + 32 + <!-- Twitter --> 33 + <meta property="twitter:card" content="summary_large_image" /> 34 + <meta property="twitter:url" content="https://typelex.org/" /> 35 + <meta property="twitter:title" content={title} /> 36 + <meta property="twitter:description" content={description} /> 37 + <meta property="twitter:image" content="https://typelex.org/og.png" /> 38 + </head> 39 + <body> 40 + <nav class:list={["top-nav", { transparent: transparentNav }]}> 41 + <div class="nav-container"> 42 + <a href="/" class="logo">typelex</a> 43 + <div class="nav-links"> 44 + <a href="#install">Install</a> 45 + <a href="https://tangled.org/@danabra.mov/typelex/blob/main/DOCS.md" target="_blank" rel="noopener noreferrer">Docs</a> 46 + <a href="https://playground.typelex.org" target="_blank" rel="noopener noreferrer">Playground</a> 47 + </div> 48 + </div> 49 + </nav> 50 + 51 + <slot /> 52 + 53 + <script> 54 + // Smooth scroll to top when clicking logo 55 + document.addEventListener('DOMContentLoaded', () => { 56 + const logo = document.querySelector('.logo'); 57 + if (logo) { 58 + logo.addEventListener('click', (e) => { 59 + // Allow Ctrl/Cmd+click to open in new tab 60 + if (e.ctrlKey || e.metaKey || e.shiftKey) { 61 + return; 62 + } 63 + e.preventDefault(); 64 + window.scrollTo({ top: 0, behavior: 'smooth' }); 65 + }); 66 + } 67 + }); 68 + </script> 69 + 70 + {transparentNav && ( 71 + <script> 72 + const nav = document.querySelector('.top-nav'); 73 + const heroTitle = document.querySelector('header h1'); 74 + 75 + if (heroTitle && nav) { 76 + const handleScroll = () => { 77 + const titleRect = heroTitle.getBoundingClientRect(); 78 + 79 + if (titleRect.bottom < 16) { 80 + nav.classList.remove('transparent'); 81 + } else { 82 + nav.classList.add('transparent'); 83 + } 84 + }; 85 + 86 + window.addEventListener('scroll', handleScroll, { passive: true }); 87 + handleScroll(); 88 + } 89 + </script> 90 + )} 91 + </body> 92 + </html> 93 + 94 + <style is:global> 95 + * { 96 + margin: 0; 97 + padding: 0; 98 + box-sizing: border-box; 99 + } 100 + 101 + html { 102 + scroll-behavior: smooth; 103 + } 104 + 105 + body { 106 + font-family: system-ui, -apple-system, sans-serif; 107 + line-height: 1.6; 108 + color: #1e293b; 109 + background: #f8fafc; 110 + font-size: 16px; 111 + } 112 + 113 + @media (min-width: 768px) { 114 + body { 115 + font-size: 17px; 116 + } 117 + } 118 + 119 + .top-nav { 120 + position: sticky; 121 + top: 0; 122 + z-index: 100; 123 + background: rgba(255, 255, 255, 0.8); 124 + backdrop-filter: blur(10px); 125 + border-bottom: 1px solid #e2e8f0; 126 + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); 127 + transition: all 0.3s ease; 128 + } 129 + 130 + .top-nav.transparent { 131 + background: rgba(255, 255, 255, 0); 132 + backdrop-filter: none; 133 + border-bottom-color: transparent; 134 + box-shadow: none; 135 + } 136 + 137 + .top-nav.transparent .logo { 138 + opacity: 0; 139 + transform: translateY(-100%); 140 + } 141 + 142 + .top-nav.transparent .nav-links a { 143 + opacity: 0.7; 144 + } 145 + 146 + .nav-container { 147 + max-width: 1104px; 148 + margin: 0 auto; 149 + padding: 1rem 2rem; 150 + display: flex; 151 + justify-content: space-between; 152 + align-items: center; 153 + } 154 + 155 + @media (min-width: 768px) { 156 + .nav-container { 157 + padding: 1rem 2rem; 158 + } 159 + } 160 + 161 + .logo { 162 + font-size: 1.25rem; 163 + font-weight: 800; 164 + background: linear-gradient(90deg, #4a9eff 0%, #7a8ef7 40%, #ff85c1 70%, #9b7ef7 100%); 165 + -webkit-background-clip: text; 166 + -webkit-text-fill-color: transparent; 167 + background-clip: text; 168 + text-decoration: none; 169 + transition: all 0.3s ease; 170 + padding-left: 80px; 171 + padding-right: 80px; 172 + margin-left: -80px; 173 + margin-right: -80px; 174 + } 175 + 176 + .nav-links { 177 + display: flex; 178 + gap: 1.5rem; 179 + align-items: center; 180 + } 181 + 182 + .nav-links a { 183 + color: #64748b; 184 + text-decoration: none; 185 + font-weight: 500; 186 + transition: all 0.3s ease; 187 + font-size: 0.9375rem; 188 + } 189 + 190 + .nav-links a:hover { 191 + color: #7a8ef7; 192 + } 193 + </style>
+445
packages/website/src/layouts/DocsLayout.astro
··· 1 + --- 2 + import BaseLayout from './BaseLayout.astro'; 3 + 4 + interface Props { 5 + title: string; 6 + } 7 + 8 + const { title } = Astro.props; 9 + --- 10 + 11 + <BaseLayout title={`${title} โ€“ typelex`}> 12 + <div class="docs-container"> 13 + <aside class="sidebar"> 14 + <div class="sidebar-content"> 15 + <h3>Documentation</h3> 16 + <nav class="sidebar-nav"> 17 + <a href="/docs" class:list={[{ active: Astro.url.pathname === '/docs' || Astro.url.pathname === '/docs/' }]}>Introduction</a> 18 + </nav> 19 + </div> 20 + </aside> 21 + 22 + <main class="docs-main"> 23 + <article class="docs-content"> 24 + <h1>{title}</h1> 25 + <slot /> 26 + </article> 27 + </main> 28 + </div> 29 + 30 + <script> 31 + document.addEventListener('DOMContentLoaded', () => { 32 + const scrollables = document.querySelectorAll('.code-panel:last-child .code-block'); 33 + 34 + // Update gradient mask based on scroll position 35 + scrollables.forEach(block => { 36 + const updateMask = () => { 37 + const isAtBottom = block.scrollHeight - block.scrollTop <= block.clientHeight + 5; 38 + if (isAtBottom) { 39 + block.style.maskImage = 'none'; 40 + block.style.webkitMaskImage = 'none'; 41 + } else { 42 + block.style.maskImage = 'linear-gradient(to bottom, black calc(100% - 150px), transparent 100%)'; 43 + block.style.webkitMaskImage = 'linear-gradient(to bottom, black calc(100% - 150px), transparent 100%)'; 44 + } 45 + }; 46 + 47 + block.addEventListener('scroll', updateMask); 48 + updateMask(); // Initial check 49 + }); 50 + 51 + // Freeze inner scrollable blocks while scrolling the page 52 + let scrollTimeout; 53 + const freezeInnerScroll = () => { 54 + document.body.classList.add('outer-scrolling'); 55 + 56 + clearTimeout(scrollTimeout); 57 + scrollTimeout = setTimeout(() => { 58 + document.body.classList.remove('outer-scrolling'); 59 + }, 150); 60 + }; 61 + 62 + // Listen for both scroll and wheel events to catch scrolling early 63 + window.addEventListener('scroll', freezeInnerScroll, { passive: true }); 64 + window.addEventListener('wheel', (e) => { 65 + // Only freeze if the wheel event is not inside a scrollable block 66 + const target = e.target; 67 + const isInsideScrollable = target.closest('.code-panel:last-child .code-block'); 68 + if (!isInsideScrollable) { 69 + freezeInnerScroll(); 70 + } 71 + }, { passive: true }); 72 + }); 73 + </script> 74 + </BaseLayout> 75 + 76 + <style is:global> 77 + .docs-container { 78 + max-width: 1400px; 79 + margin: 0 auto; 80 + display: grid; 81 + grid-template-columns: 250px 1fr; 82 + gap: 3rem; 83 + padding: 2rem 1.5rem; 84 + } 85 + 86 + @media (max-width: 968px) { 87 + .docs-container { 88 + grid-template-columns: 1fr; 89 + gap: 2rem; 90 + } 91 + 92 + .sidebar { 93 + position: static; 94 + border-right: none; 95 + border-bottom: 1px solid #e2e8f0; 96 + padding-bottom: 2rem; 97 + } 98 + } 99 + 100 + .sidebar { 101 + position: sticky; 102 + top: 5rem; 103 + height: fit-content; 104 + } 105 + 106 + .sidebar-content h3 { 107 + font-size: 0.875rem; 108 + text-transform: uppercase; 109 + letter-spacing: 0.05em; 110 + color: #94a3b8; 111 + margin-bottom: 1rem; 112 + font-weight: 600; 113 + } 114 + 115 + .sidebar-nav { 116 + display: flex; 117 + flex-direction: column; 118 + gap: 0.25rem; 119 + } 120 + 121 + .sidebar-nav a { 122 + color: #64748b; 123 + text-decoration: none; 124 + padding: 0.5rem 0.75rem; 125 + border-radius: 6px; 126 + transition: all 0.2s ease; 127 + font-weight: 500; 128 + } 129 + 130 + .sidebar-nav a:hover { 131 + background: #f1f5f9; 132 + color: #1e293b; 133 + } 134 + 135 + .sidebar-nav a.active { 136 + background: linear-gradient(135deg, #7a8ef7 0%, #9483f7 70%, #b87ed8 100%); 137 + color: white; 138 + font-weight: 600; 139 + } 140 + 141 + .docs-main { 142 + min-width: 0; 143 + max-width: 800px; 144 + } 145 + 146 + .docs-content { 147 + padding-bottom: 4rem; 148 + } 149 + 150 + .docs-content h1 { 151 + font-size: 2.5rem; 152 + font-weight: 800; 153 + margin: 0 0 2rem 0; 154 + background: linear-gradient(90deg, #4a9eff 0%, #7a8ef7 40%, #ff85c1 70%, #9b7ef7 100%); 155 + -webkit-background-clip: text; 156 + -webkit-text-fill-color: transparent; 157 + background-clip: text; 158 + } 159 + 160 + .docs-content h2 { 161 + font-size: 1.875rem; 162 + font-weight: 700; 163 + margin-top: 3rem; 164 + margin-bottom: 1.5rem; 165 + color: #1e293b; 166 + } 167 + 168 + .docs-content h3 { 169 + font-size: 1.5rem; 170 + font-weight: 600; 171 + margin-top: 2rem; 172 + margin-bottom: 1rem; 173 + color: #334155; 174 + } 175 + 176 + .docs-content h4 { 177 + font-size: 1.25rem; 178 + font-weight: 600; 179 + margin-top: 1.5rem; 180 + margin-bottom: 0.75rem; 181 + color: #475569; 182 + } 183 + 184 + .docs-content p { 185 + margin-bottom: 1.25rem; 186 + line-height: 1.8; 187 + color: #475569; 188 + } 189 + 190 + .docs-content a { 191 + color: #6366f1; 192 + text-decoration: none; 193 + border-bottom: 1px solid #c7d2fe; 194 + transition: all 0.2s ease; 195 + } 196 + 197 + .docs-content a:hover { 198 + color: #4f46e5; 199 + border-bottom-color: #6366f1; 200 + } 201 + 202 + .docs-content ul, .docs-content ol { 203 + margin-bottom: 1.5rem; 204 + padding-left: 2rem; 205 + } 206 + 207 + .docs-content li { 208 + margin-bottom: 0.5rem; 209 + line-height: 1.8; 210 + color: #475569; 211 + } 212 + 213 + .docs-content code { 214 + font-family: 'Monaco', 'Menlo', monospace; 215 + font-size: 0.875em; 216 + background: #f1f5f9; 217 + padding: 0.2em 0.4em; 218 + border-radius: 4px; 219 + color: #e879b9; 220 + } 221 + 222 + .docs-content pre { 223 + background: #1e1b29; 224 + border-radius: 8px; 225 + padding: 1rem; 226 + overflow-x: auto; 227 + margin-bottom: 1.5rem; 228 + } 229 + 230 + @media (min-width: 768px) { 231 + .docs-content pre { 232 + padding: 1.25rem; 233 + } 234 + } 235 + 236 + .docs-content pre code { 237 + background: transparent; 238 + padding: 0; 239 + color: inherit; 240 + font-size: 0.75rem; 241 + line-height: 1.6; 242 + } 243 + 244 + @media (min-width: 768px) { 245 + .docs-content pre code { 246 + font-size: 0.875rem; 247 + line-height: 1.7; 248 + } 249 + } 250 + 251 + .docs-content table { 252 + width: 100%; 253 + border-collapse: collapse; 254 + margin-bottom: 1.5rem; 255 + font-size: 0.9375rem; 256 + } 257 + 258 + .docs-content th, 259 + .docs-content td { 260 + text-align: left; 261 + padding: 0.75rem 1rem; 262 + border: 1px solid #e2e8f0; 263 + } 264 + 265 + .docs-content th { 266 + background: #f8fafc; 267 + font-weight: 600; 268 + color: #1e293b; 269 + } 270 + 271 + .docs-content td { 272 + color: #475569; 273 + } 274 + 275 + .docs-content blockquote { 276 + border-left: 4px solid #7a8ef7; 277 + padding-left: 1.5rem; 278 + margin: 1.5rem 0; 279 + color: #64748b; 280 + font-style: italic; 281 + } 282 + 283 + .comparison { 284 + background: #1e1b29; 285 + border-radius: 12px; 286 + box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); 287 + overflow: hidden; 288 + margin: 2rem 0; 289 + } 290 + 291 + .comparison-content { 292 + position: relative; 293 + padding: 0.75rem; 294 + display: grid; 295 + grid-template-columns: 1fr; 296 + gap: 1.5rem; 297 + } 298 + 299 + @media (min-width: 768px) { 300 + .comparison-content { 301 + padding: 1rem; 302 + grid-template-columns: 1fr 1fr; 303 + gap: 2rem; 304 + } 305 + } 306 + 307 + .code-panel { 308 + position: relative; 309 + min-width: 0; 310 + overflow: hidden; 311 + text-align: left; 312 + } 313 + 314 + .code-header { 315 + padding: 0.5rem 1rem; 316 + background: #252231; 317 + border-radius: 8px 8px 0 0; 318 + font-size: 0.75rem; 319 + font-weight: 600; 320 + text-transform: uppercase; 321 + letter-spacing: 0.05em; 322 + margin: 0; 323 + color: #94a3b8; 324 + display: flex; 325 + align-items: center; 326 + justify-content: space-between; 327 + } 328 + 329 + @media (min-width: 768px) { 330 + .code-header { 331 + font-size: 0.8125rem; 332 + padding: 0.625rem 1rem; 333 + } 334 + } 335 + 336 + .code-block { 337 + position: relative; 338 + text-align: left; 339 + } 340 + 341 + .code-panel:last-child .code-block { 342 + overflow-y: auto; 343 + max-height: 400px; 344 + -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 100px), transparent 100%); 345 + mask-image: linear-gradient(to bottom, black calc(100% - 100px), transparent 100%); 346 + } 347 + 348 + /* Freeze inner scrollables when scrolling the page */ 349 + body.outer-scrolling .code-panel:last-child .code-block { 350 + pointer-events: none; 351 + overflow-y: hidden; 352 + } 353 + 354 + @media (min-width: 768px) { 355 + .code-panel:first-child { 356 + position: relative; 357 + z-index: 1; 358 + } 359 + 360 + .code-panel:last-child { 361 + position: absolute; 362 + top: 1rem; 363 + bottom: 1rem; 364 + right: 1rem; 365 + left: calc(50% + 1rem); 366 + } 367 + 368 + .code-panel:last-child .code-block { 369 + max-height: none; 370 + height: 100%; 371 + padding-bottom: 1.5rem; 372 + -webkit-mask-image: linear-gradient(to bottom, black calc(100% - 150px), transparent 100%); 373 + mask-image: linear-gradient(to bottom, black calc(100% - 150px), transparent 100%); 374 + } 375 + 376 + body.outer-scrolling .code-panel:last-child .code-block { 377 + pointer-events: none; 378 + overflow-y: hidden; 379 + } 380 + } 381 + 382 + .code-block pre { 383 + margin: 0; 384 + padding: 1rem; 385 + background: transparent !important; 386 + overflow-x: auto; 387 + overflow-y: visible; 388 + -webkit-overflow-scrolling: touch; 389 + max-width: 100%; 390 + } 391 + 392 + @media (min-width: 768px) { 393 + .code-block pre { 394 + padding: 1.5rem; 395 + } 396 + } 397 + 398 + .code-block code { 399 + font-family: 'Monaco', 'Menlo', monospace; 400 + font-size: 0.75rem !important; 401 + line-height: 1.6; 402 + white-space: pre; 403 + text-align: left; 404 + } 405 + 406 + @media (min-width: 768px) { 407 + .code-block code { 408 + font-size: 0.875rem !important; 409 + } 410 + } 411 + 412 + .code-block pre code, 413 + .code-block pre code * { 414 + font-size: inherit !important; 415 + } 416 + 417 + .code-playground-link { 418 + display: inline-flex; 419 + align-items: center; 420 + justify-content: center; 421 + color: #94a3b8; 422 + transition: all 0.2s ease; 423 + text-decoration: none; 424 + opacity: 0.4; 425 + padding: 0.125rem; 426 + border-bottom: none !important; 427 + } 428 + 429 + .code-playground-link:hover { 430 + color: #c7d2fe; 431 + opacity: 1; 432 + } 433 + 434 + .code-playground-link svg { 435 + width: 1rem; 436 + height: 1rem; 437 + } 438 + 439 + @media (min-width: 768px) { 440 + .code-playground-link svg { 441 + width: 1.125rem; 442 + height: 1.125rem; 443 + } 444 + } 445 + </style>
+45 -234
packages/website/src/pages/index.astro
··· 1 1 --- 2 + import BaseLayout from '../layouts/BaseLayout.astro'; 3 + import ComparisonBlock from '../components/ComparisonBlock.astro'; 2 4 import { highlightCode } from '../utils/shiki'; 3 - import { compileToJson } from '../utils/compile'; 4 5 import { createPlaygroundUrl } from '../utils/playground-url'; 5 - import stringify from 'json-stringify-pretty-compact'; 6 - import { mkdtempSync, writeFileSync, rmSync } from 'fs'; 7 - import { join } from 'path'; 8 - import { tmpdir } from 'os'; 9 6 10 7 // Define examples inline 11 8 const examples = [ 12 9 { 13 10 title: "Records and properties", 14 - typelex: `import "@typelex/emitter"; 11 + code: `import "@typelex/emitter"; 15 12 16 13 namespace fm.teal.alpha.feed.play { 17 14 @rec("tid") 18 15 model Main { 19 16 @maxItems(10) 20 17 artistNames?: string[]; 21 - 18 + 22 19 @required 23 20 @minLength(1) 24 21 @maxLength(256) ··· 31 28 }, 32 29 { 33 30 title: "Refs and unions", 34 - typelex: `import "@typelex/emitter"; 31 + code: `import "@typelex/emitter"; 35 32 36 33 namespace app.bsky.feed.post { 37 34 @rec("tid") ··· 66 63 }, 67 64 { 68 65 title: "Queries and params", 69 - typelex: `import "@typelex/emitter"; 66 + code: `import "@typelex/emitter"; 70 67 71 68 namespace com.atproto.repo.listRecords { 72 69 @query ··· 99 96 }, 100 97 ]; 101 98 102 - // Compile examples 103 - const highlighted = await Promise.all( 104 - examples.map(async (ex) => { 105 - // Create temporary file for compilation 106 - const tmpDir = mkdtempSync(join(tmpdir(), 'typelex-')); 107 - const tmpFile = join(tmpDir, 'example.tsp'); 108 - writeFileSync(tmpFile, ex.typelex); 109 - 110 - try { 111 - const lexiconJson = await compileToJson(tmpFile); 112 - const lexicon = stringify(JSON.parse(lexiconJson), { maxLength: 80 }); 113 - 114 - return { 115 - ...ex, 116 - typelexHtml: await highlightCode(ex.typelex, 'typespec'), 117 - lexiconHtml: await highlightCode(lexicon, 'json'), 118 - playgroundUrl: createPlaygroundUrl(ex.typelex), 119 - }; 120 - } finally { 121 - rmSync(tmpDir, { recursive: true, force: true }); 122 - } 123 - }) 124 - ); 125 - --- 126 - 127 - <!DOCTYPE html> 128 - <html lang="en"> 129 - <head> 130 - <meta charset="utf-8" /> 131 - <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> 132 - <meta name="viewport" content="width=device-width, initial-scale=1" /> 133 - <meta name="generator" content={Astro.generator} /> 134 - <title>typelex โ€“ An experimental TypeSpec syntax for Lexicon</title> 135 - <meta name="description" content="An experimental TypeSpec syntax for AT Protocol Lexicons. Write Lexicons in a more readable syntax using TypeSpec." /> 136 - 137 - <!-- Open Graph / Facebook --> 138 - <meta property="og:type" content="website" /> 139 - <meta property="og:url" content="https://typelex.org/" /> 140 - <meta property="og:title" content="typelex โ€“ An experimental TypeSpec syntax for Lexicon" /> 141 - <meta property="og:description" content="An experimental TypeSpec syntax for AT Protocol Lexicons. Write Lexicons in a more readable syntax using TypeSpec." /> 142 - <meta property="og:image" content="https://typelex.org/og.png" /> 143 - 144 - <!-- Twitter --> 145 - <meta property="twitter:card" content="summary_large_image" /> 146 - <meta property="twitter:url" content="https://typelex.org/" /> 147 - <meta property="twitter:title" content="typelex โ€“ An experimental TypeSpec syntax for Lexicon" /> 148 - <meta property="twitter:description" content="An experimental TypeSpec syntax for AT Protocol Lexicons. Write Lexicons in a more readable syntax using TypeSpec." /> 149 - <meta property="twitter:image" content="https://typelex.org/og.png" /> 150 - </head> 151 - <body> 152 - <main class="container"> 153 - <header> 154 - <h1>typelex</h1> 155 - <p class="tagline">An experimental <a href="https://typespec.io" target="_blank" rel="noopener noreferrer">TypeSpec</a> syntax for <a href="https://atproto.com/specs/lexicon" target="_blank" rel="noopener noreferrer">Lexicon</a></p> 156 - 157 - <figure class="hero-comparison"> 158 - <div class="comparison-content"> 159 - <div class="hero-panel"> 160 - <p class="hero-header"> 161 - Typelex 162 - <a href={createPlaygroundUrl(`import "@typelex/emitter"; 99 + const heroCode = `import "@typelex/emitter"; 163 100 164 101 namespace app.bsky.actor.profile { 165 102 @rec("self") ··· 172 109 @maxGraphemes(256) 173 110 description?: string; 174 111 } 175 - }`)} target="_blank" rel="noopener noreferrer" class="code-playground-link" aria-label="Open in playground"> 176 - <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> 177 - <path d="M6.5 3.5C6.5 3.22386 6.72386 3 7 3H13C13.2761 3 13.5 3.22386 13.5 3.5V9.5C13.5 9.77614 13.2761 10 13 10C12.7239 10 12.5 9.77614 12.5 9.5V4.70711L6.85355 10.3536C6.65829 10.5488 6.34171 10.5488 6.14645 10.3536C5.95118 10.1583 5.95118 9.84171 6.14645 9.64645L11.7929 4H7C6.72386 4 6.5 3.77614 6.5 3.5Z" fill="currentColor"/> 178 - <path d="M3 5.5C3 4.67157 3.67157 4 4.5 4H5C5.27614 4 5.5 4.22386 5.5 4.5C5.5 4.77614 5.27614 5 5 5H4.5C4.22386 5 4 5.22386 4 5.5V11.5C4 11.7761 4.22386 12 4.5 12H10.5C10.7761 12 11 11.7761 11 11.5V11C11 10.7239 11.2239 10.5 11.5 10.5C11.7761 10.5 12 10.7239 12 11V11.5C12 12.3284 11.3284 13 10.5 13H4.5C3.67157 13 3 12.3284 3 11.5V5.5Z" fill="currentColor"/> 179 - </svg> 180 - </a> 181 - </p> 182 - <div class="hero-code" set:html={await highlightCode(`import "@typelex/emitter"; 112 + }`; 113 + 114 + const installCode = `import "@typelex/emitter"; 115 + import "./externals.tsp"; 183 116 184 - namespace app.bsky.actor.profile { 185 - @rec("self") 117 + namespace com.myapp.example.profile { 118 + /** My profile. */ 119 + @rec("literal:self") 186 120 model Main { 187 - @maxLength(64) 188 - @maxGraphemes(64) 189 - displayName?: string; 190 - 191 - @maxLength(256) 121 + /** Free-form profile description.*/ 192 122 @maxGraphemes(256) 193 123 description?: string; 194 124 } 195 - }`, 'typespec')} /> 196 - </div> 197 - <div class="hero-panel"> 198 - <p class="hero-header"> 199 - Lexicon 200 - </p> 201 - <div class="hero-code" set:html={await highlightCode(stringify({ 202 - "lexicon": 1, 203 - "id": "app.bsky.actor.profile", 204 - "defs": { 205 - "main": { 206 - "type": "record", 207 - "key": "self", 208 - "record": { 209 - "type": "object", 210 - "properties": { 211 - "displayName": { 212 - "type": "string", 213 - "maxLength": 64, 214 - "maxGraphemes": 64 215 - }, 216 - "description": { 217 - "type": "string", 218 - "maxLength": 256, 219 - "maxGraphemes": 256 220 - } 221 - } 222 - } 223 - } 224 - } 225 - }, { maxLength: 50 }), 'json')} /> 226 - </div> 227 - </div> 228 - </figure> 125 + }`; 126 + --- 127 + 128 + <BaseLayout title="typelex โ€“ An experimental TypeSpec syntax for Lexicon" transparentNav={true}> 129 + <main class="container"> 130 + <header> 131 + <h1>typelex</h1> 132 + <p class="tagline">An experimental <a href="https://typespec.io" target="_blank" rel="noopener noreferrer">TypeSpec</a> syntax for <a href="https://atproto.com/specs/lexicon" target="_blank" rel="noopener noreferrer">Lexicon</a></p> 133 + 134 + <ComparisonBlock code={heroCode} hero={true} /> 229 135 230 136 <p class="hero-description"> 231 137 Typelex lets you write AT <a target="_blank" href="https://atproto.com/specs/lexicon">Lexicons</a> in a more readable syntax. <br /> ··· 234 140 235 141 <nav class="hero-actions"> 236 142 <a href="#install" class="install-cta">Try It</a> 237 - <a href="https://tangled.org/@danabra.mov/typelex/blob/main/DOCS.md" target="_blank" rel="noopener noreferrer" class="star-btn"> 143 + <a target="_blank" href="https://tangled.org/@danabra.mov/typelex/blob/main/DOCS.md" class="star-btn"> 238 144 Read Docs 239 145 </a> 240 146 </nav> ··· 242 148 243 149 <hr class="separator" /> 244 150 245 - {highlighted.map(({ title, typelexHtml, lexiconHtml, playgroundUrl }) => ( 151 + {examples.map(({ title, code }) => ( 246 152 <section> 247 153 <h2>{title}</h2> 248 - <figure class="comparison"> 249 - <div class="comparison-content"> 250 - <div class="code-panel"> 251 - <p class="code-header"> 252 - Typelex 253 - <a href={playgroundUrl} target="_blank" rel="noopener noreferrer" class="code-playground-link" aria-label="Open in playground"> 254 - <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> 255 - <path d="M6.5 3.5C6.5 3.22386 6.72386 3 7 3H13C13.2761 3 13.5 3.22386 13.5 3.5V9.5C13.5 9.77614 13.2761 10 13 10C12.7239 10 12.5 9.77614 12.5 9.5V4.70711L6.85355 10.3536C6.65829 10.5488 6.34171 10.5488 6.14645 10.3536C5.95118 10.1583 5.95118 9.84171 6.14645 9.64645L11.7929 4H7C6.72386 4 6.5 3.77614 6.5 3.5Z" fill="currentColor"/> 256 - <path d="M3 5.5C3 4.67157 3.67157 4 4.5 4H5C5.27614 4 5.5 4.22386 5.5 4.5C5.5 4.77614 5.27614 5 5 5H4.5C4.22386 5 4 5.22386 4 5.5V11.5C4 11.7761 4.22386 12 4.5 12H10.5C10.7761 12 11 11.7761 11 11.5V11C11 10.7239 11.2239 10.5 11.5 10.5C11.7761 10.5 12 10.7239 12 11V11.5C12 12.3284 11.3284 13 10.5 13H4.5C3.67157 13 3 12.3284 3 11.5V5.5Z" fill="currentColor"/> 257 - </svg> 258 - </a> 259 - </p> 260 - <div class="code-block" set:html={typelexHtml} /> 261 - </div> 262 - <div class="code-panel"> 263 - <p class="code-header"> 264 - Lexicon 265 - </p> 266 - <div class="code-block" set:html={lexiconHtml} /> 267 - </div> 268 - </div> 269 - </figure> 154 + <ComparisonBlock code={code} /> 270 155 </section> 271 156 ))} 272 157 ··· 282 167 <div class="step-number">0</div> 283 168 <div class="step-content"> 284 169 <h3>Try the playground</h3> 285 - <p class="step-description">Experiment with typelex in your browser before installing.</p> 286 170 <a href="https://playground.typelex.org" target="_blank" rel="noopener noreferrer" class="playground-button"> 287 171 Open Playground 288 172 </a> 173 + <p class="step-description">Experiment with typelex in your browser before installing.</p> 289 174 </div> 290 175 </div> 291 176 292 177 <div class="install-step"> 293 178 <div class="step-number">1</div> 294 179 <div class="step-content"> 295 - <h3>Install packages</h3> 296 - <figure class="install-box" set:html={await highlightCode('npm install -D @typespec/compiler @typelex/emitter', 'bash')} /> 180 + <h3>Add typelex to your app</h3> 181 + <figure class="install-box" set:html={await highlightCode('npx @typelex/cli init', 'bash')} /> 182 + <p class="step-description">This will add a few things to your <code>package.json</code> and create a <code>typelex/</code> folder.</p> 297 183 </div> 298 184 </div> 299 185 300 186 <div class="install-step"> 301 187 <div class="step-number">2</div> 302 188 <div class="step-content"> 303 - <h3>Create <code>typelex/main.tsp</code></h3> 304 - <figure class="install-box install-box-with-link"> 305 - <a href={createPlaygroundUrl(`import "@typelex/emitter"; 306 - 307 - namespace com.example.actor.profile { 308 - /** My profile. */ 309 - @rec("literal:self") 310 - model Main { 311 - /** Free-form profile description.*/ 312 - @maxGraphemes(256) 313 - description?: string; 314 - } 315 - }`)} target="_blank" rel="noopener noreferrer" class="install-playground-link" aria-label="Open in playground"> 316 - <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"> 317 - <path d="M6.5 3.5C6.5 3.22386 6.72386 3 7 3H13C13.2761 3 13.5 3.22386 13.5 3.5V9.5C13.5 9.77614 13.2761 10 13 10C12.7239 10 12.5 9.77614 12.5 9.5V4.70711L6.85355 10.3536C6.65829 10.5488 6.34171 10.5488 6.14645 10.3536C5.95118 10.1583 5.95118 9.84171 6.14645 9.64645L11.7929 4H7C6.72386 4 6.5 3.77614 6.5 3.5Z" fill="currentColor"/> 318 - <path d="M3 5.5C3 4.67157 3.67157 4 4.5 4H5C5.27614 4 5.5 4.22386 5.5 4.5C5.5 4.77614 5.27614 5 5 5H4.5C4.22386 5 4 5.22386 4 5.5V11.5C4 11.7761 4.22386 12 4.5 12H10.5C10.7761 12 11 11.7761 11 11.5V11C11 10.7239 11.2239 10.5 11.5 10.5C11.7761 10.5 12 10.7239 12 11V11.5C12 12.3284 11.3284 13 10.5 13H4.5C3.67157 13 3 12.3284 3 11.5V5.5Z" fill="currentColor"/> 319 - </svg> 320 - </a> 321 - <div set:html={await highlightCode(`import "@typelex/emitter"; 322 - 323 - namespace com.example.actor.profile { 324 - /** My profile. */ 325 - @rec("literal:self") 326 - model Main { 327 - /** Free-form profile description.*/ 328 - @maxGraphemes(256) 329 - description?: string; 330 - } 331 - }`, 'typespec')} /> 332 - </figure> 189 + <h3>Write your lexicons in <code>typelex/main.tsp</code></h3> 190 + <figure class="install-box" set:html={await highlightCode(installCode, 'typespec')} /> 191 + <p class="step-description">Your app's lexicons go here. They may reference any external ones from <code>lexicons/</code>.</p> 333 192 </div> 334 - <p class="step-description">Or grab any example Lexicon <a target=_blank href="https://playground.typelex.org/">from the Playground</a>.</p> 335 193 </div> 336 194 337 195 <div class="install-step"> 338 196 <div class="step-number">3</div> 339 197 <div class="step-content"> 340 - <h3>Create <code><a href="https://typespec.io/docs/handbook/configuration/configuration/" target="_blank" rel="noopener noreferrer">tspconfig.yaml</a></code></h3> 341 - <figure class="install-box" set:html={await highlightCode(`emit: 342 - - "@typelex/emitter" 343 - options: 344 - "@typelex/emitter": 345 - output-dir: "./lexicons"`, 'yaml')} /> 198 + <h3>Compile your lexicons</h3> 199 + <figure class="install-box" set:html={await highlightCode(`npm run build:typelex`, 'bash')} /> 200 + <p class="step-description">Your appโ€™s compiled lexicons will appear in <code>lexicons/</code> alongside any external ones.</p> 346 201 </div> 347 202 </div> 348 203 349 204 <div class="install-step"> 350 205 <div class="step-number">4</div> 351 206 <div class="step-content"> 352 - <h3>Add a build script to <code>package.json</code></h3> 353 - <figure class="install-box" set:html={await highlightCode(`{ 354 - "scripts": { 355 - // ... 356 - "build:lexicons": "tsp compile typelex/main.tsp" 357 - } 358 - }`, 'json')} /> 359 - </div> 360 - </div> 361 - 362 - <div class="install-step"> 363 - <div class="step-number">5</div> 364 - <div class="step-content"> 365 - <h3>Generate Lexicon files</h3> 366 - <figure class="install-box" set:html={await highlightCode(`npm run build:lexicons`, 'bash')} /> 367 - <p class="step-description">Lexicon files will be generated in the <code>output-dir</code> from your <code>tspconfig.yaml</code> config.</p> 368 - </div> 369 - </div> 370 - 371 - <div class="install-step"> 372 - <div class="step-number">6</div> 373 - <div class="step-content"> 374 207 <h3>Set up VS Code</h3> 375 208 <p class="step-description">Install the <a href="https://typespec.io/docs/introduction/editor/vscode/" target="_blank" rel="noopener noreferrer">TypeSpec for VS Code extension</a> for syntax highlighting and IntelliSense.</p> 376 209 </div> 377 210 </div> 378 211 379 212 <div class="install-step"> 380 - <div class="step-number">7</div> 213 + <div class="step-number">5</div> 381 214 <div class="step-content"> 382 - <h3>Read the docs</h3> 215 + <h3>Learn more</h3> 383 216 <p class="step-description">Check out the <a href="https://tangled.org/@danabra.mov/typelex/blob/main/DOCS.md" target="_blank" rel="noopener noreferrer">documentation</a> to learn more.</p> 384 217 </div> 385 218 </div> ··· 392 225 <p>This is my personal hobby project and is not affiliated with AT or endorsed by anyone.</p> 393 226 <p>Who knows if this is a good idea?</p> 394 227 </footer> 395 - </main> 228 + </main> 396 229 397 - <script> 230 + <script> 398 231 document.addEventListener('DOMContentLoaded', () => { 399 232 const scrollables = document.querySelectorAll('.code-panel:last-child .code-block, .hero-panel:last-child .hero-code'); 400 233 ··· 437 270 } 438 271 }, { passive: true }); 439 272 }); 440 - </script> 441 - </body> 442 - </html> 273 + </script> 274 + </BaseLayout> 443 275 444 276 <style is:global> 445 - * { 446 - margin: 0; 447 - padding: 0; 448 - box-sizing: border-box; 449 - } 450 - 451 - html { 452 - scroll-behavior: smooth; 453 - } 454 - 455 277 body { 456 - font-family: system-ui, -apple-system, sans-serif; 457 - line-height: 1.6; 458 - color: #1e293b; 459 - background: #f8fafc; 460 - font-size: 16px; 461 278 position: relative; 462 279 overflow-x: hidden; 463 280 } ··· 473 290 border-radius: 50%; 474 291 pointer-events: none; 475 292 z-index: 0; 476 - } 477 - 478 - @media (min-width: 768px) { 479 - body { 480 - font-size: 17px; 481 - } 482 293 } 483 294 484 295 .container { ··· 781 592 .install-section { 782 593 margin: 0; 783 594 padding: 0; 595 + scroll-margin-top: 5rem; 784 596 } 785 597 786 598 .install-section h2 { ··· 1218 1030 1219 1031 .playground-button { 1220 1032 display: inline-block; 1221 - margin-top: 1.25rem; 1222 1033 padding: 0.875rem 2rem; 1223 1034 background: linear-gradient(135deg, #7a8ef7 0%, #9483f7 70%, #b87ed8 100%); 1224 1035 color: white;
+9 -12
pnpm-lock.yaml
··· 14 14 15 15 packages/cli: 16 16 dependencies: 17 - '@typelex/emitter': 18 - specifier: ^0.2.0 19 - version: 0.2.0(@typespec/compiler@1.4.0(@types/node@20.19.19)) 20 17 '@typespec/compiler': 21 18 specifier: ^1.4.0 22 19 version: 1.4.0(@types/node@20.19.19) 20 + globby: 21 + specifier: ^14.0.0 22 + version: 14.1.0 23 23 picocolors: 24 24 specifier: ^1.1.1 25 25 version: 1.1.1 ··· 27 27 specifier: ^18.0.0 28 28 version: 18.0.0 29 29 devDependencies: 30 + '@typelex/emitter': 31 + specifier: workspace:* 32 + version: link:../emitter 30 33 '@types/node': 31 34 specifier: ^20.0.0 32 35 version: 20.19.19 ··· 36 39 typescript: 37 40 specifier: ^5.0.0 38 41 version: 5.9.3 42 + vitest: 43 + specifier: ^1.0.0 44 + version: 1.6.1(@types/node@20.19.19) 39 45 40 46 packages/emitter: 41 47 dependencies: ··· 1669 1675 1670 1676 '@ts-morph/common@0.25.0': 1671 1677 resolution: {integrity: sha512-kMnZz+vGGHi4GoHnLmMhGNjm44kGtKUXGnOvrKmMwAuvNjM/PgKVGfUnL7IDvK7Jb2QQ82jq3Zmp04Gy+r3Dkg==} 1672 - 1673 - '@typelex/emitter@0.2.0': 1674 - resolution: {integrity: sha512-4Iw6VAnd9nCFGOkJcu9utWdmu9ZyPeAb1QX/B7KerGBmfc2FuIDqgZZ/mZ6c56atcZd62pb2oYF/3RgSFhEsoQ==} 1675 - peerDependencies: 1676 - '@typespec/compiler': ^1.4.0 1677 1678 1678 1679 '@types/babel__core@7.20.5': 1679 1680 resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} ··· 7446 7447 minimatch: 9.0.5 7447 7448 path-browserify: 1.0.1 7448 7449 tinyglobby: 0.2.15 7449 - 7450 - '@typelex/emitter@0.2.0(@typespec/compiler@1.4.0(@types/node@20.19.19))': 7451 - dependencies: 7452 - '@typespec/compiler': 1.4.0(@types/node@20.19.19) 7453 7450 7454 7451 '@types/babel__core@7.20.5': 7455 7452 dependencies:
+229
scripts/publish-all.sh
··· 1 + #!/bin/bash 2 + set -e 3 + 4 + # Usage: ./scripts/publish-all.sh <version> [--dry] 5 + # Example: ./scripts/publish-all.sh 0.4.0 6 + # Example: ./scripts/publish-all.sh 0.4.0 --dry 7 + 8 + if [ -z "$1" ]; then 9 + echo "Error: Version argument required" 10 + echo "Usage: ./scripts/publish-all.sh <version> [--dry]" 11 + echo "Example: ./scripts/publish-all.sh 0.4.0" 12 + echo "Example: ./scripts/publish-all.sh 0.4.0 --dry" 13 + exit 1 14 + fi 15 + 16 + VERSION="$1" 17 + DRY_RUN=false 18 + 19 + if [ "$2" = "--dry" ]; then 20 + DRY_RUN=true 21 + fi 22 + 23 + # Validate version format (basic semver check) 24 + if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$ ]]; then 25 + echo "Error: Invalid version format. Use semver format (e.g., 0.4.0 or 0.4.0-beta.1)" 26 + exit 1 27 + fi 28 + 29 + echo "๐Ÿ“ฆ Publishing all packages at version $VERSION" 30 + echo "" 31 + 32 + # Get the root directory 33 + ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" 34 + cd "$ROOT_DIR" 35 + 36 + # Find all package.json files in packages/* 37 + ALL_PACKAGES=($(find packages -maxdepth 2 -name "package.json" -not -path "*/node_modules/*" | sort)) 38 + 39 + # Filter out private packages and topologically sort by dependencies 40 + PACKAGES=($(node -e " 41 + const fs = require('fs'); 42 + const allPackages = process.argv.slice(1); 43 + 44 + // Filter out private packages 45 + const packages = allPackages.filter(path => { 46 + const pkg = JSON.parse(fs.readFileSync(path, 'utf-8')); 47 + return !pkg.private; 48 + }); 49 + 50 + // Build dependency graph 51 + const graph = new Map(); 52 + const pkgNames = new Map(); 53 + 54 + packages.forEach(path => { 55 + const pkg = JSON.parse(fs.readFileSync(path, 'utf-8')); 56 + pkgNames.set(pkg.name, path); 57 + 58 + const deps = new Set(); 59 + [pkg.dependencies, pkg.devDependencies, pkg.peerDependencies].forEach(depObj => { 60 + if (depObj) { 61 + Object.keys(depObj).forEach(dep => { 62 + if (dep.startsWith('@typelex/')) { 63 + deps.add(dep); 64 + } 65 + }); 66 + } 67 + }); 68 + 69 + graph.set(pkg.name, deps); 70 + }); 71 + 72 + // Topological sort - packages with more dependents first 73 + const sorted = []; 74 + const processed = new Set(); 75 + 76 + function visit(pkgName) { 77 + if (processed.has(pkgName)) return; 78 + processed.add(pkgName); 79 + 80 + // Visit all dependencies first 81 + const deps = graph.get(pkgName) || new Set(); 82 + deps.forEach(dep => { 83 + if (graph.has(dep)) { 84 + visit(dep); 85 + } 86 + }); 87 + 88 + sorted.push(pkgName); 89 + } 90 + 91 + // Visit all packages 92 + graph.forEach((_, pkgName) => visit(pkgName)); 93 + 94 + // Output sorted package paths 95 + sorted.forEach(name => { 96 + if (pkgNames.has(name)) { 97 + console.log(pkgNames.get(name)); 98 + } 99 + }); 100 + " "${ALL_PACKAGES[@]}")) 101 + 102 + if [ ${#PACKAGES[@]} -eq 0 ]; then 103 + echo "Error: No publishable packages found in packages/" 104 + exit 1 105 + fi 106 + 107 + echo "Found ${#PACKAGES[@]} publishable packages (topologically sorted):" 108 + for pkg in "${PACKAGES[@]}"; do 109 + PKG_NAME=$(node -p "require('./$pkg').name") 110 + echo " - $PKG_NAME" 111 + done 112 + echo "" 113 + 114 + # Update all package.json files with the new version 115 + echo "๐Ÿ”„ Updating versions in all packages..." 116 + for pkg in "${PACKAGES[@]}"; do 117 + PKG_DIR=$(dirname "$pkg") 118 + PKG_NAME=$(node -p "require('./$pkg').name") 119 + 120 + echo " Updating $PKG_NAME..." 121 + 122 + # Update version 123 + node -e " 124 + const fs = require('fs'); 125 + const path = '$pkg'; 126 + const pkg = require('./' + path); 127 + pkg.version = '$VERSION'; 128 + 129 + // Helper to preserve semver prefix (^, ~, etc.) and workspace: protocol 130 + function updateVersion(currentVersion, newVersion) { 131 + // Preserve workspace: protocol for monorepo 132 + if (currentVersion.startsWith('workspace:')) { 133 + return currentVersion; 134 + } 135 + // Preserve semver prefix 136 + const match = currentVersion.match(/^([~^>=<]*)(.*)$/); 137 + if (match) { 138 + return match[1] + newVersion; 139 + } 140 + return newVersion; 141 + } 142 + 143 + // Helper to update dependencies 144 + function updateDeps(deps) { 145 + if (!deps) return; 146 + for (const dep in deps) { 147 + if (dep.startsWith('@typelex/')) { 148 + deps[dep] = updateVersion(deps[dep], '$VERSION'); 149 + } 150 + } 151 + } 152 + 153 + updateDeps(pkg.dependencies); 154 + updateDeps(pkg.devDependencies); 155 + updateDeps(pkg.peerDependencies); 156 + 157 + fs.writeFileSync(path, JSON.stringify(pkg, null, 2) + '\n'); 158 + " 159 + done 160 + 161 + echo "" 162 + echo "โœ… All versions updated to $VERSION" 163 + echo "" 164 + 165 + if [ "$DRY_RUN" = true ]; then 166 + echo "โœ… Dry run complete! Version updates have been applied." 167 + echo "" 168 + echo "๐Ÿ“‹ Updated packages:" 169 + for pkg in "${PACKAGES[@]}"; do 170 + PKG_NAME=$(node -p "require('./$pkg').name") 171 + echo " - $PKG_NAME@$VERSION" 172 + done 173 + echo "" 174 + echo "๐Ÿ’ก Review the changes, then run without --dry to publish." 175 + exit 0 176 + fi 177 + 178 + # Ask for confirmation 179 + read -p "๐Ÿš€ Ready to publish all packages to npm. Continue? (y/N) " -n 1 -r 180 + echo 181 + if [[ ! $REPLY =~ ^[Yy]$ ]]; then 182 + echo "โŒ Publish cancelled" 183 + exit 1 184 + fi 185 + 186 + echo "" 187 + echo "๐Ÿ“ค Publishing packages..." 188 + echo "" 189 + 190 + # Publish each package 191 + PUBLISHED=() 192 + FAILED=() 193 + 194 + for pkg in "${PACKAGES[@]}"; do 195 + PKG_DIR=$(dirname "$pkg") 196 + PKG_NAME=$(node -p "require('./$pkg').name") 197 + 198 + echo "Publishing $PKG_NAME..." 199 + 200 + if (cd "$PKG_DIR" && npm publish --access public); then 201 + echo " โœ… $PKG_NAME published successfully" 202 + PUBLISHED+=("$PKG_NAME") 203 + else 204 + echo " โŒ $PKG_NAME failed to publish" 205 + FAILED+=("$PKG_NAME") 206 + fi 207 + 208 + echo "" 209 + done 210 + 211 + # Summary 212 + echo "๐Ÿ“Š Summary:" 213 + echo "" 214 + echo "Published (${#PUBLISHED[@]}):" 215 + for pkg in "${PUBLISHED[@]}"; do 216 + echo " โœ… $pkg" 217 + done 218 + 219 + if [ ${#FAILED[@]} -gt 0 ]; then 220 + echo "" 221 + echo "Failed (${#FAILED[@]}):" 222 + for pkg in "${FAILED[@]}"; do 223 + echo " โŒ $pkg" 224 + done 225 + exit 1 226 + fi 227 + 228 + echo "" 229 + echo "๐ŸŽ‰ All packages published successfully!"