### Install Dnsmasq on Linux with apt Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md Installs the Dnsmasq package on a Linux system using the apt package manager. This command is typically run on Debian-based distributions like Ubuntu. ```bash apt install dnsmasq ``` -------------------------------- ### Darklang Record Declaration with Type Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Demonstrates how to declare a record with explicit type arguments in Darklang. This example shows a basic record initialization with a string field. ```Darklang MyRecord { name = "test" } ``` -------------------------------- ### Darklang HTTP Client Library Source: https://context7.com/darklang/dark/llms.txt This Darklang code defines types and functions for making HTTP requests. It includes types for `Response` and `RequestError`, and functions for making GET and POST requests with customizable headers and bodies. Example usage is also provided. ```darklang // packages/darklang/stdlib/httpclient.dark module Darklang.Stdlib.HttpClient type Response = { statusCode: Int64 headers: List<(String * String)> body: List } type RequestError = | BadUrl of BadUrlDetails | Timeout | BadHeader of BadHeader | NetworkError | BadMethod // Make HTTP GET request let get (uri: String) (headers: List<(String * String)>) : Stdlib.Result.Result = request "GET" uri headers [] // Make HTTP POST request with body let post (uri: String) (headers: List<(String * String)>) (body: List) : Stdlib.Result.Result = request "POST" uri headers body // Example usage in Darklang: // let response = Stdlib.HttpClient.get "https://api.example.com/users" [] // match response with // | Ok resp -> // let bodyStr = Stdlib.String.fromBytes resp.body // Stdlib.Cli.printLine bodyStr // | Error err -> // let errMsg = Stdlib.HttpClient.toString err // Stdlib.Cli.printLine $"Request failed: {errMsg}" ``` -------------------------------- ### Darklang Record Declaration with Function Calls Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Illustrates initializing a Darklang record where one of the fields is assigned the result of a function call. This example uses a function from the Stdlib.Int module. ```Darklang MyRecord { name = "test" age = Stdlib.Int.toString 30L } ``` -------------------------------- ### Darklang Lambda: Unit Argument Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/lambda.txt Defines a lambda function that takes a unit argument and returns an Int64 literal. This is a basic example showcasing the minimal lambda structure. ```dark fun () -> 1L ``` -------------------------------- ### Parse Comparison Operator < Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing a less than comparison operation between two variables. ```Darklang a < b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Install Dnsmasq on macOS with Homebrew Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md Installs the Dnsmasq package on macOS using the Homebrew package manager. This is the initial step for setting up local DNS resolution on a Mac. ```bash brew install dnsmasq ``` -------------------------------- ### Darklang Enum - Two Integer Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Provides an example of an enum case with two separate integer arguments. Arguments are listed sequentially, separated by commas. ```darklang MyEnum.TwoArgs(1L, 2L) ``` -------------------------------- ### Darklang Record with Multiple Fields Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Shows how to define a record with multiple fields, including strings, integers, and lists. This demonstrates handling collections within a record. ```Darklang Person {name = "John"; age = 30L; hobbies = ["reading"; "swimming"]} ``` -------------------------------- ### Darklang Record with Multi-line Fields Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Provides an example of defining a record with multiple fields spread across several lines for improved readability. This format is helpful for records with many fields or long field values. ```Darklang Person { name = "John" age = 30L hobbies = ["reading"; "swimming"] } ``` -------------------------------- ### Darklang Syntax Examples Source: https://context7.com/darklang/dark/llms.txt Illustrates fundamental Darklang syntax, including list operations with pipes, record and enum construction, pattern matching, and standard library usage for arithmetic and string manipulation. ```darklang // List operations with pipe operator (Stdlib.List.range 0L 100L) |> Stdlib.List.map (fun x -> x + 1L) |> Stdlib.List.filter (fun x -> x > 50L) // Record construction with proper formatting type User = { name: String; age: Int64; email: String } let user = User { name = "Alice" age = 30L email = "alice@example.com" } // Enum construction type Status = | Active | Inactive | Pending let status = Status.Active // Match expression with enum deconstruction match status with | Active -> "User is active" | Inactive -> "User is inactive" | Pending -> "User is pending" // Division using Stdlib (no / operator) let result = Stdlib.Int64.divide 10L 3L // Float subtraction using Stdlib (no - operator) let diff = Stdlib.Float.subtract 5.5 2.3 // String concatenation with ++ let greeting = "Hello, " ++ "World!" // List concatenation using Stdlib.List.append let combined = Stdlib.List.append [1L; 2L] [3L; 4L] // List items separated by semicolons let numbers = [ 1L; 2L; 3L; 4L; 5L ] ``` -------------------------------- ### Parse Comparison Operator > Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing a greater than comparison operation between two variables. ```Darklang a > b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Enum - With Type Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Demonstrates an enum that uses type arguments, specifying the type of data it holds. This example shows a string type argument. ```darklang MyEnum.B("test") ``` -------------------------------- ### Darklang Complex Record Initialization Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Shows a more complex Darklang record initialization involving nested records and function calls for arithmetic and string concatenation. It demonstrates multi-line assignments and nested structures. ```Darklang MyRecord { name = "test" age = Stdlib.Int64.add 30L 10L address = Address { city = "New York" street = Stdlib.String.concat [ "5th Avenue"; "Broadway" ] ", " } } ``` -------------------------------- ### Parse Comparison Operator == Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing an equality comparison operation between two variables. ```Darklang a == b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Parse Comparison Operator != Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing a not equal to comparison operation between two variables. ```Darklang a != b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang If/Elif/Else Statement Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt Demonstrates a standard if/elif/else structure in Darklang. The keyword 'then' signifies the start of the conditional block, and blocks are indented. This example shows nested 'else if' conditions. ```darklang if a > b then a else if c > d then c else d ``` -------------------------------- ### Parse Basic Infix Operation Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates parsing a simple infix operation with two operands and an operator. This is a fundamental building block for arithmetic and logical expressions. ```Darklang a + b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Record with Two Fields Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Illustrates creating a record with two fields, a string and an integer. This expands on the basic record structure to include multiple data types. ```Darklang Person {name = "John"; age = 30L} ``` -------------------------------- ### Pipe Expression: Function Call into Function Call Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt This example demonstrates piping the result of one function call into another. `Stdlib.Int64.add 1L 2L` is evaluated first, and its result is then passed as the first argument to `Stdlib.Int64.add 1L`. This showcases sequential application of functions. ```dark Stdlib.Int64.add 1L 2L |> Stdlib.Int64.add 1L ``` -------------------------------- ### F# SQL Execution Pattern Source: https://github.com/darklang/dark/blob/main/CODING-GUIDE.md Demonstrates the recommended pattern for executing SQL queries in F# to avoid performance issues. It shows how to separate data retrieval from expensive operations by mapping over the results. ```F# let! results = someSqlStuff |> Sql.executeAsync (fun read -> read.string "value") return results |> (List.map (fun str -> expensiveOperation str) ``` -------------------------------- ### Parse Basic Function Call Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Illustrates the parsing of a basic function call with a qualified name and two boolean literal arguments. ```Darklang Bool.and true false --- (source_file (expression (apply (qualified_fn_name (module_identifier) (symbol) (fn_identifier)) (simple_expression (bool_literal)) (simple_expression (bool_literal)) ) ) ) ``` -------------------------------- ### Function call with dictionary argument in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates passing a dictionary (key-value pairs) as an argument. Useful for flexible data structures. ```Darklang Builtin.printLine Dict {a = 1L} ``` -------------------------------- ### Parse Comparison Operator <= Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing a less than or equal to comparison operation between two variables. ```Darklang a <= b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Stdlib Function Calls Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/list.txt Provides examples of common standard library function calls in Darklang, such as Stdlib.Int64.add, Stdlib.Tuple2.second, and Stdlib.List.head. These showcase practical usage of built-in functions for arithmetic, tuples, and lists. ```Darklang [ (Stdlib.Int64.add 1L 2L) Stdlib.Tuple2.second (4L, 5L) Stdlib.List.head [1L; 2L] ] ``` -------------------------------- ### Darklang Record Update - Record as Variable Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/record_update.txt This example demonstrates updating a field in a record that is stored in a variable. First, a record is defined and assigned to 'myRec'. Then, a new record is created by updating the 'y' field of 'myRec' using the 'with' keyword. The input is a variable assignment and a record update operation, producing a new record. ```dark let myRec = RecordForUpdate { x = 4L; y = 1L } { myRec with y = 2L } ``` -------------------------------- ### Parse Comparison Operator >= Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Example of parsing a greater than or equal to comparison operation between two variables. ```Darklang a >= b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Parse Exponent Operator ^ Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates parsing the exponentiation operator (`^`) between two operands. ```Darklang a ^ b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Mixed Indentation (Tab and Space) - Valid Case Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt This example shows a potentially valid scenario in Darklang where a mix of tab and double-space indentation is used. The outer if/else uses tabs, while the inner if/else uses spaces. This highlights Darklang's flexibility with indentation, though consistency is generally recommended. ```darklang if a > b then if c > d then c else d ``` -------------------------------- ### Pipe Expression: Function Call with Arguments (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Demonstrates passing an integer literal and an additional argument to a standard library function for addition. ```Darklang 1L |> Stdlib.Int64.add 2L ``` -------------------------------- ### Kubernetes Secret Management and Rollout Restart Source: https://github.com/darklang/dark/blob/main/docs/production/db-creds-rotation.md Demonstrates how to back up, update, and apply Kubernetes secrets for database credentials. It includes commands to restart deployments in both 'default' and 'darklang' namespaces to apply the new credentials. ```bash # Backup secret: kubectl get secrets -n default cloudsql-db-credentials -o yaml > old-db-secret.yaml # Get base64 for new password and user: echo -n "NEW PASSWORD" | base64 echo -n "userNEW" | base64 # Edit the secret: kubectl edit secrets cloudsql-db-credentials -n default # Restart services in 'default' namespace: kubectl rollout restart deployment editor-deployment -n default kubectl rollout restart deployment garbagecollector-deployment -n default kubectl rollout restart deployment cronchecker-deployment -n default # --- For 'darklang' namespace --- # Backup secret: kubectl get secrets -n darklang cloudsql-db-credentials -o yaml > old-db-secret.yaml # Edit the secret: kubectl edit secrets cloudsql-db-credentials -n darklang # Restart services in 'darklang' namespace: kubectl rollout restart deployment prodexec-deployment -n darklang kubectl rollout restart deployment queueworker-deployment -n darklang kubectl rollout restart deployment bwdserver-deployment -n darklang # In case of error, restore old secret: kubectl apply -f old-db-secret.yaml ``` -------------------------------- ### Darklang Enum - Tuple Argument Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Shows how to use a tuple as an argument for an enum case. The tuple is enclosed in parentheses and its elements are separated by commas. ```darklang MyEnum.TwoArgs((1L, 2L)) ``` -------------------------------- ### SQL Injection: Basic DROP TABLE Commands Source: https://github.com/darklang/dark/blob/main/backend/testfiles/data/naughty-strings.txt These are common string patterns used in SQL Injection attacks to drop tables. The first example uses a semicolon to terminate the previous query and execute `DROP TABLE users`. The second example uses a single quote to terminate a string and a comment (`-- 1`) to ignore the rest of the original query, followed by `DROP TABLE users`. ```sql 1;DROP TABLE users 1'; DROP TABLE users-- ``` -------------------------------- ### Darklang Lambda: Mixed Arguments (Variable and Tuple) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/lambda.txt An example of a lambda function with mixed argument types: a single variable `x` and a tuple `(y, z)`. The function concatenates all three variables. This demonstrates combining different argument patterns. ```dark fun x (y, z) -> x ++ y ++ z ``` -------------------------------- ### Darklang Nested If/Else Statement Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt Provides an example of deeply nested if/else statements in Darklang. This structure handles complex decision trees where conditions are evaluated within the branches of preceding conditions. ```darklang if a > b then if c > d then c else if e > f then e else if g > h then g else h else b ``` -------------------------------- ### Darklang Pipe Expression: Sequential Function Calls Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Demonstrates a sequence of pipe expressions in Darklang, where the output of one function becomes the input of the next. This improves readability for complex data transformations. ```darklang (pipe_expr (pipe_fn_call (qualified_fn_name (module_identifier) (symbol) (module_identifier) (symbol) (fn_identifier)))) ) ) ) (pipe_exprs (symbol) (pipe_expr (pipe_fn_call (qualified_fn_name (module_identifier) (symbol) (fn_identifier)))) ) ) ) ) ``` -------------------------------- ### Darklang Lambda: Two Variable Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/lambda.txt Demonstrates a lambda function accepting two variable arguments, `a` and `b`. It performs an infix multiplication operation on these variables. This highlights multi-argument lambda syntax. ```dark fun a b -> a * b ``` -------------------------------- ### Parse Left Associative Infix Operation Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Illustrates how the parser handles left associativity for infix operators, ensuring that chained operations like `a + b + c` are correctly grouped as `(a + b) + c`. ```Darklang a + b + c --- (source_file (expression (simple_expression (infix_operation (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Enum - No Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Demonstrates the basic syntax for an enum with no arguments. This is the simplest form, representing a distinct state without associated data. ```darklang MyEnum.NoArgs ``` -------------------------------- ### Darklang Lambda: Single Variable Argument Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/lambda.txt Illustrates a lambda function with a single variable argument `x`. It performs an infix operation, adding 1 to the input variable. This shows basic variable usage within lambdas. ```dark fun x -> x + 1L ``` -------------------------------- ### Darklang Enum - Fully Qualified Name Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Demonstrates using a fully qualified name for an enum, including module and type identifiers. This is useful for disambiguation in larger projects. ```darklang Stdlib.Option.Option.None ``` -------------------------------- ### Pipe Expression: Let Binding and Variable (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Defines a simple lambda function using a let binding and then pipes an integer literal to this function, demonstrating function application. ```Darklang let fn = (fun x -> x + 1L) 1L |> fn ``` -------------------------------- ### Parse Infix Operator Precedence (^ > *) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates parsing with exponentiation (`^`) having higher precedence than multiplication (`*`), so `a * b ^ c` is parsed as `a * (b ^ c)`. ```Darklang a * b ^ c --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ) ) ``` -------------------------------- ### Darklang Record with One Field Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Defines a record with a single field. This is the most basic form of record creation in Darklang, suitable for simple data structures. ```Darklang Person {name = "John"} ``` -------------------------------- ### Darklang: Return Ok from Result Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt Illustrates a Darklang function that returns an 'Ok' value for the Stdlib.Result type. This function signifies a successful operation with an Int64 value. It takes no arguments and returns Stdlib.Result.Ok 5L. ```darklang let returnsResultOk () : Stdlib.Result.Result = Stdlib.Result.Result.Ok 5L ``` -------------------------------- ### Darklang Record Update with Function Application Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/record_update.txt Demonstrates updating record fields by applying functions from modules like Stdlib.Int64.List, Stdlib.Int64, and Stdlib.Tuple. This syntax is used when the new value for a field is the result of a function call. ```Darklang { record with x = Stdlib.Int64.List.push [1L] 2L y = Stdlib.Int64.add 1L 2L z = Stdlib.Tuple.first (1L, 2L) } ``` -------------------------------- ### Parse Function Call with Nested Function Call Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates parsing a function call where one of the arguments is itself a function call, showcasing nested expression handling. ```Darklang Bool.and (Bool.and true false) false --- (source_file (expression (apply (qualified_fn_name (module_identifier) (symbol) (fn_identifier)) (simple_expression (paren_expression (symbol) (expression (apply (qualified_fn_name (module_identifier) (symbol) (fn_identifier)) (simple_expression (bool_literal)) (simple_expression (bool_literal)) ) ) ) ) (simple_expression (bool_literal)) ) ) ) ``` -------------------------------- ### Darklang Lambda: Parenthesized Expression Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/lambda.txt Shows a lambda function definition wrapped in parentheses. This syntax is often used for clarity or when a lambda needs to be treated as a single expression. ```dark (fun x -> x + 1L) ``` -------------------------------- ### Darklang Enum - Fully Qualified with Single Argument Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Shows a fully qualified enum name with a single integer argument. This combines namespace clarity with data association. ```darklang Stdlib.Option.Option.Some(1L) ``` -------------------------------- ### Pipe Expression: Multiple List Operations Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt This snippet shows a chain of pipe expressions applied to a list literal. The list `[1L; 2L]` is first piped into `Stdlib.List.last` to get the last element, and the result of that is then piped into `Builtin.unwrap` to extract the value. ```dark [1L; 2L] |> Stdlib.List.last |> Builtin.unwrap ``` -------------------------------- ### Function call with record argument in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Shows how to pass a record literal as an argument to a function. This is useful for structured data passing, like defining object properties. ```Darklang Builtin.printLine Person { name = "Alice" } ``` -------------------------------- ### Darklang HTTP Server Request Handling Source: https://context7.com/darklang/dark/llms.txt This F# code demonstrates core functionalities for the Darklang HTTP server (BwdServer), including reading request headers, extracting query strings, and reading the request body. It also shows how to write a response back to the client. ```fsharp // backend/src/BwdServer/Server.fs // Read headers from incoming request let getHeadersWithoutMergingKeys (ctx : HttpContext) : List = ctx.Request.Headers |> Seq.map Tuple2.fromKeyValuePair |> Seq.map (fun (k, v) -> v.ToArray() |> Array.toList |> List.map (fun v -> (k, v))) |> Seq.collect (fun pair -> pair) |> Seq.toList // Get query string let getQuery (ctx : HttpContext) : string = ctx.Request.QueryString.ToString() // Read request body let getBody (ctx : HttpContext) : Task = task { try let ms = new System.IO.MemoryStream() do! ctx.Request.Body.CopyToAsync(ms) return ms.ToArray() with e -> return raise (GrandUserException $"Invalid request body: {e.Message}") } // Write response let writeResponseToContext (ctx : HttpContext) (statusCode : int) (headers : List) (body : array) : Task = task { ctx.Response.StatusCode <- statusCode headers |> List.iter (fun (k, v) -> setResponseHeader ctx k v) ctx.Response.ContentLength <- int64 body.Length if ctx.Request.Method <> "HEAD" then do! ctx.Response.BodyWriter.WriteAsync(body) } ``` -------------------------------- ### Parse Infix Operator Precedence (* > +) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Shows how the parser correctly interprets operator precedence, specifically that multiplication (`*`) has higher precedence than addition (`+`), parsing `a + b * c` as `a + (b * c)`. ```Darklang a + b * c --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ) ) ``` -------------------------------- ### Function call with indented arguments in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Demonstrates a function call where arguments, including lambda expressions, are indented for readability. This improves clarity for functions with multiple or complex arguments. ```Darklang Stdlib.Tuple3.mapAllThree (fun x -> Stdlib.String.toUppercase x) (fun x -> x - 2L) (fun x -> Stdlib.String.toUppercase x) ("one", 2L, "pi") ``` -------------------------------- ### Test General Internet Connectivity with ping Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md This command checks general internet connectivity by pinging www.google.com. It sends a single ping packet (-c 1) and waits for a response. This helps ensure that setting up local DNS has not disrupted external network access. ```bash ping -c 1 www.google.com ``` -------------------------------- ### Darklang: Return None from Option Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt Demonstrates a Darklang function that returns a 'None' value for the Stdlib.Option type. This is useful for representing the absence of a value without causing errors. It takes no arguments and returns Stdlib.Option.None. ```darklang let returnsOptionNone () : Stdlib.Option.Option<'a> = Stdlib.Option.Option.None ``` -------------------------------- ### Darklang Match Expression - When Condition Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/match.txt Shows a match expression with a 'when' condition to further refine pattern matching. This example matches an integer and checks if it's greater than zero before returning a boolean. No external dependencies are required. ```Darklang match 5L with | x when x > 0L -> true | x -> false ``` -------------------------------- ### Darklang Module Declaration with Newlines Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt A 'Test' module declaration in Darklang demonstrating the use of newlines for readability. It includes a value declaration 'x', a record type 'T', and a function 'helloWorld'. ```darklang module Test = val x = 1L type T = { x : Int64 } let helloWorld (i: Int64): String = "Hello world" ``` -------------------------------- ### Darklang Record Literal with Function Calls Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt This snippet demonstrates how to define a record literal in Darklang. It includes assigning values to fields, utilizing standard library functions like `Stdlib.Int64.add` for integer operations, and assigning string literals. ```dark MyRecord { age = Stdlib.Int64.add 30L 10L address = "test" } ``` -------------------------------- ### Restart Dnsmasq service on Linux Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md Restarts the Dnsmasq service on a Linux system using the init.d scripts. This command ensures that the Dnsmasq service is running and has loaded the latest configuration. ```bash sudo /etc/init.d/dnsmasq restart ``` -------------------------------- ### Darklang Inline If/Else Statement Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt Illustrates a standard inline if-else statement in Darklang. A condition is evaluated, and one of two expressions is executed based on whether the condition is true or false. ```darklang if true then a else b ``` -------------------------------- ### F# DB Annotation for Darklang Source: https://github.com/darklang/dark/blob/main/backend/testfiles/execution/README.md Databases in Darklang can be defined by creating a type alias with a `DB` annotation. This explicitly marks the type as a database, allowing Darklang to manage and interact with it. The example defines `MyTypeDB` as a database. ```fsharp [] type MyTypeDB = MyDB ``` -------------------------------- ### Darklang Basic If/Else Statement Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt Presents a basic multi-line if-else statement in Darklang. This structure is used for more complex conditional logic where the true and false branches contain multiple statements or require indentation. ```darklang if a > b then a else b ``` -------------------------------- ### Darklang Inline If/Elif/Else Statement Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt Shows an inline if-elif-else structure in Darklang. This allows for multiple conditions to be checked sequentially, executing the block associated with the first true condition, or a final 'else' block if none are true. ```darklang if true then a else if false then b else c ``` -------------------------------- ### Darklang Module Declaration with Record Type Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt Declares a simple module named 'Test' containing a record type 'T' with two Int64 fields, 'x' and 'y'. This demonstrates basic module and type definition syntax in Darklang. ```darklang module Test = type T = { x : Int64; y : Int64} ``` -------------------------------- ### Darklang Pipe Expression: Infix Operations with Multiple Pipes Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Illustrates Darklang's pipe expressions with infix operators, allowing for operations like addition, multiplication, and comparison to be chained. This syntax is particularly useful for arithmetic sequences. ```darklang 1L |> (+) 2L |> (*) 3L |> (>) 4L ``` ```darklang (source_file (expression (pipe_expression (expression (pipe_expression (expression (pipe_expression (expression (simple_expression (int64_literal (digits (positive_digits)) (symbol)))) (pipe_exprs (symbol) (pipe_expr (pipe_infix (symbol) (operator) (symbol) (expression (simple_expression (int64_literal (digits (positive_digits)) (symbol)))) ) ) ) ) ) (pipe_exprs (symbol) (pipe_expr (pipe_infix (symbol) (operator) (symbol) (expression (simple_expression (int64_literal (digits (positive_digits)) (symbol)))) ) ) ) ) ) (pipe_exprs (symbol) (pipe_expr (pipe_infix (symbol) (operator) (symbol) (expression (simple_expression (int64_literal (digits (positive_digits)) (symbol)))) ) ) ) ) ) ) ``` -------------------------------- ### Darklang HTTP Response Helpers for Handlers Source: https://context7.com/darklang/dark/llms.txt Provides functions to construct various HTTP responses within Darklang handler functions. These helpers simplify setting status codes, headers (like Content-Type), and request bodies, ensuring correct response formatting. They are essential for building web services in Darklang. ```darklang module Darklang.Stdlib.Http type Response = { statusCode: Int64 headers: List body: List } // Create response with status code and body let response (body: List) (statusCode: Int64) : Stdlib.Http.Response = Stdlib.Http.Response { statusCode = statusCode headers = [] body = body } // Create 200 OK response let success (body: List) : Stdlib.Http.Response = Stdlib.Http.Response { statusCode = 200L headers = [] body = body } // Create HTML response with content-type header let responseWithHtml (body: String) (statusCode: Int64) : Stdlib.Http.Response = Stdlib.Http.Response { statusCode = statusCode headers = [ ("Content-Type", "text/html; charset=utf-8") ] body = body |> Stdlib.String.toBytes } // Create plain text response let responseWithText (text: String) (statusCode: Int64) : Stdlib.Http.Response = Stdlib.Http.Response { statusCode = statusCode headers = [ ("Content-Type", "text/plain; charset=utf-8") ] body = Stdlib.String.toBytes text } // Example usage: // Stdlib.Http.responseWithText "Hello, World!" 200L ``` -------------------------------- ### Bash Development Scripts for Darklang Source: https://context7.com/darklang/dark/llms.txt A collection of bash scripts for managing the Darklang development environment, including building, testing, running servers, formatting code, and executing commands within Docker containers. ```bash # Run the CLI with arguments ./scripts/run-cli help ./scripts/run-cli test arg1 arg2 # Run backend tests ./scripts/run-backend-tests # Run backend server ./scripts/run-backend-server # Build with watch mode and tests ./scripts/builder --compile --watch --test # Format code ./scripts/formatting/format format # Run in docker container ./scripts/run-in-docker bash ./scripts/run-in-docker psql -d devdb # Example CLI execution: # ./scripts/run-cli eval "1L + 2L" # Output: 3 ``` -------------------------------- ### Darklang Module Declaration without Newlines Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt A 'Test' module declaration in Darklang with elements defined on a single line, separated by spaces. It includes a value 'x', a type 'T', and a function 'helloWorld'. This highlights compact syntax. ```darklang module Test = val x = 1L type T = { x : Int64 } let helloWorld (i: Int64): String = "Hello world" ``` -------------------------------- ### Execute CLI Command with Darklang Source: https://context7.com/darklang/dark/llms.txt This F# code snippet demonstrates how to execute a CLI command using the Darklang package manager. It takes a list of string arguments and returns an execution result. This functionality is part of the backend CLI execution component. ```fsharp // backend/src/Cli/Cli.fs // Execute a CLI command with arguments let execute (packageManager : RT.PackageManager) (args : List) : Task = task { let state = state packageManager let fnName = RT.FQFnName.fqPackage PackageIDs.Fn.Cli.executeCliCommand let args = args |> List.map RT.DString |> Dval.list RT.KTString |> NEList.singleton let! result = Exe.executeFunction state fnName [] args return result } // Main entry point that initializes and runs CLI [] let main (args : string[]) = try EmbeddedResources.extract () initSerializers () let cliPackageManager = LibPackageManager.PackageManager.rt cliPackageManager.init.Result let result = execute cliPackageManager (Array.toList args) let result = result.Result NonBlockingConsole.wait () match result with | Error(rte, callStack) -> // handle error, exit code 1 | Ok dval -> // exit code 0 with e -> // handle exception, exit code 2 ``` -------------------------------- ### Darklang Mixed Indentation (Tab and Space) - Error Case Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/if_else.txt This example demonstrates an error-prone mixed indentation scenario in Darklang. Inconsistent indentation within nested blocks can lead to parsing errors or unexpected behavior. The inner 'else' block's indentation is particularly problematic. ```darklang if a > b then if c > d then c else d ``` -------------------------------- ### F# Package Manager for Darklang Source: https://context7.com/darklang/dark/llms.txt Implements runtime and program-time package managers for loading and caching types, functions, and values. Includes an in-memory package manager for testing purposes. It depends on the RT, PT, PMPT, and PMRT modules for package operations. ```fsharp module LibPackageManager.PackageManager // Runtime package manager with caching let rt : RT.PackageManager = { getType = withCache PMRT.Type.get getFn = withCache PMRT.Fn.get getValue = withCache PMRT.Value.get init = uply { return () } } // Program-time package manager let pt : PT.PackageManager = { findType = withCache PMPT.Type.find findValue = withCache PMPT.Value.find findFn = withCache PMPT.Fn.find getType = withCache PMPT.Type.get getFn = withCache PMPT.Fn.get getValue = withCache PMPT.Value.get getTypeLocation = withCache PMPT.Type.getLocation getValueLocation = withCache PMPT.Value.getLocation getFnLocation = withCache PMPT.Fn.getLocation search = LibPackageManager.ProgramTypes.search init = uply { return () } } // Create in-memory package manager for testing let createInMemory (ops : List) : PT.PackageManager = // Build maps by applying each op let types = ResizeArray() let fns = ResizeArray() for op in ops do match op with | PT.PackageOp.AddType t -> types.Add(t) | PT.PackageOp.AddFn f -> fns.Add(f) | _ -> () let typeMap = types |> Seq.map (fun t -> t.id, t) |> Map.ofSeq let fnMap = fns |> Seq.map (fun f -> f.id, f) |> Map.ofSeq { getType = fun id -> Ply(Map.tryFind id typeMap) getFn = fun id -> Ply(Map.tryFind id fnMap) (* ... other fields ... *) } // Usage in CLI: // let pm = LibPackageManager.PackageManager.rt // pm.init.Result // Initialize package manager ``` -------------------------------- ### Darklang Match Expression: Apply, Value, Pipe, and Variable Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/match.txt Illustrates matching against different scenarios within a Darklang match expression: function application, module values, pipe expressions, and simple variables. ```dark match var with | 5L -> Stdlib.Int64.add var 1L | 6L -> MyModule.myVal | 7L -> 7L |> Stdlib.Int64.add 1L | 8L -> myVar ``` -------------------------------- ### Parse String Concatenation Operator ++ Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Shows the parsing of the string concatenation operator (`++`) between two string operands. ```Darklang a ++ b --- (source_file (expression (simple_expression (infix_operation (simple_expression (variable_identifier)) (operator) (simple_expression (variable_identifier)) ) ) ) ) ``` -------------------------------- ### Darklang Function Call with Multiple Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/list.txt Demonstrates a typical function call in Darklang, showing how qualified function names and simple expressions with int64 literals are structured. This pattern is common for applying functions to data. ```Darklang (expression (apply (qualified_fn_name (module_identifier) (symbol) (module_identifier) (symbol) (fn_identifier)) (simple_expression (int64_literal (digits (positive_digits)) (symbol))) (simple_expression (int64_literal (digits (positive_digits)) (symbol))) ) ) ``` -------------------------------- ### Declare Enum Value in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/constant_decls.txt Illustrates the declaration of an enum value in Darklang. This example uses a qualified type name for the enum. ```dark val colorRed = Color.Red ``` -------------------------------- ### Function call with enum argument in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Illustrates passing an enum value as an argument to a function. This is common for representing distinct states or types. ```Darklang Builtin.printLine Stdlib.Option.Option.Some 1L ``` -------------------------------- ### Server Code Injection: Null Device and Touch Source: https://github.com/darklang/dark/blob/main/backend/testfiles/data/naughty-strings.txt This payload attempts Server Code Injection by redirecting output to `/dev/null` and then executing a `touch` command. The semicolon separates commands, ensuring `touch /tmp/blns.fail` is executed even if the initial part fails. This aims to create a file, possibly as a proof-of-concept or to indicate successful command execution. ```bash /dev/null; touch /tmp/blns.fail ; echo ``` -------------------------------- ### Pipe Expression: Infix Operation (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Pipes an integer literal into an infix operation, where the operator acts as the function and the second literal is the argument. ```Darklang 1L |> (+) 2L ``` -------------------------------- ### Configuration: Domain (Dark Test) Source: https://github.com/darklang/dark/blob/main/backend/testfiles/httphandler/README.md Sets a custom domain name for the test environment. The placeholder 'DOMAIN' in the test file will be replaced with this configured domain. ```dark [domain my.special.domainname.com] ``` -------------------------------- ### Nested Field Access in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/field_access.txt Illustrates accessing nested fields. This example accesses the 'street' field, which is within the 'address' field of the 'person' object. ```Darklang person.address.street ``` -------------------------------- ### Darklang Nested Modules with Values Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/module_decls.txt Demonstrates a 'Test' module containing two nested modules, 'Nested1' and 'Nested2'. 'Nested1' defines an Int64 value 'x', while 'Nested2' defines a boolean value 'x'. This illustrates multiple nested structures within a module. ```darklang module Test = module Nested1 = val x = 1L module Nested2 = val x = true ``` -------------------------------- ### Pipe Expression: Simple Function Call (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Passes an integer literal to a standard library function for string conversion using the pipe operator. ```Darklang 1L |> Stdlib.Int64.toString ``` -------------------------------- ### Dark Multi-Pattern Matching Example Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/match.txt This Dark code snippet demonstrates how to use the 'match' expression with multiple patterns. It allows for concise conditional logic by checking an input against several possible patterns, executing specific code blocks for each match or a default case. ```dark match x with | 1L | 2L | 3L -> "pass" | _ -> "fail" ``` -------------------------------- ### Function call with field access argument in Darklang Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/fn_calls.txt Illustrates a function call where one argument is a field access from a variable. This accesses specific data within a structure. ```Darklang Darklang.Stdlib.Http.response request.body 200L ``` -------------------------------- ### Configure macOS to use Dnsmasq for localhost Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md Configures macOS to use the locally running Dnsmasq service as the nameserver for the 'localhost' domain. This involves creating a resolver file that specifies '127.0.0.1' as the nameserver for '.localhost' domains, ensuring that local DNS queries are handled by Dnsmasq. ```bash sudo mkdir -p /etc/resolver sudo tee /etc/resolver/localhost >/dev/null < MyEnum.B(21L, 12L) ``` -------------------------------- ### Pipe Expression: Enum Construction with One Field (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Demonstrates piping a value into a custom enum constructor that accepts a single argument, like 'MyEnum.A'. ```Darklang 33L |> MyEnum.A(21L) ``` -------------------------------- ### Pipe Expression: Passing a Variable (Darklang) Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/pipe.txt Illustrates piping an integer literal to a variable, implying the variable holds a function or value that accepts the piped input. ```Darklang 5L |> x ``` -------------------------------- ### F# Self-Update Logic for Dark CLI Source: https://github.com/darklang/dark/blob/main/packages/darklang/cli/installation/README.md This F# code checks if the Dark CLI should perform a self-update. It verifies if an update has occurred within the last 24 hours and handles different operating systems for locating the configuration file. It also checks if the CLI is already at the latest version before proceeding with an update. ```fsharp // Check if we should skip self update // (if we've updated in the last 24 hours, don't update) let hasUpdatedInLastDay (configPath: String) : Bool = match Config.read configPath with | Ok config -> match config |> Stdlib.Dict.get "lastUpdateTimestamp" with | None -> false | Some timestamp -> let secondsSinceLastUpdate = ((Stdlib.DateTime.now ()) |> Stdlib.DateTime.toSeconds) - (timestamp |> Stdlib.Int64.parse |> Builtin.unwrap) let oneDayInSeconds = 86400L // TODO: show math secondsSinceLastUpdate < oneDayInSeconds | Error e -> false let selfUpdateIfRelevant () : Stdlib.Result.Result = // if not installed, ignore -- nothing to self-update let configPath = match (Stdlib.Cli.OS.getOS ()) with | Ok Windows -> let homeDirectory = (Stdlib.Cli.PowerShell.getHomeDirectory ()) |> Builtin.unwrap $"{homeDirectory}\.darklang\config.json" | Ok Linux | Ok MacOS -> "$HOME/.darklang/config.json" if Stdlib.Bool.not (Builtin.fileExists configPath) then Stdlib.Result.Result.Ok() // don't update _too_ often else if hasUpdatedInLastDay configPath then Stdlib.printLine "Skipping self-update because we've updated in the last 24 hours" Stdlib.Result.Result.Ok() else match isAtLatestVersion configPath with | Ok true -> Stdlib.Result.Result.Ok() | Ok false -> (Stdlib.Cli.Host.getRuntimeHost ()) |> Stdlib.Result.andThen (fun host -> Installation.Install.installOrUpdateLatestRelease host) | Error e -> Stdlib.Result.Result.Error e if Stdlib.List.member_v0 args "--skip-self-update" then let newArgs = args |> Stdlib.List.filter (fun arg -> arg != "--skip-self-update") processNormally newArgs else match Installation.selfUpdateIfRelevant () with | Ok _ -> processNormally args | Error e -> Stdlib.printLine $"Failed to run self-update: {e}\nProceeding anyway." processNormally args ``` -------------------------------- ### Darklang Enum - Two Indented Arguments Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Presents an enum with two arguments where each argument is on a new line. This improves the readability of enums with multiple data fields. ```darklang MyEnum.TwoArgs( 1L, 2L ) ``` -------------------------------- ### Restart Dnsmasq service on macOS Source: https://github.com/darklang/dark/blob/main/docs/dnsmasq.md Restarts the Dnsmasq service on macOS using Homebrew's service management. This command applies any recent configuration changes made to Dnsmasq. ```bash sudo brew services restart dnsmasq ``` -------------------------------- ### Darklang Enum - Single Integer Argument Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Enum.txt Illustrates an enum case that accepts a single integer argument. The argument is appended directly after the enum case identifier. ```darklang MyEnum.OneArg 1L ``` -------------------------------- ### Darklang Record with Nested Record Source: https://github.com/darklang/dark/blob/main/tree-sitter-darklang/test/corpus/exhaustive/exprs/Record.txt Demonstrates a record containing another nested record. This is useful for representing hierarchical data structures, such as an address within a person record. ```Darklang Person {name = "John"; address = Address {city = "New York"; street = "5th Avenue"}} ```