### Start state TODO block in Realm React Native tutorial Source: https://mongodb-university.github.io/Bluehawk/tutorials Shows the start state of the Realm React Native tutorial, where the code is a TODO block. Use this as the starting point for a checkpointed tutorial branch. ```javascript // TODO: Open the project realm with the given configuration and store // it in the realmRef. Once opened, fetch the Task objects in the realm, // sorted by name, and attach a listener to the Task collection. When the // listener fires, use the setTasks() function to apply the updated Tasks // list to the state. ``` -------------------------------- ### Install Bluehawk as a module Source: https://mongodb-university.github.io/Bluehawk/install Installs Bluehawk as a local dependency in the current project, suitable for using it as a module in your code. ```bash npm install bluehawk ``` -------------------------------- ### Plugin Definition Example Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules A plugin is a Node module that exports a register() function. This example demonstrates adding a CLI option and subscribing to Bluehawk events. ```javascript // MyPlugin.js exports.register = (args) => { // Add a new CLI option args.yargs.option("myNewOption", { string: true }); // Add Bluehawk listener args.bluehawk.subscribe((result) => { console.log("Plugin called for file", result.document.path); }); }; ``` -------------------------------- ### Install Bluehawk with NPM Source: https://mongodb-university.github.io/Bluehawk Install Bluehawk globally via NPM. Run this command in a terminal to make the Bluehawk CLI available for processing tagged source files. ```bash npm install -g bluehawk ``` -------------------------------- ### Start state of the clean-up snippet Source: https://mongodb-university.github.io/Bluehawk/tutorials The same snippet after Bluehawk extraction in the start state. Shows only the TODO block, with the final code removed. ```javascript return () => { // cleanup function const projectRealm = realmRef.current; if (projectRealm) { // TODO: close the project realm and reset the realmRef's // current value to null. setTasks([]); } }; ``` -------------------------------- ### Annotate a tutorial snippet with Bluehawk state tags Source: https://mongodb-university.github.io/Bluehawk/tutorials Annotated tutorial snippet with Bluehawk tags. Uses :snippet-start: and :snippet-end: to delimit the snippet, and :state-start: final / :state-end: :state-uncomment-start: start to mark the final and start states. The double-commented TODO block is uncommented in the start state. ```javascript // :snippet-start: clean-up return () => { // cleanup function const projectRealm = realmRef.current; if (projectRealm) { // :state-start: final projectRealm.close(); realmRef.current = null; // :state-end: :state-uncomment-start: start //// TODO: close the project realm and reset the realmRef's //// current value to null. // :state-uncomment-end: setTasks([]); } }; // :snippet-end: ``` -------------------------------- ### Create checkpointed tutorial states with Bluehawk Source: https://mongodb-university.github.io/Bluehawk/use-cases Mark up a tutorial source file with :state-start: and :state-end: tags to define different checkpoints. Running `bluehawk copy` with `--state start` produces a version with only the TODO placeholder, while `--state final` produces a version with the final implementation and no TODO. ```swift // WelcomeViewController.swift // ... more code ... // :snippet-start: signUp @objc func signUp() { // :state-start: final setLoading(true); app.emailPasswordAuth.registerUser(email: email!, password: password!, completion: { [weak self](error) in DispatchQueue.main.async { self!.setLoading(false); ... } }) // :state-end: // :state-start: start // TODO: Use the app's emailPasswordAuth to registerUser with the email and password. // When registered, call signIn(). // :state-end: } // :snippet-end: // ... more code ... ``` ```swift // WelcomeViewController.swift // ... more code ... @objc func signUp() { setLoading(true); app.emailPasswordAuth.registerUser(email: email!, password: password!, completion: { [weak self](error) in DispatchQueue.main.async { self!.setLoading(false); ... } }) } // ... more code ... ``` -------------------------------- ### Replace tag example with models Source: https://mongodb-university.github.io/Bluehawk/code-snippets Shows a complete example of using the `replace` tag to remove the `ReadWriteDataExamples_` prefix from Realm model class names. The replace tag wraps a code block containing model definitions, and the terms map specifies the replacement. ```swift // :replace-start: { // "terms": { // "ReadWriteDataExamples_": "" // } // } import XCTest import RealmSwift // :snippet-start: models class ReadWriteDataExamples_DogToy: Object { @Persisted var name = "" } class ReadWriteDataExamples_Dog: Object { @Persisted var name = "" @Persisted var age = 0 @Persisted var color = "" @Persisted var currentCity = "" // To-one relationship @Persisted var favoriteToy: ReadWriteDataExamples_DogToy? } class ReadWriteDataExamples_Person: Object { @Persisted(primaryKey: true) var id = 0 @Persisted var name = "" // To-many relationship - a person can have many dogs @Persisted var dogs: List // Inverse relationship - a person can be a member of many clubs @Persisted(originProperty: "members") var clubs: LinkingObjects } class ReadWriteDataExamples_DogClub: Object { @Persisted var name = "" @Persisted var members: List } // :snippet-end: // Many more lines of code examples, until eventually, we end the replace // :replace-end: ``` -------------------------------- ### Bluehawk snippet-start tag example Source: https://mongodb-university.github.io/Bluehawk/code-snippets Shows the syntax for a Bluehawk snippet-start tag with a descriptive title. The output file name concatenates the unit test file name, 'snippet', the descriptive name, and the file type. ```plaintext // :snippet-start: person-model ``` -------------------------------- ### process Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Executes the tags on the given source. Use subscribe to get results. ```APIDOC ## process ### Description Executes the tags on the given source. Use subscribe to get results. ### Parameters - `parseResult` (ParseResult) - Required - The parse result to process. - `processOptions?` (ProcessOptions) - Optional - Options for processing. ### Returns `Promise` ``` -------------------------------- ### Extracted code snippet output Source: https://mongodb-university.github.io/Bluehawk/code-snippets The final code example after using the Bluehawk CLI to extract the snippet. It includes only the lines between the snippet-start and snippet-end tags, excluding the import statement. ```swift class Person: Object { // Required string property @Persisted var name: String = "" // Optional string property @Persisted var address: String? // Optional integral type property @Persisted var age: Int? } ``` -------------------------------- ### Run bluehawk check in GitHub Actions Source: https://mongodb-university.github.io/Bluehawk/continuous-integration Executes the bluehawk check command to validate files within the examples and tutorial directories while ignoring specific file types. ```bash npx bluehawk check -i "*.md" -i "*.properties" -i "*.lock" examples tutorial ``` -------------------------------- ### Extract tested code snippet with Bluehawk tags Source: https://mongodb-university.github.io/Bluehawk/use-cases Mark up a unit test source file with Bluehawk tags (:snippet-start:, :snippet-end:, :remove-start:, :remove-end:) to extract a tested code example. Running the `snip` command produces a snippet file named `SomeTest.snippet.some-example.swift` containing only the marked lines, with the test boilerplate removed. ```swift // SomeTest.swift // ... more tests ... func someTest() { // :snippet-start: some-example let person = getPerson() // :remove-start: // remove test boilerplate from the code block XCTAssert(person.name != "Keith") // :remove-end: person.doSomething { person.doSomethingElse() } // :snippet-end: } // ... more tests ... ``` ```swift let person = getPerson() person.doSomething { person.doSomethingElse() } ``` -------------------------------- ### Annotated Swift unit test with snippet tags Source: https://mongodb-university.github.io/Bluehawk/code-snippets Example of annotating a Swift class with Bluehawk snippet-start and snippet-end tags. The import statement is excluded from the snippet. The output file becomes Models.snippet.person-model.swift. ```swift import RealmSwift // :snippet-start: person-model class Person: Object { // Required string property @Persisted var name: String = "" // Optional string property @Persisted var address: String? // Optional integral type property @Persisted var age: Int? } // :snippet-end: ``` -------------------------------- ### State-uncomment: Main.java, bluehawk snip command, and output Source: https://mongodb-university.github.io/Bluehawk/reference/tags Use this workflow to see how `state-uncomment` removes one layer of comments from a state in the produced output. The `Main.java` file defines two states: `add-one` (active) and `subtract-one` (uncommented). Running the `bluehawk snip` command with `--state subtract-one` produces `Main.snippet.add-or-subtract.java`, where the `example--;` line is uncommented and the `example++;` line is omitted. The note clarifies that Bluehawk trims one layer of comments from the state in the produced code block. ```java public class Main { public static void main(String[] args){ // :snippet-start: add-or-subtract int example = 1; // :state-start: add-one example++; // :state-end: // :state-uncomment-start: subtract-one //example--; // :state--uncomment-end: System.out.println("Example: " + example); // :snippet-end: } } ``` ```bash bluehawk snip Main.java -o . --state subtract-one ``` ```java int example = 1; example--; System.out.println("Example: " + example); ``` -------------------------------- ### Include a snippet in Docusaurus with raw-loader and CodeBlock Source: https://mongodb-university.github.io/Bluehawk/code-snippets In Docusaurus, import the generated file using raw-loader and render it inside a CodeBlock component. The example imports a Dart snippet and sets the language to dart. ```JavaScript import QuickStartTestSnippetUpdateRealmObjectDart from "!!raw-loader!@site/generated/flutter/quick_start_test.snippet.update-realm-object.dart"; {QuickStartTestSnippetUpdateRealmObjectDart} ``` -------------------------------- ### Uncomment tag: input, command, and output Source: https://mongodb-university.github.io/Bluehawk/reference/tags Shows the effect of the `uncomment` tag on a Java file. The input file contains commented lines marked with `:uncomment-start:` and `:uncomment-end:`; running `bluehawk copy Main.java -o .` removes the comment markers and the leading `//` from the `example--;` line in the output. ```java public class Main { public static void main(String[] args){ int example = 1; // :uncomment-start: //example--; // :uncomment-end: example++; System.out.println("Example: " + example); } } ``` ```bash bluehawk copy Main.java -o . ``` ```java public class Main { public static void main(String[] args){ int example = 1; example--; example++; System.out.println("Example: " + example); } } ``` -------------------------------- ### Extract code snippets with bluehawk snip --state Source: https://mongodb-university.github.io/Bluehawk/tutorials Use the Bluehawk CLI to extract code snippets for the 'start' and 'final' states from the same annotated file. The input file is identical; only the output directory and --state flag differ. Generated files follow the same naming convention, so the output file name is TasksProvider.snippet.clean-up.js in both cases. ```shell bluehawk snip -o source/tutorial/generated/code/start/ tutorial/rn/providers/TasksProvider.js --state=start ``` ```shell bluehawk snip -o source/tutorial/generated/code/final/ tutorial/rn/providers/TasksProvider.js --state=final ``` -------------------------------- ### Remove tag in Java with Bluehawk CLI and output Source: https://mongodb-university.github.io/Bluehawk/reference/tags Shows the `remove` tag in a Java file, the Bluehawk CLI command to generate output, and the resulting snippet without the `assert` line. The `remove` tag hides the spanned range from output, useful for hiding assertions and state setup. ```java public class Main { public static void main(String[] args){ // :snippet-start: division int dividend = 11; int divisor = 3; int quotient = dividend / divisor; assert(quotient == 3) // :remove: System.out.println(dividend + " / " + divisor + " = " + quotient); // :snippet-end: } } ``` ```bash bluehawk snip Main.java -o . ``` ```java int dividend = 11; int divisor = 3; int quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " = " + quotient); ``` -------------------------------- ### constructor Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Creates a new Bluehawk instance with optional configuration. ```APIDOC ## constructor ### Description Creates a new Bluehawk instance with optional configuration. ### Parameters - `configuration?` (BluehawkConfiguration) - Optional - Configuration for the Bluehawk instance. ### Returns `Bluehawk` ``` -------------------------------- ### Register a Bluehawk plugin with register() and load it via --plugin Source: https://mongodb-university.github.io/Bluehawk/develop/plugins Create a plugin file that implements the register() function to add tags, CLI commands, and listeners. Use the --plugin flag to load the plugin when running bluehawk; the flag can be passed multiple times to load different plugins or compose plugins. ```javascript // myPlugin.js exports.register = (bluehawk) => { // Register a new tag, :my-tag: bluehawk.registerTag("my-tag", { rules: [], process: (request) => { // Execute tag }, }); // Register a document listener bluehawk.subscribe((finishedDocument) => { // Do something with finishedDocument }); }; ``` ```bash bluehawk --plugin ./myPlugin source.txt ``` -------------------------------- ### Include a snippet in reStructured Text (rST) with literalinclude Source: https://mongodb-university.github.io/Bluehawk/code-snippets Use the rST literalinclude directive to include a generated code file. The example specifies the file path and language (swift). ```reStructuredText .. literalinclude:: /examples/generated/code/start/ReadWriteData.snippet.models.swift :language: swift ``` -------------------------------- ### Extract code from a directory with bluehawk snip Source: https://mongodb-university.github.io/Bluehawk/code-snippets Generates Bluehawk output for all files in the examples/ios/Examples directory. New or updated output files are generated for all changes. ```bash bluehawk snip -o source/examples/generated/code/start/ examples/ios/Examples ``` -------------------------------- ### Block remove tag Source: https://mongodb-university.github.io/Bluehawk/reference/tags Use the block form of the remove tag to mark a range of lines for removal. The start and end tags are placed in comments on the lines that begin and end the range. ```java public class Main { public static void main(String[] args){ int a = 2; int b = 3; int c = a * b; // :remove-start: assert(c == 6); // :remove-end: System.out.println("Hello world!"); } } ``` -------------------------------- ### Snippet tag with identifier Source: https://mongodb-university.github.io/Bluehawk/reference/tags Use the snippet tag with a unique identifier to mark a code snippet. The identifier must be unique to the file. This example also nests a remove block inside the snippet. ```java public class Main { public static void main(String[] args){ // :snippet-start: multiply-abc int a = 2; int b = 3; int c = a * b; // :remove-start: assert(c == 6); // :remove-end: System.out.println("Hello world!"); // :snippet-end: } } ``` -------------------------------- ### makeCstVisitor(parser, getParser?) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a CST visitor for the given parser. Optionally accepts a function to retrieve a visitor by parser ID. ```APIDOC ## makeCstVisitor(parser, getParser?) ### Description Creates a CST visitor for the given parser. Optionally accepts a function to retrieve a visitor by parser ID. ### Parameters - `parser` (RootParser) - Required - The root parser. - `getParser?` (function) - Optional - A function that takes a parser ID and returns an IVisitor or undefined. ### Returns `IVisitor` ``` -------------------------------- ### pathWithInfix(infix) Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Document Returns a path with an infix inserted. The infix is a string that is inserted into the path. ```APIDOC ## pathWithInfix(infix) ### Description Returns a path with an infix inserted. ### Parameters - **infix** (string) - Required - The infix to insert into the path. ### Returns - **string** - The resulting path. ``` -------------------------------- ### makePushParserTokens(pushPattern, popPattern, configuration) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a pair of token types for push/pop parsing based on the given patterns and configuration. ```APIDOC ## makePushParserTokens(pushPattern, popPattern, configuration) ### Description Creates a pair of token types for push/pop parsing based on the given patterns and configuration. ### Parameters - `pushPattern` (RegExp) - Required - The pattern for the push token. - `popPattern` (RegExp) - Required - The pattern for the pop token. - `configuration` (PushParserTokenConfiguration) - Required - The configuration for the push parser tokens. ### Returns [`TokenType`, `TokenType`] ``` -------------------------------- ### makeParser(languageSpecification) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a parser for the given language specification. ```APIDOC ## makeParser(languageSpecification) ### Description Creates a parser for the given language specification. ### Parameters - `languageSpecification` (LanguageSpecification) - Required - The language specification. ### Returns `IParser` ``` -------------------------------- ### ProcessOptions Interface Source: https://mongodb-university.github.io/Bluehawk/develop/api/interfaces/ProcessOptions The ProcessOptions interface defines configuration options for the Bluehawk processor. It includes two properties: stripUnknownTags and waitForListeners, both of which are booleans. ```APIDOC ## Interface: ProcessOptions ### Description Configuration options for the Bluehawk processor. ### Properties #### stripUnknownTags - **Type**: boolean - **Optional**: Yes - **Description**: When true, unknown tags are stripped from the output. #### waitForListeners - **Type**: boolean - **Optional**: No - **Description**: When true, the processor waits for listeners to complete before finishing. ### Defined In - bluehawk/processor/Processor.ts:12 (stripUnknownTags) - bluehawk/processor/Processor.ts:11 (waitForListeners) ``` -------------------------------- ### Project Interface Source: https://mongodb-university.github.io/Bluehawk/develop/api/interfaces/Project The Project interface defines the structure for a project, including an optional ignore pattern and a required root path. ```APIDOC ## Interface: Project ### Properties #### ignore - **ignore** (`string` | `string[]`) - Optional - A pattern or list of patterns to ignore. #### rootPath - **rootPath** (`string`) - Required - The root path of the project. ``` -------------------------------- ### Final state completed code in Realm React Native tutorial Source: https://mongodb-university.github.io/Bluehawk/tutorials Shows the final state of the Realm React Native tutorial, with the completed code that opens the realm, fetches tasks, and attaches a listener. Use this as the completed branch for a checkpointed tutorial. ```javascript Realm.open(config).then((projectRealm) => { realmRef.current = projectRealm; const syncTasks = projectRealm.objects("Task"); let sortedTasks = syncTasks.sorted("name"); setTasks([...sortedTasks]); sortedTasks.addListener(() => { setTasks([...sortedTasks]); }); }); ``` -------------------------------- ### parseAndProcess Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Runs through all given source paths to parse and process them. ```APIDOC ## parseAndProcess ### Description Runs through all given source paths to parse and process them. ### Parameters - `path` (string | string[]) - Required - The path or paths to the directory or files to parse and process. - `optionsIn?` (ParseAndProcessOptions) - Optional - Options for parsing and processing. ### Returns `Promise` ``` -------------------------------- ### Replace tag: input, command, and output Source: https://mongodb-university.github.io/Bluehawk/reference/tags Shows the effect of the `replace` tag on a Java file. The input file contains a `:replace-start:` block with a JSON dictionary of terms; running `bluehawk copy Main.java -o .` replaces occurrences of the keys with their values in the output, such as `MyMainExample` becoming `Main` and the URL becoming `YOUR_REST_ENDPOINT_HERE`. ```java // :replace-start: { // "terms": { // "MyMainExample": "Main", // "www.example.com/rest/v1": "YOUR_REST_ENDPOINT_HERE" // } // } /* * MyMainExample -- a class that contains only a hello world main method * that defines a rest endpoint. */ public class MyMainExample { String rest_endpoint; public static void main(String[] args){ System.out.println("Hello world!"); rest_endpoint = "www.example.com/rest/v1" } } // :replace-end: ``` ```bash bluehawk copy Main.java -o . ``` ```java /* * Main -- a class that contains only a hello world main method * that defines a rest endpoint. */ public class Main { String rest_endpoint; public static void main(String[] args){ System.out.println("Hello world!"); rest_endpoint = "YOUR_REST_ENDPOINT_HERE" } } ``` -------------------------------- ### Extract code from a single file with bluehawk snip Source: https://mongodb-university.github.io/Bluehawk/code-snippets Extracts code snippets from the ReadWriteData.swift file and generates output files in source/examples/generated/code/start/. ```bash bluehawk snip -o source/examples/generated/code/start/ examples/ios/Examples/ReadWriteData.swift ``` -------------------------------- ### parse Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Parses the given source file into tags. ```APIDOC ## parse ### Description Parses the given source file into tags. ### Parameters - `source` (Document) - Required - The source document to parse. - `options?` (Object) - Optional - Options for parsing. - `options.languageSpecification?` (LanguageSpecification) - Optional - Language specification to use. - `options.reporter?` (ActionReporter) - Optional - Reporter for actions. ### Returns `ParseResult` ``` -------------------------------- ### new Document(destructured) Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Document Creates a new Document instance with the given properties. The destructured parameter includes optional attributes, modifiers, path, and text. ```APIDOC ## new Document(destructured) ### Description Creates a new Document instance. ### Parameters - **destructured** (Object) - Required - **attributes** (TagAttributes) - Optional - Attributes that a tag can store information in for later processing by listeners. - **modifiers** (Object) - Optional - Read-only attributes that contribute to the document's identity. - **path** (string) - Required - The original path of the document. - **text** (string | default) - Required - The source text as a conveniently editable magic string. ### Returns - **Document** - The new Document instance. ``` -------------------------------- ### makeLineTag(tag) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a line tag from the given tag definition. The tag must include a process function. ```APIDOC ## makeLineTag(tag) ### Description Creates a line tag from the given tag definition. The tag must include a process function. ### Parameters - `tag` (Tag & { attributesSchema?: undefined; process: (request: ProcessRequest) => NotPromise }) - Required - The tag definition. ### Returns `AnyTag` ``` -------------------------------- ### snip(args) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Executes the snip action with the given arguments, returning a promise that resolves when complete. ```APIDOC ## snip(args) ### Description Executes the snip action with the given arguments, returning a promise that resolves when complete. ### Parameters - `args` (WithActionReporter) - Required - The arguments for the snip action. ### Returns `Promise` ``` -------------------------------- ### CopyArgs.onBinaryFile Source: https://mongodb-university.github.io/Bluehawk/develop/api/interfaces/CopyArgs Hook for additional work after a binary file is processed. This method is part of the CopyArgs interface and can be implemented by users to customize behavior. ```APIDOC ## onBinaryFile(path) ### Description Hook for additional work after a binary file is processed. ### Method onBinaryFile ### Parameters - **path** (string) - Required - The path to the binary file. ### Returns `void` | `Promise` ### Defined in bluehawk/actions/copy.ts:18 ``` -------------------------------- ### Replace tag syntax Source: https://mongodb-university.github.io/Bluehawk/code-snippets Shows the minimal syntax for the `replace` tag, defining a terms map that replaces `ReadWriteDataExamples_` with an empty string. ```swift // :replace-start: { // "terms": { // "ReadWriteDataExamples_": "" // } // } ``` -------------------------------- ### makeId(newPath, modifiers?) Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Document Returns a uniform path + modifier combination to uniquely identify a file instance. ```APIDOC ## makeId(newPath, modifiers?) ### Description Returns a uniform path + modifier combination to uniquely identify a file instance. ### Parameters - **newPath** (string) - Required - The new path for the file. - **modifiers** (Object) - Optional - Additional modifiers to include in the ID. ### Returns - **string** - The unique identifier. ``` -------------------------------- ### Emphasize tag in Java with Bluehawk CLI and RST output Source: https://mongodb-university.github.io/Bluehawk/reference/tags Shows the `emphasize` tag in a Java file, the Bluehawk CLI command to generate RST output, and the resulting RST snippet with `:emphasize-lines: 3`. The `emphasize` tag marks a line for highlighting in formatted output; it requires the `--format` flag to take effect. ```java public class Main { public static void main(String[] args){ // :snippet-start: modulo int dividend = 11; int divisor = 3; int modulus = dividend % divisor; // :emphasize: System.out.println(dividend + " % " + divisor + " = " + modulus); // :snippet-end: } } ``` ```bash bluehawk snip Main.java -o . --format=rst ``` ```rst .. code-block:: java :emphasize-lines: 3 int dividend = 11; int divisor = 3; int modulus = dividend % divisor; System.out.println(dividend + " % " + divisor + " = " + modulus); ``` -------------------------------- ### Swift source with remove tags Source: https://mongodb-university.github.io/Bluehawk/code-snippets The original Swift code with :remove-start: and :remove-end: tags around a test assertion that should be removed from the documentation output. ```swift func testPasswordResetFunc() async { // :snippet-start: password-reset-function let app = App(id: YOUR_REALM_APP_ID) let client = app.emailPasswordAuth let email = "forgot.my.password@example.com" let newPassword = "mynewpassword12345" // The password reset function takes any number of // arguments. You might ask the user to provide answers to // security questions, for example, to verify the user // should be able to complete the password reset. let args: [AnyBSON] = [] // This SDK call maps to the custom password reset // function that you define in the backend do { try await client.callResetPasswordFunction(email: email, password: newPassword, args: args) print("Password reset successful!") } catch { print("Password reset failed: \(error.localizedDescription)") // :remove-start: XCTAssertEqual(error.localizedDescription, "user not found") // :remove-end: } // :snippet-end: } ``` -------------------------------- ### bluehawk snip command syntax Source: https://mongodb-university.github.io/Bluehawk/code-snippets The most common Bluehawk CLI command. Pass the output directory and the input file or directory. ```bash bluehawk snip -o ``` -------------------------------- ### bluehawk copy command Source: https://mongodb-university.github.io/Bluehawk/reference/cli Outputs full processed files while maintaining directory structure. Supports ignoring files, specifying states, and renaming files via a JSON string. ```bash bluehawk copy --output ``` -------------------------------- ### State tag and snip --state flag Source: https://mongodb-university.github.io/Bluehawk/reference/tags The state tag marks ranges of content as part of a named state. The snip command with the --state flag includes only content from the specified state, removing other state blocks. Without --state, state blocks are excluded. The output files are named Main.snippet.example.java for both states. ```java public class Main { public static void main(String[] args){ // :snippet-start: example int example = 1; // :state-start: hello-world System.out.println("Hello world!"); // :state-end: // :state-start: hello-user System.out.println("Hello user!"); // :state-end: example++; // :snippet-end: } } ``` ```bash bluehawk snip Main.java -o . --state hello-user ``` ```java int example = 1; System.out.println("Hello user!"); example++; ``` ```bash bluehawk snip Main.java -o . --state hello-world ``` ```java int example = 1; System.out.println("Hello world!"); example++; ``` -------------------------------- ### withLogLevelOption(yargs) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Adds the logLevel option to the given yargs instance. ```APIDOC ## withLogLevelOption(yargs) ### Description Adds the logLevel option to the given yargs instance. ### Type Parameters - `T` - The type of the yargs arguments. ### Parameters - `yargs` (Argv) - Required - The yargs instance. ### Returns `Argv` ``` -------------------------------- ### makePayloadPattern(pattern, getPayload) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a custom pattern that extracts a payload from a query using the provided getPayload function. ```APIDOC ## makePayloadPattern(pattern, getPayload) ### Description Creates a custom pattern that extracts a payload from a query using the provided getPayload function. ### Type Parameters - `PayloadType` - The type of the payload. ### Parameters - `pattern` (RegExp) - Required - The regular expression pattern. - `getPayload` (function) - Required - A function that takes a PayloadQuery and returns the payload. ### Returns `ICustomPattern` ``` -------------------------------- ### Output after replace Source: https://mongodb-university.github.io/Bluehawk/code-snippets The resulting code after the `replace` tag removes the `ReadWriteDataExamples_` prefix from all model names. ```swift class DogToy: Object { @Persisted var name = "" } class Dog: Object { @Persisted var name = "" @Persisted var age = 0 @Persisted var color = "" @Persisted var currentCity = "" // To-one relationship @Persisted var favoriteToy: DogToy? } class Person: Object { @Persisted(primaryKey: true) var id = 0 @Persisted var name = "" // To-many relationship - a person can have many dogs @Persisted var dogs: List // Inverse relationship - a person can be a member of many clubs @Persisted(originProperty: "members") var clubs: LinkingObjects } class DogClub: Object { @Persisted var name = "" @Persisted var members: List } ``` -------------------------------- ### makeLineCommentToken(pattern) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Creates a token type for line comments based on the given regular expression pattern. ```APIDOC ## makeLineCommentToken(pattern) ### Description Creates a token type for line comments based on the given regular expression pattern. ### Parameters - `pattern` (RegExp) - Required - The regular expression pattern for line comments. ### Returns `TokenType` ``` -------------------------------- ### bluehawk snip command Source: https://mongodb-university.github.io/Bluehawk/reference/cli Generates snippet files containing content from Bluehawk tags. By default, it omits state tag contents unless the --state flag is used. ```bash bluehawk snip --output ``` -------------------------------- ### withStateOption(yargs): Argv Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Adds an optional 'state' option to a Yargs command. This is a utility function for CLI builders that need to accept a state parameter. ```APIDOC ## withStateOption(yargs): Argv ### Description Adds an optional `state` option to a Yargs command. This is a utility function for CLI builders that need to accept a state parameter. ### Signature `withStateOption(yargs: Argv): Argv` ### Type Parameters - `T` - The argument type of the input Yargs instance. ### Parameters - `yargs` (Argv) - Required - The Yargs instance to which the state option will be added. ### Returns - `Argv` - A new Yargs instance with an optional `state` string option. ### Defined in `bluehawk/options.ts:39` ``` -------------------------------- ### withIgnoreOption(yargs) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Adds the ignore option to the given yargs instance. ```APIDOC ## withIgnoreOption(yargs) ### Description Adds the ignore option to the given yargs instance. ### Type Parameters - `T` - The type of the yargs arguments. ### Parameters - `yargs` (Argv) - Required - The yargs instance. ### Returns `Argv` ``` -------------------------------- ### withOutputOption(yargs) Source: https://mongodb-university.github.io/Bluehawk/develop/api/modules Adds the output option to the given yargs instance. ```APIDOC ## withOutputOption(yargs) ### Description Adds the output option to the given yargs instance. ### Type Parameters - `T` - The type of the yargs arguments. ### Parameters - `yargs` (Argv) - Required - The yargs instance. ### Returns `Argv` ``` -------------------------------- ### Final state of the clean-up snippet Source: https://mongodb-university.github.io/Bluehawk/tutorials The same snippet after Bluehawk extraction in the final state. Shows only the final code, with the TODO block removed. ```javascript return () => { // cleanup function const projectRealm = realmRef.current; if (projectRealm) { projectRealm.close(); realmRef.current = null; setTasks([]); } }; ``` -------------------------------- ### waitForListeners Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Waits for all listeners to complete processing. ```APIDOC ## waitForListeners ### Description Waits for all listeners to complete processing. ### Returns `Promise` ``` -------------------------------- ### Attribute list syntax Source: https://mongodb-university.github.io/Bluehawk/reference/tags Attribute lists are JSON objects that must use double quotes for fields. The opening line of an attribute list must appear on the same line as the tag itself. ```plaintext // :some-tag-start: { // "field": "value" // } // :some-tag-end: ``` -------------------------------- ### ActionReporter Interface Source: https://mongodb-university.github.io/Bluehawk/develop/api/interfaces/ActionReporter The ActionReporter interface defines methods for handling various events during Bluehawk actions. It includes properties for error count and log level, and methods for reporting binary files, errors, parsing, writing, and state events. ```APIDOC ## Interface: ActionReporter ### Description Handles various events for user information. ### Implemented by - ConsoleActionReporter ### Properties #### errorCount - **Type**: number (Readonly) - **Description**: The number of errors encountered. #### logLevel - **Type**: LogLevel - **Description**: The current log level. ### Methods #### onBinaryFile(event) - **Parameters**: - event (FileEvent) - **Returns**: void - **Description**: Handles a binary file event. #### onBluehawkErrors(event) - **Parameters**: - event (BluehawkErrorsEvent) - **Returns**: void - **Description**: Handles Bluehawk errors event. #### onFileError(event) - **Parameters**: - event (FileErrorEvent) - **Returns**: void - **Description**: Handles a file error event. #### onFileParsed(event) - **Parameters**: - event (FileParsedEvent) - **Returns**: void - **Description**: Handles a file parsed event. #### onFileWritten(event) - **Parameters**: - event (FileWrittenEvent) - **Returns**: void - **Description**: Handles a file written event. #### onIdsUnused(event) - **Parameters**: - event (IdsUnusedEvent) - **Returns**: void - **Description**: Handles an unused IDs event. #### onParserNotFound(event) - **Parameters**: - event (ParserNotFoundEvent) - **Returns**: void - **Description**: Handles a parser not found event. #### onStateNotFound(event) - **Parameters**: - event (StateNotFoundEvent) - **Returns**: void - **Description**: Handles a state not found event. #### onStatesFound(event) - **Parameters**: - event (StatesFoundEvent) - **Returns**: void - **Description**: Handles a states found event. #### onWriteFailed(event) - **Parameters**: - event (WriteFailedEvent) - **Returns**: void - **Description**: Handles a write failed event. #### printSummary() - **Returns**: void - **Description**: Requests the summary of all things reported so far. Users should call this after an action is complete. ``` -------------------------------- ### addLanguage Source: https://mongodb-university.github.io/Bluehawk/develop/api/classes/Bluehawk Specify the special patterns for a given language. ```APIDOC ## addLanguage ### Description Specify the special patterns for a given language. ### Parameters - `forFileExtension` (string | string[]) - Required - The file extension(s) to associate with the language specification. - `languageSpecification` (LanguageSpecification) - Required - The language specification defining special patterns. ### Returns `void` ```