### Manage Dependencies and Development Source: https://github.com/shellicar/reference-foundation/blob/main/packages/ui-nuxt/README.md Commands to install project dependencies and start the local development server. The development server utilizes the .playground directory to test the layer in isolation. ```bash pnpm install pnpm dev ``` -------------------------------- ### Publish and Install Nuxt Layer Source: https://github.com/shellicar/reference-foundation/blob/main/packages/ui-nuxt/README.md Instructions for publishing the layer to the NPM registry and installing it as a dependency in a target Nuxt project. ```bash npm publish --access public npm install --save your-layer ``` -------------------------------- ### Start Development Server - Nuxt 3 Starter Source: https://github.com/shellicar/reference-foundation/blob/main/apps/nuxt-webapp/README.md Starts the Nuxt 3 development server, typically accessible at http://localhost:3000. This command is used for local development and testing. ```bash # npm npm run dev # pnpm pnpm run dev # yarn yarn dev # bun bun run dev ``` -------------------------------- ### Install Dependencies - Nuxt 3 Starter Source: https://github.com/shellicar/reference-foundation/blob/main/apps/nuxt-webapp/README.md Installs project dependencies using various package managers. Ensure you have Node.js and your chosen package manager (npm, pnpm, yarn, or bun) installed. ```bash # npm npm install # pnpm pnpm install # yarn yarn install # bun bun install ``` -------------------------------- ### GitVersion MainLine Configuration Example Source: https://github.com/shellicar/reference-foundation/blob/main/README.md An example configuration for GitVersion using the MainLine mode. This mode is suitable for continuous development workflows where each commit on the main branch can be a potential release. ```yaml mode: MainLine branches: {} ignore: sha: [] merge-message-formats: {} ``` -------------------------------- ### Deploy Multi-role Configuration with Monitoring Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Installs the required Loki plugin and starts a multi-role Temporal Server deployment including Grafana and Prometheus. ```bash docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions docker compose -f docker-compose-multirole.yaml up ``` -------------------------------- ### Start Temporal Services via Docker Compose Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Command to initialize the Temporal services using the configured docker-compose file. ```bash docker-compose up ``` -------------------------------- ### Configure Nuxt Layer Extension Source: https://github.com/shellicar/reference-foundation/blob/main/packages/ui-nuxt/README.md How to register the installed layer within the nuxt.config file of a consuming project using the extends property. ```typescript defineNuxtConfig({ extends: 'your-layer' }) ``` -------------------------------- ### Start Temporal Server with Docker Compose Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Commands to clone the repository and launch a local Temporal Server instance using the default docker-compose configuration. ```bash git clone https://github.com/temporalio/docker-compose.git cd docker-compose docker-compose up ``` -------------------------------- ### Get GitVersion Full Version Output Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Retrieves the full version information generated by GitVersion, including build metadata. This command is useful for inspecting all available version variables. ```shell $ gitversion -version ``` ```shell > dotnet-gitversion -version ``` -------------------------------- ### Manage Node.js versions with NVM Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Uses the .nvmrc file to switch to or install the required Node.js version for the project. This ensures environment consistency across all contributor machines. ```shell nvm use ``` -------------------------------- ### Run Svelte development server Source: https://github.com/shellicar/reference-foundation/blob/main/apps/svelte-webapp/README.md Starts the local development server for a Svelte project. Supports optional flags like opening the application in a browser tab automatically. ```bash npm run dev # or start the server and open the app in a new browser tab npm run dev -- --open ``` -------------------------------- ### Azure Monitor Setup with OpenTelemetry and Winston (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Configures Azure Monitor using OpenTelemetry for comprehensive application observability. It integrates with Winston logging and supports various instrumentation options including HTTP, Azure SDK, and MongoDB. Dependencies include '@azure/monitor-opentelemetry', '@opentelemetry/resources', '@opentelemetry/semantic-conventions', and 'applicationinsights'. ```typescript // packages/monitor/src/monitor.ts - Azure Monitor setup import { type AzureMonitorOpenTelemetryOptions, useAzureMonitor } from '@azure/monitor-opentelemetry'; import { resourceFromAttributes } from '@opentelemetry/resources'; import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'; import { TelemetryClient } from 'applicationinsights'; export type AzureMonitorConfig = { service?: { name?: string; namespace?: string; instanceId?: string }; samplingRatio?: number; enableLiveMetrics?: boolean; }; export const getMonitor = (config: AzureMonitorConfig = {}) => { const customResource = resourceFromAttributes({ [ATTR_SERVICE_NAME]: config.service?.name, }); const options: AzureMonitorOpenTelemetryOptions = { instrumentationOptions: { winston: { enabled: true }, http: { enabled: true }, azureSdk: { enabled: true }, mongoDb: { enabled: true }, redis: { enabled: true }, }, enableLiveMetrics: config.enableLiveMetrics ?? true, samplingRatio: config.samplingRatio, resource: customResource, azureMonitorExporterOptions: { connectionString: process.env.APPLICATIONINSIGHTS_CONNECTION_STRING, }, }; useAzureMonitor(options); return new TelemetryClient(); }; ``` -------------------------------- ### Setup Apollo Client for Web App (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Configures the Apollo Client for Svelte and Nuxt web applications. It sets up an `HttpLink` to the GraphQL endpoint and integrates with an `InMemoryCache` that includes custom type policies for scalar deserialization. ```typescript // apps/svelte-webapp/src/lib/client/createClient.ts - Apollo Client setup import { ApolloClient } from '@apollo/client/core/ApolloClient'; import type { ApolloLink } from '@apollo/client/link/core/ApolloLink'; import { from } from '@apollo/client/link/core/from'; import { HttpLink } from '@apollo/client/link/http/HttpLink'; import { cache } from './cache'; export const createClient = () => { const httpLink = new HttpLink({ uri: '/api/graphql', headers: { 'apollo-require-preflight': 'true', }, }); const link: ApolloLink = from([httpLink]); return new ApolloClient({ cache, link, }); }; ``` -------------------------------- ### Get Specific GitVersion SemVer Variable Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Retrieves a specific version variable, such as the SemVer (Semantic Versioning) string, from GitVersion. This is useful for integrating version numbers into build artifacts or deployment configurations. ```shell $ gitversion -showvariable SemVer ``` -------------------------------- ### Build and Preview Production Source: https://github.com/shellicar/reference-foundation/blob/main/packages/ui-nuxt/README.md Commands to compile the application for production deployment or static generation, and to preview the production build locally. ```bash pnpm build pnpm generate pnpm preview ``` -------------------------------- ### Preview Production Build - Nuxt 3 Starter Source: https://github.com/shellicar/reference-foundation/blob/main/apps/nuxt-webapp/README.md Locally previews the production build of the Nuxt 3 application. This is useful for testing the production environment before deployment. ```bash # npm npm run preview # pnpm pnpm run preview # yarn yarn preview # bun bun run preview ``` -------------------------------- ### Build for Production - Nuxt 3 Starter Source: https://github.com/shellicar/reference-foundation/blob/main/apps/nuxt-webapp/README.md Builds the Nuxt 3 application for production deployment. This command optimizes assets and generates a production-ready build. ```bash # npm npm run build # pnpm pnpm run build # yarn yarn build # bun bun run build ``` -------------------------------- ### Run Alternative Docker Compose Configurations Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Demonstrates how to launch the Temporal Server using specific configuration files, such as those utilizing MySQL and Elasticsearch. ```bash docker-compose -f docker-compose-mysql-es.yml up ``` -------------------------------- ### Deploy Infrastructure via Shell Script Source: https://github.com/shellicar/reference-foundation/blob/main/infrastructure/README.md Executes the infrastructure deployment process by navigating to the infrastructure directory and running the deploy.sh script with required environment variables. This script provisions Azure resources based on the provided SubscriptionId, UniqueId, and location parameters. ```bash cd infrastructure ./deploy.sh SubscriptionId=00000000-0000-0000-0000-000000000000 UniqueId=00000000-0000-0000-0000-000000000000 Suffix=250508-2138 Location=australiaeast Name=core-250508-2138 ``` -------------------------------- ### Deploy Temporal Server in Production Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Command to run the production-ready temporalio/server image, requiring external management of dependencies like Cassandra and Elasticsearch. ```bash docker run -e CASSANDRA_SEEDS=10.x.x.x \ -e KEYSPACE= \ -e VISIBILITY_KEYSPACE= \ -e SKIP_SCHEMA_SETUP=true \ -e NUM_HISTORY_SHARDS=1024 \ -e SERVICES=history,matching \ -e LOG_LEVEL=debug,info \ -e DYNAMIC_CONFIG_FILE_PATH=config/foo.yaml \ temporalio/server: ``` -------------------------------- ### Create a Svelte project using sv CLI Source: https://github.com/shellicar/reference-foundation/blob/main/apps/svelte-webapp/README.md Initializes a new Svelte project using the sv CLI tool. It supports creating projects in the current directory or a specified subdirectory. ```bash # create a new project in the current directory npx sv create # create a new project in my-app npx sv create my-app ``` -------------------------------- ### Build Custom Temporal Docker Image Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Commands to clone the Temporal repository, checkout a specific commit, and build a custom Docker image with the auto-setup target. ```bash git clone https://github.com/temporalio/temporal.git git checkout docker build . -t temporalio/auto-setup: --build-arg TARGET=auto-setup ``` -------------------------------- ### Build and preview Svelte production app Source: https://github.com/shellicar/reference-foundation/blob/main/apps/svelte-webapp/README.md Compiles the Svelte application for production deployment and provides a command to preview the generated build locally. ```bash npm run build # preview the production build npm run preview ``` -------------------------------- ### Configure and Use Temporal CLI (tctl) Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/README.md Sets up an alias for the tctl command within the Temporal container and demonstrates how to register a new namespace. ```bash alias tctl="docker exec temporal-admin-tools tctl" tctl --ns test-namespace namespace register -rd 1 ``` -------------------------------- ### Configure esbuild for Function Applications Source: https://context7.com/shellicar/reference-foundation/llms.txt Configures esbuild with custom plugins for GraphQL support and environment-aware build settings. It supports both a one-time build process and a continuous watch mode for development. ```typescript import GraphQLPlugin from '@shellicar/build-graphql/esbuild'; import { createBuildContext, defineConfig } from '@shellicar-core-foundation/build/esbuild'; const watch = process.argv.includes('--watch'); const graphqlPlugins = GraphQLPlugin({ globPattern: 'src/**/*.graphql', }); const configuration = defineConfig((x) => { x.plugins.push(graphqlPlugins); x.minify = !watch; return x; }); const ctx = await createBuildContext(configuration); if (watch) { await ctx.watch(); console.log('watching...'); } else { await ctx.rebuild(); ctx.dispose(); } ``` -------------------------------- ### Define Dynamic Configuration Properties in YAML Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/dynamicconfig/README.md Configures dynamic properties by mapping keys to values and optional constraints. Constraints include namespace, taskQueueName, and taskType, which must match query filters exactly for the value to be selected. ```yaml testGetBoolPropertyKey: - value: false - value: true constraints: namespace: "global-samples-namespace" - value: false constraints: namespace: "samples-namespace" testGetDurationPropertyKey: - value: "1m" constraints: namespace: "samples-namespace" taskQueueName: "longIdleTimeTaskqueue" testGetFloat64PropertyKey: - value: 12.0 constraints: namespace: "samples-namespace" testGetMapPropertyKey: - value: key1: 1 key2: "value 2" key3: - false - key4: true key5: 2.0 ``` -------------------------------- ### Configure GraphQL Context and DataLoaders Source: https://context7.com/shellicar/reference-foundation/llms.txt Sets up the request context for Azure Functions and initializes DataLoaders for batching requests. This pattern prevents N+1 query issues by grouping multiple requests for the same entity type. ```typescript import type { v4 } from '@as-integrations/azure-functions'; import { createLoaders } from '../../features/test-relations/dataLoaders'; import type { AppContext } from './types'; export const createContext = async (_ctx: v4.AzureFunctionsContextFunctionArgument): Promise => { return { loaders: createLoaders(), }; }; export const createLoaders = () => { const entity1Loader = new Entity1Loader(async (ids) => { console.log(`Loading Entity1 for IDs: ${ids}`); return ids.map((id) => entity1Data.find((e) => e.id === id)); }); const entity2Loader = new Entity2Loader(async (ids) => { console.log(`Loading Entity2 for IDs: ${ids}`); return ids.map((id) => entity2Data.find((e) => e.id === id)); }); return { entity1Loader, entity2Loader }; }; ``` -------------------------------- ### Activate Corepack with PNPM Version Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Ensures the correct version of PNPM, as specified in `package.json`, is used for the repository. This command activates the specified package manager version. ```shell corepack prepare --activate ``` -------------------------------- ### Update Release Version in .env File Source: https://github.com/shellicar/reference-foundation/blob/main/docker/temporalio/RELEASE.md This snippet shows how to update the TEMPORAL_VERSION and TEMPORAL_UI_VERSION variables in the .env file to reflect the new release version. Ensure these variables are updated accurately before committing. ```dotenv TEMPORAL_VERSION=1.16.2 TEMPORAL_UI_VERSION=2.7.1 ``` -------------------------------- ### Configure GraphQL Code Generation (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Sets up the GraphQL Code Generator CLI configuration for server-side applications. It defines the schema source, output file for generated TypeScript types, and plugins to use, including custom scalar mappings for `UUID`, `Instant`, and `EmailAddress`. ```typescript // apps/function-app/codegen.ts - Server-side codegen configuration import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { overwrite: true, schema: ['src/**/*.graphql'], generates: { 'src/generated/graphql-types.ts': { plugins: ['typescript', 'typescript-resolvers'], config: { useTypeImports: true, preResolveTypes: false, resolversNonOptionalTypename: true, strictScalars: true, scalars: { UUID: 'node:crypto#UUID', Instant: '@js-joda/core#Instant', EmailAddress: 'string', }, avoidOptionals: { field: true, inputValue: false, }, contextType: '../core/graphql/types#AppContext', maybeValue: 'T | null | undefined', }, }, './graphql.schema.json': { plugins: ['introspection'], }, }, }; export default config; // Run codegen: pnpm codegen ``` -------------------------------- ### List Syncpack Dependency Mismatches Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Checks for and lists any version inconsistencies in dependencies across packages within the monorepo. This script helps identify potential conflicts before they cause issues. ```shell pnpm list-mismatches ``` -------------------------------- ### Dependency Injection with @shellicar/core-di Source: https://context7.com/shellicar/reference-foundation/llms.txt Demonstrates the dependency injection system using a service collection pattern. Modules encapsulate registrations, and the `@dependsOn` decorator facilitates property injection. This system is crucial for managing dependencies in a modular and maintainable way. ```typescript // packages/server-common/src/module.ts - Defining a service module import type { IServiceCollection, IServiceModule } from '@shellicar/core-di'; import { Button } from './button'; import { Input } from './input'; import { IButton, IInput, IManager } from './interfaces'; import { Manager } from './Manager'; export class ManagerModule implements IServiceModule { registerServices(services: IServiceCollection): void { services.register(IButton).to(Button); services.register(IInput).to(Input); services.register(IManager).to(Manager); } } ``` ```typescript // packages/server-common/src/Manager.ts - Using dependency injection import { dependsOn } from '@shellicar/core-di'; import { IButton, IInput, IManager } from './interfaces'; export class Manager extends IManager { @dependsOn(IButton) private readonly button!: IButton; @dependsOn(IInput) private readonly input!: IInput; public async manage(): Promise { return `${await this.button.button()} ${await this.input.input()}`; } } ``` ```typescript // apps/function-app/src/core/di/container.ts - Building the container import { createServiceCollection } from '@shellicar/core-di'; import { ManagerModule } from '@shellicar/core-foundation/server-common/module'; const services = createServiceCollection(); services.registerModules(ManagerModule); export const container = services.buildProvider(); ``` -------------------------------- ### Fix Syncpack Dependency Mismatches Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Automatically resolves and aligns dependency versions across all packages in the monorepo. This script ensures consistent dependency versions, reducing the risk of conflicts. ```shell pnpm fix-mismatches ``` -------------------------------- ### Upgrade Bicep via Azure CLI Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Updates the Bicep CLI tool to the latest version using the Azure CLI. This is necessary to maintain compatibility with infrastructure-as-code definitions. ```shell az bicep upgrade ``` -------------------------------- ### Implement GraphQL Resolvers with DataLoaders Source: https://context7.com/shellicar/reference-foundation/llms.txt Implements resolvers for Entity1 and Entity2, utilizing the DataLoader pattern to fetch related data efficiently. It handles mapping logic and ensures that related entities are resolved via batch loading. ```typescript export const testEntityResolvers = { Query: { entity1: (_, { id }, { loaders }) => { return loaders.entity1Loader.load(id).then(mapEntity1); }, entity2: (_, { id }, { loaders }) => { return loaders.entity2Loader.load(id).then(mapEntity2); }, }, Entity1: { entities2: async (parent, _, { loaders }) => { const entity1Document = await loaders.entity1Loader.load(parent.id); if (!entity1Document?.entity2Ids) { return { edges: [], nodes: [], totalCount: 0 } satisfies Entity2Connection; } const relatedEntities = await loaders.entity2Loader.loadMany(entity1Document.entity2Ids); return { edges: relatedEntities.map((entity, index) => ({ cursor: Buffer.from(`cursor-${index}`).toString('base64'), node: mapEntity2(entity), }) satisfies Entity2Edge), nodes: relatedEntities.filter((entity) => entity !== null).map(mapEntity2), totalCount: relatedEntities.length, } satisfies Entity2Connection; }, }, } satisfies Resolvers; ``` -------------------------------- ### Provision Azure Function App Infrastructure with Bicep Source: https://context7.com/shellicar/reference-foundation/llms.txt This Bicep template defines the infrastructure for an Azure Function App, including a Storage Account and a Server Farm (App Service Plan). It utilizes Azure Verified Modules for resource deployment and accepts parameters for workspace ID, sandbox ID, location, and a secure secret. The template outputs the resource IDs for the provisioned components. ```bicep // infrastructure/main.bicep - Azure Function App infrastructure param workspaceId string @maxLength(36) @minLength(36) param sandboxId string param location string @secure() param mySecret string @maxLength(32) @minLength(32) param resourceSuffix string = replace(sandboxId, '-', '') @maxLength(32) param funcName string = substring('func${resourceSuffix}', 0, 32) @maxLength(24) param storageName string = substring('st${resourceSuffix}', 0, 24) module storage 'br/public:avm/res/storage/storage-account:0.14.1' = { name: '${deployment().name}-storage-api' params: { name: storageName requireInfrastructureEncryption: false allowBlobPublicAccess: false location: location skuName: 'Standard_LRS' } } module serverfarm 'br/public:avm/res/web/serverfarm:0.2.3' = { name: '${deployment().name}-plan' params: { name: planName kind: 'FunctionApp' location: location skuName: 'FC1' reserved: true } } resource func 'Microsoft.Web/sites@2023-12-01' = { name: funcName location: location identity: { type: 'SystemAssigned' } kind: 'functionapp,linux' properties: { serverFarmId: serverfarm.outputs.resourceId functionAppConfig: { runtime: { name: 'node', version: '20' } scaleAndConcurrency: { maximumInstanceCount: 40, instanceMemoryMB: 2048 } } } } // Deploy: cd infrastructure && ./deploy.sh ``` -------------------------------- ### Define Instant GraphQL Scalar (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Implements a custom GraphQL scalar type for handling `Instant` objects using the `js-joda` library. It defines functions for parsing input values, parsing literals from AST, and serializing output values to strings, ensuring type safety for date-time data. ```typescript // apps/function-app/src/core/graphql/scalars/Instant.ts - Instant scalar for js-joda import { DateTimeFormatter, Instant } from '@js-joda/core'; import type { ValueNode } from 'graphql'; import { GraphQLScalarType, Kind } from 'graphql'; export const localDateFormatter = DateTimeFormatter.ISO_INSTANT; const parseValue = (inputValue: unknown): Instant => { if (typeof inputValue === 'string') { return Instant.parse(inputValue); } throw new Error('Instant must be of type string'); }; const parseLiteral = (valueNode: ValueNode): Instant => { if (valueNode.kind === Kind.STRING) { return Instant.parse(valueNode.value); } throw new Error('Instant must be of type string'); }; const serialize = (outputValue: unknown): string => { if (outputValue instanceof Instant) { return localDateFormatter.format(outputValue); } throw new Error('Instant must be of type Instant'); }; export const InstantGraphQLType = new GraphQLScalarType({ name: 'Instant', description: 'A date-time string at UTC, compliant with RFC 3339', parseLiteral, parseValue, serialize, }); ``` -------------------------------- ### Define and Implement Cucumber Acceptance Tests Source: https://context7.com/shellicar/reference-foundation/llms.txt Uses Gherkin feature files to describe business scenarios and TypeScript step definitions to execute domain logic against the aggregate. These tests validate that business rules are correctly enforced during state changes. ```gherkin Feature: Employee management rules Scenario: The CEO must be located in "America" Given an employee is located in "Australia" When updating their position to "CEO" Then an error should be raised with code "CEO_LOCATION_INVALID" Scenario: The CEO salary must be between 200,000 and 500,000 Given an employee is located in "America" And their salary is 150000 When updating their position to "CEO" Then an error should be raised with code "CEO_SALARY_INVALID" ``` ```typescript import { Given, setWorldConstructor, Then, When } from '@cucumber/cucumber'; import { expect } from 'chai'; import { EmployeeWorld } from './EmployeeWorld.js'; setWorldConstructor(EmployeeWorld); Given('an employee is located in {string}', function (this: EmployeeWorld, location: string) { this.startBuildingEmployee('1'); this.builder?.withLocation(location); }); When('updating their position to {string}', function (this: EmployeeWorld, position: string) { const employee = this.getEmployee('1'); try { employee.changePosition(position); } catch (error) { this.setError(error); } }); Then('an error should be raised with code {string}', function (this: EmployeeWorld, errorCode: string) { expect(this.error).to.not.be.null; expect(this.error).to.have.property('code', errorCode); }); ``` -------------------------------- ### Async Handler Factory for Azure Functions (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Implements a factory function to create an asynchronous handler for Azure Functions. It supports deferred initialization, lazy loading of dependencies, and includes error handling and logging via a Deferred promise wrapper. Dependencies include '@shellicar-core-foundation/common/Deferred' and 'winston'. ```typescript // packages/server-common/src/function-handler.ts - Async handler factory import { Deferred } from '@shellicar-core-foundation/common/Deferred'; import type { Logger } from 'winston'; type LoggerType = Pick; type BaseHandler = (...args: any[]) => any; export const createAsyncHandler = ( name: string, importHandler: () => Promise<{ handler: THandler }> ): THandler => { const handlerDeferred = new Deferred(); const initialize = async () => { const logger = await createLogger(); try { logger.debug(`Initializing ${name} handler`); const { handler } = await importHandler(); logger.info(`${name} handler initialized`); handlerDeferred.resolve(handler); } catch (err) { logger.error(`Failed to initialize ${name} handler`, err); handlerDeferred.resolve((() => ({ status: 503, body: JSON.stringify({ errors: [{ message: 'Service temporarily unavailable' }] }), headers: { 'Content-Type': 'application/json' }, })) as THandler); } }; initialize(); return ((...args) => handlerDeferred.promise.then((handler) => handler(...args))) as THandler; }; // packages/common/src/Deferred.ts - Promise wrapper utility export class Deferred { promise: Promise; resolve: (value: T) => void = () => {}; reject: (reason?: any) => void = () => {}; constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } } ``` -------------------------------- ### GraphQL Server with Apollo and Azure Functions Source: https://context7.com/shellicar/reference-foundation/llms.txt Integrates Apollo Server with Azure Functions v4 for a type-safe GraphQL API. The schema is generated from `.graphql` files using `@shellicar/build-graphql`, including automatic TypeScript type generation. ```typescript // apps/function-app/src/core/graphql/schema.ts - Building executable schema import { makeExecutableSchema } from '@graphql-tools/schema'; import { printSchemaWithDirectives } from '@graphql-tools/utils'; import typeDefs from '@shellicar/build-graphql/typedefs'; import { lexicographicSortSchema } from 'graphql'; import { resolvers } from './resolvers'; export const schema = makeExecutableSchema({ typeDefs, resolvers, }); if (process.env.GRAPHQL__PRINT_SCHEMA) { console.log(printSchemaWithDirectives(lexicographicSortSchema(schema))); } ``` ```typescript // apps/function-app/src/core/graphql/server.ts - Apollo Server configuration import { ApolloServer } from '@apollo/server'; import { schema } from './schema'; export const apolloServer = new ApolloServer({ schema, includeStacktraceInErrorResponses: true, introspection: true, csrfPrevention: true, }); ``` ```typescript // apps/function-app/src/core/graphql/handler.ts - Azure Functions integration import { v4 } from '@as-integrations/azure-functions'; import { createContext } from './context'; import { apolloServer } from './server'; export const graphqlHandler = v4.startServerAndCreateHandler(apolloServer, { context: createContext, }); ``` -------------------------------- ### Configure InMemoryCache with Type Policies (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Initializes an `InMemoryCache` for Apollo Client, incorporating custom `scalarTypePolicies`. These policies define how specific fields, such as `created` (for `Instant`) and `emailAddress` (for `EmailAddress`), are handled during data deserialization and caching. ```typescript // apps/svelte-webapp/src/lib/client/cache.ts - Cache configuration import { InMemoryCache } from '@apollo/client/cache/inmemory/inMemoryCache'; import { scalarTypePolicies } from '$lib/graphql/scalarTypePolicies'; export const cache = new InMemoryCache({ typePolicies: scalarTypePolicies, }); ``` -------------------------------- ### GraphQL Schema Definition with Custom Scalars Source: https://context7.com/shellicar/reference-foundation/llms.txt Defines GraphQL schemas in `.graphql` files, incorporating custom scalars for common data types like EmailAddress, UUID, and Instant. The schema supports relay-style connections for pagination and relationships. ```graphql # apps/function-app/src/core/graphql/base.graphql - Base schema with custom scalars type Query scalar EmailAddress scalar UUID scalar Instant ``` ```graphql # apps/function-app/src/features/version/version.graphql - Version query extend type Query { version: Version! validate(input: ValidateInput!): Validate! } type Version { buildDate: String branch: String sha: String shortSha: String commitDate: String version: String } type Validate { field1: UUID! emailAddress: EmailAddress } input ValidateInput { emailAddress: EmailAddress uuid: UUID } ``` -------------------------------- ### Winston Logger with Application Insights Transport (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Creates a Winston logger instance that integrates with Azure Application Insights for sending logs. It utilizes '@opentelemetry/winston-transport' and '@shellicar/winston-azure-application-insights' for seamless integration. The logger is configured with JSON format for errors and includes console output for development. Dependencies include 'winston', '@opentelemetry/winston-transport', and '@shellicar/winston-azure-application-insights'. ```typescript // packages/monitor/src/logger.ts - Winston logger with Application Insights import { OpenTelemetryTransportV3 } from '@opentelemetry/winston-transport'; import { createApplicationInsightsTransport, ApplicationInsightsVersion } from '@shellicar/winston-azure-application-insights'; import winston, { format } from 'winston'; const createWinstonLogger = (client: TelemetryClient) => { const transport = createApplicationInsightsTransport({ client, version: ApplicationInsightsVersion.V3, }); return winston.createLogger({ format: format.combine(format.errors({ stack: true }), format.splat(), format.json()), level: 'debug', transports: [ new winston.transports.Console({ format: format.combine(format.colorize(), format.simple()), }), new OpenTelemetryTransportV3(), transport, ], }); }; ``` -------------------------------- ### Define Scalar Type Policies for Apollo Cache (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Defines type policies for custom scalars used within Apollo Client's `InMemoryCache`. It specifies how to read and write `Instant` and `EmailAddress` fields for different entities, ensuring correct deserialization and caching of these custom types. ```typescript // apps/svelte-webapp/src/lib/graphql/scalarTypePolicies.ts - Type policies import { emailAddressTypePolicy } from './policies/EmailAddress'; import { instantTypePolicy } from './policies/Instant'; export const scalarTypePolicies = { Entity1: { fields: { created: instantTypePolicy } }, Entity2: { fields: { created: instantTypePolicy } }, Validate: { fields: { emailAddress: emailAddressTypePolicy } }, }; ``` -------------------------------- ### Register Custom GraphQL Scalars (TypeScript) Source: https://context7.com/shellicar/reference-foundation/llms.txt Registers custom GraphQL scalar types, including `EmailAddress`, `UUID`, and the custom `Instant` scalar, within the application's resolvers. This makes these custom types available for use in GraphQL schemas and operations. ```typescript // apps/function-app/src/core/graphql/resolvers.ts - Registering scalars import { GraphQLEmailAddress } from 'graphql-scalars'; import { InstantGraphQLType } from './scalars/Instant'; import { GraphQLUUID } from './scalars/UUID'; export const resolvers: Resolvers[] = [ testEntityResolvers, versionResolvers, { EmailAddress: GraphQLEmailAddress, UUID: GraphQLUUID, Instant: InstantGraphQLType, }, ]; ``` -------------------------------- ### Implement Domain Aggregate and Custom Errors Source: https://context7.com/shellicar/reference-foundation/llms.txt Defines an EmployeeAggregate class to encapsulate business logic and state, alongside a custom DomainError class for specific business rule violations. This ensures domain integrity by throwing errors when invalid state transitions occur. ```typescript import { DomainError } from './DomainError.js'; export type EmployeeState = { id: string; location: string; salary: number; position: string | null; }; export class EmployeeAggregate { constructor(private state: EmployeeState) {} public get position() { return this.state.position; } changePosition(position: string) { if (position === 'CEO' && this.state.location !== 'America') { throw new DomainError('The CEO must be located in America', 'CEO_LOCATION_INVALID'); } if (position === 'CEO' && (this.state.salary < 200000 || this.state.salary > 500000)) { throw new DomainError('The CEO salary must be between 200,000 and 500,000', 'CEO_SALARY_INVALID'); } this.state.position = position; } } export type DomainErrorCodes = 'CEO_LOCATION_INVALID' | 'CEO_SALARY_INVALID'; export class DomainError extends Error { code: DomainErrorCodes; constructor(message: string, code: DomainErrorCodes) { super(message); this.code = code; } } ``` -------------------------------- ### Define GraphQL Entity Relations Schema Source: https://context7.com/shellicar/reference-foundation/llms.txt Defines the GraphQL schema for Entity1 and Entity2, including connection types for pagination and bidirectional relations. This schema serves as the contract for the underlying data structure. ```graphql extend type Query { entity1(id: ID!): Entity1 entity2(id: ID!): Entity2 } type Entity2Connection { edges: [Entity2Edge!]! nodes: [Entity2!]! totalCount: Int! } type Entity2Edge { cursor: String! node: Entity2! } type Entity2 { id: ID! created: Instant! description: String entity1: Entity1Edge! } type Entity1Edge { cursor: String! node: Entity1! } type Entity1 { id: ID! created: Instant! name: String! entities2: Entity2Connection! } ``` -------------------------------- ### Update PNPM Version with Corepack Source: https://github.com/shellicar/reference-foundation/blob/main/README.md Updates the PNPM version to the latest available. This command modifies the `packageManager` field in `package.json` to reflect the newest version. ```shell corepack up ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.