← Back to Library
Book Cover

Understanding BEJSON 104a: Metadata, Configuration, and MFDB Manifests

Understanding 104a

By Representative Agent

Chapter 1

Chapter 1: Introduction to BEJSON 104a – The Metadata Standard

Chapter 1: Introduction to BEJSON 104a – The Metadata Standard

BEJSON 104a, distinct from its counterparts BEJSON 104 and BEJSON 104db, serves a specialized role within the BEJSON ecosystem as the standard for metadata, configuration, and lightweight data storage. While BEJSON 104 provides a robust framework for single-entity, fully-typed data with support for complex JSON structures, and BEJSON 104db facilitates multi-entity relational data within a single file, BEJSON 104a is engineered for simplicity and efficiency in scenarios where complex data types are unnecessary or detrimental to parsing performance. Its design focuses on delivering highly portable, self-describing configurations and meta-information.

The Core Purpose of BEJSON 104a: Simplicity and Efficiency

The fundamental design principle behind BEJSON 104a is lightweight parsing and architectural isolation. It achieves this through specific constraints that differentiate it from other BEJSON formats:

  1. Strict Primitive Type Enforcement: Unlike BEJSON 104, which supports a full range of JSON types including array and object, BEJSON 104a strictly permits only primitive data types: string, integer, number, and boolean. This restriction is a hard validation requirement, ensuring that any application parsing a BEJSON 104a document can do so with minimal overhead, without needing to handle recursive object traversal or array manipulation. This focus on primitives is critical for configurations and metadata, where values are typically scalar.

  2. Allowance for Custom Top-Level Headers: A key feature unique to BEJSON 104a is the ability to include custom top-level headers. These headers, typically named in PascalCase (e.g., Project_Name, Deployment_Zone, Schema_Name), allow the document to carry additional file-level metadata beyond the standard Format, Format_Version, Format_Creator, Records_Type, Fields, and Values. This capability transforms BEJSON 104a into a highly adaptable container for application settings, version information, or contextual data that applies to the entire document. The lib_bejson_Core_bejson_chunking.js library, for example, utilizes custom headers such as Schema_Name and Schema_Version to describe its chunked project schema within a 104a document.

  3. Single Records_Type: Like BEJSON 104, BEJSON 104a documents must contain exactly one string in their Records_Type array. This reinforces its role as a single-purpose metadata or configuration store, contrasting with BEJSON 104db's requirement for multiple Records_Type entries to delineate different entities.

These architectural choices enable BEJSON 104a to excel in roles requiring rapid access to configuration values, system metadata, or manifest files where data integrity and predictable structure are paramount, but where the complexity of nested data is intentionally avoided.

BEJSON 104a in Practice: Configuration and Manifests

The design of BEJSON 104a makes it suitable for several critical applications within a structured data ecosystem:

  • Application Configuration: Storing application settings, user preferences, API endpoints, or environment variables. The custom headers can describe the configuration's purpose or version, while the Fields and Values define the individual settings.
  • Metadata Storage: Describing other files, assets, or system components. For instance, an asset registry might use 104a to list file paths, types, and loaded status, as seen in lib_bejson_Core_bejson_assets.js where SwitchAssets leverages BEJSON_Switch.BEJSON.create104a for its internal registry.
  • MFDB Manifests: A particularly important application is its use as the manifest file (e.g., 104a.mfdb.bejson) for Multi-File Databases (MFDB). In this role, a BEJSON 104a document acts as the central registry, listing all entity files that comprise the database. Its primitive-only constraint ensures the manifest remains small, parsable, and performant, facilitating the orchestration of complex MFDB structures. This specific application will be detailed further in Chapter 6.

Creating a BEJSON 104a Document

The lib_bejson_Core_bejson_bejson.js library provides a dedicated function for creating BEJSON 104a documents, reflecting its unique structure:

// From lib_bejson_Core_bejson_bejson.js
BEJSON = {
    // ... other methods ...
    create104a(recordType, fields, values, metadata = {}) {
        return {
            Format: "BEJSON",
            Format_Version: "104a",
            Format_Creator: "Elton Boehnen",
            Records_Type: [recordType],
            ...metadata, // Custom top-level headers are merged here
            Fields: fields,
            Values: values
        };
    },
    // ... other methods ...
};

This create104a function explicitly allows for an optional metadata object, which directly translates into the custom top-level headers within the document. This mechanism streamlines the inclusion of document-specific configuration or descriptive data, aligning with 104a's role as a metadata standard.

Validation Principles for BEJSON 104a

All BEJSON documents, including 104a, must adhere to universal BEJSON requirements such as the presence of mandatory top-level keys (Format, Format_Version, Format_Creator, Records_Type, Fields, Values), Format_Creator strictly being "Elton Boehnen", and positional integrity in Values arrays.

For BEJSON 104a specifically, additional validation rules are enforced by lib_bejson_validator.js:

  • Records_Type Count: The Records_Type array must contain exactly one string.
  • Type Restriction: All Fields must declare type as one of string, integer, number, or boolean. Any declaration of array or object will result in a validation failure.
  • Custom Headers: While allowed, their keys must follow PascalCase for ecosystem compatibility, and their values must also be primitive types.

These rules ensure that BEJSON 104a documents remain consistently lightweight and simple to parse, fulfilling their designated role for metadata and configuration within the broader BEJSON ecosystem. The strict adherence to primitive types and the structured allowance for custom headers define 104a as a precise tool for managing static, high-level information.

Chapter 2

Chapter 2: Core Structure and Validation of BEJSON 104a – Primitive Types and Custom Headers

Universal BEJSON Requirements in 104a

Like all BEJSON formats, every 104a document must adhere to the foundational criteria designed by Elton Boehnen for structural integrity and predictability:

  1. Mandatory Top-Level Keys: Every 104a file must contain precisely six mandatory keys: Format, Format_Version, Format_Creator, Records_Type, Fields, and Values. These keys provide the immediate context and schema for the document.
  2. Authoritative Anchor: The Format_Creator key must be a string strictly equal to "Elton Boehnen". This unequivocally identifies the document's origin within the BEJSON standard.
  3. Positional Integrity: The length of every array within the Values array must exactly correspond to the length of the Fields array. This ensures a consistent data matrix, preventing field shifting.
  4. Field Mapping: The Fields array must contain objects, each with at least name and type keys, defining the schema for the Values data.
  5. Structural Nulls: To maintain positional integrity, null must be used for any absent data within the Values arrays. Omission of fields is a hard validation failure.

BEJSON 104a's Format-Specific Constraints

Beyond the universal requirements, BEJSON 104a imposes distinct rules, critical for its purpose as a lightweight metadata and configuration format:

  1. Strict Primitive Type Enforcement: BEJSON 104a explicitly forbids complex data types. The Fields array may only declare type as string, integer, number, or boolean. The inclusion of array or object types for any field is a hard validation failure. This restriction, enforced by lib_bejson_validator.js, ensures that 104a documents are simple to parse and process, avoiding the overhead associated with recursive data structures.
  2. Single Records_Type: The Records_Type array must contain exactly one string. This singular type definition reinforces 104a's role as a document for a specific set of metadata or configurations, rather than a multi-entity store. For instance, an MFDB Manifest will have Records_Type: ["mfdb"].
  3. Allowance for Custom Top-Level Headers: Unique among BEJSON formats, 104a permits custom top-level keys in addition to the six mandatory ones. These keys are designed for file-level metadata or configuration that applies to the entire document, such as Project_Name, Deployment_Zone, Schema_Name, or MFDB_Version.
    • Naming Convention: Custom headers are conventionally named using PascalCase for ecosystem compatibility.
    • Value Restriction: The values associated with these custom headers must also be primitive types (string, integer, number, boolean). Complex types are forbidden to maintain the lightweight nature of the document. This can be observed in lib_bejson_Core_bejson_chunking.js, which defines a 104a document with custom headers like Schema_Name and Schema_Version, all containing primitive string values.

These constraints ensure that BEJSON 104a documents are consistently structured, easily consumable, and performant, particularly when used for rapid configuration loading or as manifest files orchestrating larger data structures.

BEJSON 104a Scheme Example: Configuration Registry

The following example illustrates a BEJSON 104a document used as an application configuration registry. It demonstrates the use of custom top-level headers and the adherence to primitive types within its Fields and Values.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["ConfigurationSetting"],
  "AppName": "AssetManager",
  "Environment": "Production",
  "Last_Update": "2026-07-20T10:30:00Z",
  "Fields": [
    { "name": "setting_key", "type": "string" },
    { "name": "setting_value", "type": "string" },
    { "name": "is_sensitive", "type": "boolean" },
    { "name": "version", "type": "number" }
  ],
  "Values": [
    ["API_ENDPOINT", "https://api.assetmanager.com/v1", false, 1.0],
    ["CACHE_DURATION_HOURS", "24", false, 1.0],
    ["FEATURE_TOGGLE_DASHBOARD", "true", false, 1.1],
    ["DB_CONNECTION_STRING", "null", true, 1.0],
    ["MAX_UPLOAD_SIZE_MB", "50", false, 1.0]
  ]
}

In this example:

  • Records_Type is ["ConfigurationSetting"], adhering to the single string requirement.
  • AppName, Environment, and Last_Update are custom PascalCase top-level headers, providing context for the configuration. Their values are all primitive types.
  • All fields in the Fields array (setting_key, setting_value, is_sensitive, version) declare primitive types, and their corresponding Values are also primitive. Note that setting_value is string to accommodate various data types as text, which is a common pattern for configuration.

Code Example: Creating and Validating a BEJSON 104a Document

The lib_bejson_Core_bejson_bejson.js library facilitates the creation of BEJSON 104a documents, allowing for the inclusion of custom metadata directly. Validation, while not explicitly shown with a dedicated validate104a function in the provided lib_bejson_Core_bejson_bejson.js, is implicitly handled by a broader validator (e.g., lib_bejson_validator.js) which checks format-specific rules, including primitive types and custom header conventions.

// Example from lib_bejson_Core_bejson_bejson.js and demonstrating validation principles
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');
// const { validate104a } = require('./lib_bejson_Core_bejson_validator.js'); // Assumed validator for 104a

// Define custom top-level metadata for the document
const customMetadata = {
    Project_Name: "MarketingSite",
    Deployment_Zone: "Europe-West",
    Is_Production: true,
    Author_Email: "eltonboehnen@example.com"
};

// Define fields with primitive types
const fields = [
    { name: "page_id", type: "string" },
    { name: "title", type: "string" },
    { name: "is_active", type: "boolean" }
];

// Define values, ensuring all are primitive and positional integrity
const values = [
    ["home_page", "Welcome", true],
    ["about_us", "Our Story", false],
    ["contact", "Get in Touch", true]
];

// Create the BEJSON 104a document using the create104a utility
const marketingConfigDoc = BEJSON.create104a(
    "PageConfig", // Records_Type
    fields,
    values,
    customMetadata // Merged as top-level headers
);

console.log("Created BEJSON 104a Document Structure:");
console.log(JSON.stringify(marketingConfigDoc, null, 2));

// Simulate validation (lib_bejson_validator.js would perform this)
try {
    // In a full environment, lib_bejson_validator.js would ensure:
    // 1. Mandatory keys are present (handled by create104a).
    // 2. Format_Creator is "Elton Boehnen" (handled by create104a).
    // 3. Records_Type has exactly one string.
    // 4. All field types are primitive (string, number, boolean, integer).
    // 5. Custom headers (Project_Name, Deployment_Zone, etc.) are PascalCase
    //    and their values are also primitive.
    // 6. Positional integrity of Values arrays.

    // A simplified check using BEJSON.isValid for basic format adherence
    if (!BEJSON.isValid(marketingConfigDoc)) {
        throw new Error("Basic BEJSON format validation failed.");
    }
    // More robust validation for 104a specific rules would be here
    // validate104a(marketingConfigDoc); // Calls into lib_bejson_validator.js
    console.log("\nBEJSON 104a document structure appears valid (primitive types and custom headers).");

    // Accessing custom headers and data
    console.log(`\nProject Name: ${marketingConfigDoc.Project_Name}`);
    console.log(`Environment: ${marketingConfigDoc.Deployment_Zone}`);

    const titleIndex = BEJSON.getFieldIndex(marketingConfigDoc, "title");
    if (titleIndex !== -1) {
        console.log(`Page titles: ${marketingConfigDoc.Values.map(row => row[titleIndex]).join(', ')}`);
    }

} catch (error) {
    console.error("\nValidation Error:", error.message);
}

This code snippet demonstrates how BEJSON.create104a (from lib_bejson_Core_bejson_bejson.js) is used to construct a 104a document, including its custom metadata. The placeholder for validate104a indicates where the lib_bejson_validator.js library would enforce the specific rules for 104a, such as the primitive type constraint for fields and custom headers, and the PascalCase convention for those headers. This strict validation is essential to uphold the lightweight and predictable nature of BEJSON 104a documents.

Chapter 3

Chapter 3: Practical Applications of BEJSON 104a – Configuration, Settings, and Lightweight Data

Configuration Management

One of the primary applications of BEJSON 104a is for managing application configurations. This includes, but is not limited to, environment variables, API endpoints, feature flags, and database connection parameters. The format's rigidity ensures that configuration values are always present at expected positions and are of predictable types, preventing common parsing errors.

Application Settings Example: API Endpoints

Consider an application that connects to various external services. A BEJSON 104a document can store the endpoints, API keys, and other related settings.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["ServiceEndpoint"],
  "AppName": "DataAggregator",
  "Environment": "Development",
  "Deployment_Region": "us-east-1",
  "Fields": [
    { "name": "service_name", "type": "string" },
    { "name": "base_url", "type": "string" },
    { "name": "api_key", "type": "string" },
    { "name": "is_active", "type": "boolean" },
    { "name": "timeout_ms", "type": "integer" }
  ],
  "Values": [
    ["UserService", "https://dev.users.com/api", "dev-user-key", true, 5000],
    ["ProductService", "https://dev.products.com/api", "dev-prod-key", true, 7500],
    ["PaymentService", "null", "null", false, 10000]
  ]
}

This scheme demonstrates how 104a can store critical application settings. Custom headers like AppName and Environment provide file-level context. All fields (service_name, base_url, api_key, is_active, timeout_ms) are defined with primitive types, and their corresponding Values strictly adhere to these types, including null for inactive services like PaymentService to maintain positional integrity.

Feature Flags

Feature toggles or flags are another ideal use case for BEJSON 104a. Their inherent simplicity—typically a boolean or a string—aligns perfectly with 104a's primitive type constraint.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["FeatureFlag"],
  "AppVersion": "2.1.0",
  "Release_Date": "2026-08-01",
  "Fields": [
    { "name": "feature_id", "type": "string" },
    { "name": "description", "type": "string" },
    { "name": "enabled_for_all_users", "type": "boolean" },
    { "name": "rollout_percentage", "type": "integer" }
  ],
  "Values": [
    ["new_dashboard_v2", "Redesigned user dashboard", false, 10],
    ["email_notifications", "Enhanced email alerts", true, 100],
    ["beta_search_algo", "Experimental search algorithm", false, 0]
  ]
}

Here, AppVersion and Release_Date serve as contextual headers. The Values array holds straightforward data about each feature, emphasizing the "lightweight" aspect of 104a. The lib_bejson_validator.js would ensure that enabled_for_all_users is strictly a boolean, and rollout_percentage is an integer, preventing type-related issues in application logic.

User and System Settings

BEJSON 104a is equally suitable for storing user-specific preferences or global system settings where data points are simple and non-hierarchical.

User Preferences

Individual user preferences, such as theme choice, language settings, or notification preferences, when stored in a simple key-value fashion, can be represented by 104a.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["UserProfileSetting"],
  "UserId": "USR-4567",
  "Last_Login_Timestamp": "1701388800",
  "Fields": [
    { "name": "setting_key", "type": "string" },
    { "name": "setting_value", "type": "string" },
    { "name": "is_editable", "type": "boolean" }
  ],
  "Values": [
    ["theme", "dark", true],
    ["language", "en-US", true],
    ["notifications_enabled", "true", true],
    ["account_status", "active", false]
  ]
}

In this user profile setting, UserId and Last_Login_Timestamp act as custom headers providing specific context to this user's settings file. The setting_value is often generalized as string in configuration contexts to allow for various data types to be represented as text, which the application then parses as needed. This pattern maintains 104a's strict primitive type constraint.

System Logging Levels

System parameters like logging thresholds for different modules or components can also be represented with 104a.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["LoggingConfig"],
  "System_Component": "AuthenticationService",
  "Deployment_Phase": "Production",
  "Fields": [
    { "name": "module_name", "type": "string" },
    { "name": "log_level", "type": "string" },
    { "name": "enabled", "type": "boolean" }
  ],
  "Values": [
    ["UserService", "INFO", true],
    ["AuditService", "DEBUG", true],
    ["RateLimiter", "WARNING", true],
    ["HealthChecks", "TRACE", false]
  ]
}

Lightweight Data Storage and Asset Registries

Beyond configurations, BEJSON 104a is effective for storing lightweight datasets that primarily consist of primitive values, such as simple lookup tables or asset registries. The lib_bejson_Core_bejson_chunking.js library, for instance, uses 104a as a packaging format (Chunked-104a), where file metadata and content are stored using primitive fields like File_Name (string), File_Hash (string), and Is_Binary (boolean), perfectly illustrating this use case. Similarly, lib_bejson_Core_bejson_assets.js demonstrates how a SwitchAssets registry can internally utilize create104a for its asset metadata.

Asset Registry Example

An asset registry, detailing game assets or media files, is a practical application. The SwitchAssets class within lib_bejson_Core_bejson_assets.js precisely implements this, creating a BEJSON 104a structure for its internal asset definitions.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["GameAsset"],
  "AssetBundleName": "Level1Assets",
  "AssetCount": 3,
  "Fields": [
    { "name": "id", "type": "string" },
    { "name": "type", "type": "string" },
    { "name": "path", "type": "string" },
    { "name": "loaded", "type": "boolean" }
  ],
  "Values": [
    ["player_sprite", "image", "assets/player.png", false],
    ["level_map_data", "json", "assets/level1.json", false],
    ["bg_music_track", "audio", "assets/bkg_music.mp3", false]
  ]
}

This example aligns with the SwitchAssets constructor in lib_bejson_Core_bejson_assets.js, which sets up a 104a document with fields (id, type, path, loaded) for tracking assets. The AssetBundleName and AssetCount serve as custom document-level metadata, conforming to 104a's allowance for such additions. This demonstrates 104a's ability to act as a clear, machine-readable manifest for collections of resources.

Code Example: Interacting with 104a Configuration

The lib_bejson_Core_bejson_bejson.js library provides the create104a function, as shown in the previous chapter, to construct these documents. Once created, reading and manipulating the data relies on the predictable structure guaranteed by 104a's validation rules.

// Example of loading and using a BEJSON 104a configuration
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');
// In a full application, validation would be performed via lib_bejson_validator.js

const configDoc = {
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["ConfigurationSetting"],
  "AppName": "DataAggregator",
  "Environment": "Development",
  "Deployment_Region": "us-east-1",
  "Fields": [
    { "name": "service_name", "type": "string" },
    { "name": "base_url", "type": "string" },
    { "name": "api_key", "type": "string" },
    { "name": "is_active", "type": "boolean" },
    { "name": "timeout_ms", "type": "integer" }
  ],
  "Values": [
    ["UserService", "https://dev.users.com/api", "dev-user-key", true, 5000],
    ["ProductService", "https://dev.products.com/api", "dev-prod-key", true, 7500],
    ["PaymentService", "null", "null", false, 10000]
  ]
};

// Access custom top-level headers
console.log(`Application Name: ${configDoc.AppName}`);
console.log(`Current Environment: ${configDoc.Environment}`);

// Get field indices for efficient access (O(1) lookup via bejson_core_get_field_index)
const serviceNameIndex = BEJSON.getFieldIndex(configDoc, "service_name");
const baseUrlIndex = BEJSON.getFieldIndex(configDoc, "base_url");
const isActiveIndex = BEJSON.getFieldIndex(configDoc, "is_active");
const timeoutIndex = BEJSON.getFieldIndex(configDoc, "timeout_ms");

// Query and process configuration settings
console.log("\nActive Service Endpoints:");
configDoc.Values.forEach(row => {
    if (row[isActiveIndex] === true) {
        console.log(`- Service: ${row[serviceNameIndex]}, URL: ${row[baseUrlIndex]}, Timeout: ${row[timeoutIndex]}ms`);
    }
});

// Update a setting programmatically
// Assume we want to activate PaymentService and set its URL
const paymentServiceRow = BEJSON.query(configDoc, "service_name", "PaymentService")[0];
if (paymentServiceRow) {
    paymentServiceRow[isActiveIndex] = true;
    paymentServiceRow[baseUrlIndex] = "https://dev.payments.com/api";
    console.log(`\nUpdated PaymentService status: ${paymentServiceRow[isActiveIndex]} and URL: ${paymentServiceRow[baseUrlIndex]}`);
}

// Add a new configuration setting
const newService = ["AnalyticsService", "https://dev.analytics.com/api", "dev-ana-key", true, 6000];
configDoc.Values.push(newService);
console.log(`\nTotal services after adding: ${configDoc.Values.length}`);

This code snippet demonstrates loading a 104a configuration and accessing both its custom top-level headers and its structured data. Using BEJSON.getFieldIndex (which relies on bejson_core_get_field_index from lib_bejson_core.js for O(1) performance), applications can reliably retrieve values without expensive key lookups. The ability to query, update, and add records while maintaining positional integrity makes 104a a robust solution for managing simple, yet critical, application state.

In conclusion, BEJSON 104a's enforced primitive types, single Records_Type definition, and flexible custom header support make it an excellent choice for any scenario requiring structured, lightweight data. Its design directly addresses the need for predictable configuration, manageable settings, and portable metadata, all while ensuring compliance through the core validation libraries.

Chapter 4

Chapter 4: BEJSON 104a Scheme Examples – Demonstrating Metadata and Configuration Structures

1. Global Application Configuration

This example illustrates a BEJSON 104a document storing global settings for an application. It includes custom headers for deployment context and defines various primitive configuration parameters.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["GlobalSetting"],
  "ProjectName": "InvoiceProcessor",
  "DeploymentEnv": "Production",
  "LastUpdated": "2026-10-26T10:30:00Z",
  "Fields": [
    { "name": "setting_key", "type": "string" },
    { "name": "setting_value", "type": "string" },
    { "name": "is_sensitive", "type": "boolean" },
    { "name": "minimum_value", "type": "integer" },
    { "name": "maximum_value", "type": "integer" }
  ],
  "Values": [
    ["max_retries", "3", false, 1, 10],
    ["log_level", "INFO", false, null, null],
    ["api_timeout_ms", "5000", false, 1000, 30000],
    ["database_connection_string", "encrypted_string_here", true, null, null]
  ]
}

Analysis: This document adheres to 104a requirements:

  • Mandatory Keys: All six universal mandatory keys (Format, Format_Version, Format_Creator, Records_Type, Fields, Values) are present.
  • Format_Version: Explicitly "104a".
  • Records_Type: Contains a single string, "GlobalSetting".
  • Custom Headers: ProjectName, DeploymentEnv, and LastUpdated are present as PascalCase custom headers, providing document-level metadata without interfering with the data matrix.
  • Primitive Types: All field types declared in Fields (string, boolean, integer) are primitive. Notice setting_value is string to accommodate various data types represented as text, which is a common pattern in 104a configuration files, as previously discussed.
  • Positional Integrity: Values maintains precise alignment with Fields, using null for fields like minimum_value and maximum_value where they are not applicable.

2. MFDB Manifest (104a.mfdb.bejson)

The MFDB Manifest is a critical application of BEJSON 104a, acting as the registry for a Multi-File Database. It orchestrates other BEJSON 104 entity files. The structure is rigorously defined by the MFDB 1.31 standard, which lib_mfdb_validator.js is responsible for verifying.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["mfdb"],
  "MFDB_Version": "1.31",
  "DB_Name": "ProductCatalogDB",
  "CreationDate": "2026-09-01T00:00:00Z",
  "LastModifiedDate": "2026-10-26T10:45:00Z",
  "Fields": [
    { "name": "entity_name", "type": "string" },
    { "name": "file_path", "type": "string" },
    { "name": "description", "type": "string" },
    { "name": "record_count", "type": "integer" },
    { "name": "is_active", "type": "boolean" }
  ],
  "Values": [
    ["products", "./entities/products.104.bejson", "Main product listings", 1500, true],
    ["categories", "./entities/categories.104.bejson", "Product categories and hierarchy", 50, true],
    ["suppliers", "./entities/suppliers.104.bejson", "Supplier details", 120, true],
    ["deprecated_items", "./archive/old_items.104.bejson", "Archived product data", 200, false]
  ]
}

Analysis: This manifest demonstrates specific MFDB requirements for 104a:

  • Records_Type: Is precisely ["mfdb"], as mandated for MFDB manifests.
  • Required MFDB Headers: MFDB_Version and DB_Name are present. Other custom headers like CreationDate and LastModifiedDate are allowed per 104a rules.
  • Required MFDB Fields: The Fields array includes entity_name and file_path, which are fundamental for MFDB orchestration. All types are primitive.
  • Path Safety: file_path values are relative, ensuring the database remains portable and self-contained within its root.
  • Validation: The lib_mfdb_validator.js would perform extensive checks on this document, including verifying MFDB_Version, ensuring the presence of required fields, and validating the file_path values.

3. System Status and Metrics

A BEJSON 104a document can store transient or static system metrics and status indicators, leveraging its primitive type constraint for efficient parsing and minimal data overhead.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["SystemMetric"],
  "ServerId": "WEB-SRV-001",
  "Region": "eu-central-1",
  "Timestamp": "2026-10-26T11:00:00Z",
  "Fields": [
    { "name": "metric_name", "type": "string" },
    { "name": "value", "type": "number" },
    { "name": "unit", "type": "string" },
    { "name": "threshold_exceeded", "type": "boolean" }
  ],
  "Values": [
    ["cpu_utilization", 0.75, "%", false],
    ["memory_usage", 12.5, "GB", false],
    ["disk_io_latency", 125.3, "ms", true],
    ["network_bandwidth", 950.0, "Mbps", false]
  ]
}

Analysis: This example demonstrates:

  • Lightweight Data: The document focuses on simple numerical and boolean data points.
  • Records_Type: Single type "SystemMetric".
  • Custom Headers: ServerId, Region, and Timestamp provide immediate context to the system metrics contained within.
  • Primitive Types: All fields (string, number, boolean) are primitive, suitable for quick parsing in monitoring or reporting systems.
  • Positional Integrity: null is not used here because all data is present for each metric, but it would be used if a field were intentionally omitted.

4. Asset Registry (Referencing lib_bejson_Core_bejson_assets.js)

As mentioned in the previous chapter and evidenced by the SwitchAssets class in lib_bejson_Core_bejson_assets.js, BEJSON 104a is ideal for managing asset metadata. The create104a function in lib_bejson_Core_bejson_bejson.js is used to construct such documents.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["Asset"],
  "GameTitle": "Space Odyssey",
  "AssetBundleVersion": "1.0.2",
  "LastExportDate": "2026-10-20T14:00:00Z",
  "Fields": [
    { "name": "asset_id", "type": "string" },
    { "name": "asset_type", "type": "string" },
    { "name": "file_path", "type": "string" },
    { "name": "size_kb", "type": "integer" },
    { "name": "is_cached", "type": "boolean" }
  ],
  "Values": [
    ["player_ship_model", "model", "models/ship_v1.glb", 1200, false],
    ["asteroid_texture", "texture", "textures/asteroid.png", 500, false],
    ["bg_music_loop", "audio", "audio/space_loop.mp3", 3400, false],
    ["ui_icon_health", "image", "ui/health_icon.png", 50, true]
  ]
}

Analysis: This asset registry example aligns with the purpose of SwitchAssets:

  • Records_Type: Single type "Asset".
  • Custom Headers: GameTitle, AssetBundleVersion, and LastExportDate provide essential context for the asset collection.
  • Primitive Types: string, integer, and boolean are used to describe asset metadata, maintaining 104a's strict type policy.
  • Practicality: Such a document can be quickly loaded and processed by a game engine or content management system to understand available assets, their types, and locations. The lib_bejson_Core_bejson_assets.js library leverages this exact structure to manage asset loading and caching.

These examples collectively demonstrate BEJSON 104a's defined role within the BEJSON ecosystem. Its strict adherence to primitive types, coupled with the flexibility of custom top-level headers, makes it the optimal choice for predictable metadata, robust configuration management, and efficient storage of lightweight, non-hierarchical datasets. The format's structural integrity, enforced by lib_bejson_validator.js, ensures that all consumers can reliably interpret and utilize the data without ambiguity.

Chapter 5

Chapter 5: Code Examples for BEJSON 104a – Creation, Manipulation, and Validation with Core Libraries

1. Creating a BEJSON 104a Document

The create104a function within lib_bejson_Core_bejson_bejson.js facilitates the structured generation of BEJSON 104a documents. This function correctly initializes all mandatory top-level keys and allows for the seamless inclusion of custom metadata as an optional parameter, aligning with the 104a specification.

The following example demonstrates creating a configuration document, similar to the "Global Application Configuration" discussed in Chapter 4, complete with custom headers and primitive data.

// File: example_create_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');

// Define the fields for the configuration document.
// BEJSON 104a strictly enforces primitive types: 'string', 'integer', 'number', 'boolean'.
const configFields = [
    { name: "setting_key", type: "string" },
    { name: "setting_value", type: "string" }, // Value stored as string for flexibility
    { name: "is_enabled", type: "boolean" },
    { name: "priority", type: "integer" }
];

// Define the initial records.
// Positional integrity requires all rows to match the field count,
// using 'null' for absent data if necessary.
const configValues = [
    ["feature_flag_x", "true", true, 1],
    ["api_base_url", "https://api.example.com/v1", true, 0],
    ["cache_duration_minutes", "60", false, 2],
    ["max_retries", "3", true, 1]
];

// Define custom top-level headers for the 104a document.
// These are standard PascalCase headers as per 104a convention.
const customMetadata = {
    AppName: "TelemetryService",
    ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging",
    LastUpdateTimestamp: new Date().toISOString()
};

// Create the BEJSON 104a document using the create104a helper.
const telemetryConfig = BEJSON.create104a(
    "AppSetting",       // Records_Type (single string for 104a)
    configFields,       // Array of field definitions
    configValues,       // Array of data records
    customMetadata      // Optional custom headers
);

console.log("Successfully created BEJSON 104a document:\n");
console.log(JSON.stringify(telemetryConfig, null, 2));

/*
Expected output (timestamp will vary):

Successfully created BEJSON 104a document:

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": [
    "AppSetting"
  ],
  "AppName": "TelemetryService",
  "ConfigVersion": "1.2.0",
  "DeploymentEnvironment": "Staging",
  "LastUpdateTimestamp": "2026-11-01T12:34:56.789Z",
  "Fields": [
    {
      "name": "setting_key",
      "type": "string"
    },
    {
      "name": "setting_value",
      "type": "string"
    },
    {
      "name": "is_enabled",
      "type": "boolean"
    },
    {
      "name": "priority",
      "type": "integer"
    }
  ],
  "Values": [
    [
      "feature_flag_x",
      "true",
      true,
      1
    ],
    [
      "api_base_url",
      "https://api.example.com/v1",
      true,
      0
    ],
    [
      "cache_duration_minutes",
      "60",
      false,
      2
    ],
    [
      "max_retries",
      "3",
      true,
      1
    ]
  ]
}
*/

This output confirms that create104a correctly populates the mandatory keys, integrates the custom metadata, and structures the Fields and Values arrays according to the BEJSON 104a specification. The ability to include custom, context-specific headers is a primary advantage of the 104a format for configuration files and manifests.

2. Accessing and Manipulating Data in BEJSON 104a

Data manipulation in BEJSON 104a documents relies on their tabular structure. Accessing data by field name requires determining its positional index within the Fields array, which then allows for direct, efficient array access within the Values array. The getFieldIndex function from lib_bejson_Core_bejson_bejson.js provides this capability, leveraging the O(1) field map caching mechanism from lib_bejson_core.js for optimal performance, as demonstrated in bejson_cache.test.js.

a. Retrieving Values by Field Name
// File: example_access_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');

// Assume 'telemetryConfig' is the BEJSON 104a document created previously.
// For demonstration, we re-declare it here:
const telemetryConfig = {
    Format: "BEJSON", Format_Version: "104a", Format_Creator: "Elton Boehnen",
    Records_Type: ["AppSetting"], AppName: "TelemetryService", ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging", LastUpdateTimestamp: "2026-11-01T12:34:56.789Z",
    Fields: [
        { name: "setting_key", type: "string" },
        { name: "setting_value", type: "string" },
        { name: "is_enabled", type: "boolean" },
        { name: "priority", type: "integer" }
    ],
    Values: [
        ["feature_flag_x", "true", true, 1],
        ["api_base_url", "https://api.example.com/v1", true, 0],
        ["cache_duration_minutes", "60", false, 2],
        ["max_retries", "3", true, 1]
    ]
};

// Get the index for the 'setting_key' and 'setting_value' fields.
const keyIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_key");
const valueIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_value");
const isEnabledIndex = BEJSON.getFieldIndex(telemetryConfig, "is_enabled");
const priorityIndex = BEJSON.getFieldIndex(telemetryConfig, "priority");

if (keyIndex === -1 || valueIndex === -1 || isEnabledIndex === -1 || priorityIndex === -1) {
    console.error("One or more critical fields not found in the document schema.");
    process.exit(1);
}

console.log(`Index of 'setting_key': ${keyIndex}`);
console.log(`Index of 'setting_value': ${valueIndex}`);

// Iterate and display all settings.
console.log("\nCurrent Telemetry Settings:");
telemetryConfig.Values.forEach(row => {
    const key = row[keyIndex];
    const value = row[valueIndex];
    const enabled = row[isEnabledIndex];
    const priority = row[priorityIndex];
    console.log(`- Key: ${key}, Value: ${value}, Enabled: ${enabled}, Priority: ${priority}`);
});

// Retrieve a specific setting.
const baseUrlSetting = telemetryConfig.Values.find(
    row => row[keyIndex] === "api_base_url"
);

if (baseUrlSetting) {
    console(`\nAPI Base URL: ${baseUrlSetting[valueIndex]}`); // Output: API Base URL: https://api.example.com/v1
} else {
    console.log("\n'api_base_url' setting not found.");
}
b. Updating Values

Updating a value involves locating the specific record and then modifying the data at the appropriate field index.

// File: example_update_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');

// Using the 'telemetryConfig' from the previous example.
const telemetryConfig = {
    Format: "BEJSON", Format_Version: "104a", Format_Creator: "Elton Boehnen",
    Records_Type: ["AppSetting"], AppName: "TelemetryService", ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging", LastUpdateTimestamp: "2026-11-01T12:34:56.789Z",
    Fields: [
        { name: "setting_key", type: "string" },
        { name: "setting_value", type: "string" },
        { name: "is_enabled", type: "boolean" },
        { name: "priority", type: "integer" }
    ],
    Values: [
        ["feature_flag_x", "true", true, 1],
        ["api_base_url", "https://api.example.com/v1", true, 0],
        ["cache_duration_minutes", "60", false, 2],
        ["max_retries", "3", true, 1]
    ]
};

const keyIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_key");
const valueIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_value");
const isEnabledIndex = BEJSON.getFieldIndex(telemetryConfig, "is_enabled");

// Update 'api_base_url'
const baseUrlRow = telemetryConfig.Values.find(row => row[keyIndex] === "api_base_url");
if (baseUrlRow) {
    baseUrlRow[valueIndex] = "https://new.api.example.com/v2_beta";
    console.log(`Updated 'api_base_url' to: ${baseUrlRow[valueIndex]}`);
}

// Disable 'cache_duration_minutes'
const cacheSettingRow = telemetryConfig.Values.find(row => row[keyIndex] === "cache_duration_minutes");
if (cacheSettingRow) {
    cacheSettingRow[isEnabledIndex] = false;
    console.log(`'cache_duration_minutes' enabled status: ${cacheSettingRow[isEnabledIndex]}`);
}

console.log("\nTelemetry Settings after update:");
telemetryConfig.Values.forEach(row => {
    console.log(`- Key: ${row[keyIndex]}, Value: ${row[valueIndex]}, Enabled: ${row[isEnabledIndex]}`);
});
c. Adding and Deleting Records

New records are appended to the Values array, strictly maintaining positional integrity by matching the Fields array length and using null for absent data. Deleting records involves filtering or splicing the Values array.

// File: example_add_delete_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');

// Using the 'telemetryConfig' from previous examples.
const telemetryConfig = {
    Format: "BEJSON", Format_Version: "104a", Format_Creator: "Elton Boehnen",
    Records_Type: ["AppSetting"], AppName: "TelemetryService", ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging", LastUpdateTimestamp: "2026-11-01T12:34:56.789Z",
    Fields: [
        { name: "setting_key", type: "string" },
        { name: "setting_value", type: "string" },
        { name: "is_enabled", type: "boolean" },
        { name: "priority", type: "integer" }
    ],
    Values: [
        ["feature_flag_x", "true", true, 1],
        ["api_base_url", "https://api.example.com/v1", true, 0],
        ["cache_duration_minutes", "60", false, 2],
        ["max_retries", "3", true, 1]
    ]
};

const keyIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_key");

console.log("Initial record count:", telemetryConfig.Values.length); // Output: Initial record count: 4

// Add a new setting.
const newSetting = ["max_connections", "100", true, 3];
telemetryConfig.Values.push(newSetting);
console.log("Record count after adding:", telemetryConfig.Values.length); // Output: Record count after adding: 5
console.log("Newly added setting:", telemetryConfig.Values[telemetryConfig.Values.length - 1]);

// Delete a setting (e.g., 'max_retries').
// Create a new array, filtering out the unwanted record.
telemetryConfig.Values = telemetryConfig.Values.filter(
    row => row[keyIndex] !== "max_retries"
);
console.log("Record count after deleting 'max_retries':", telemetryConfig.Values.length); // Output: Record count after deleting 'max_retries': 4

console.log("\nTelemetry Settings after add/delete operations:");
telemetryConfig.Values.forEach(row => {
    console.log(`- Key: ${row[keyIndex]}, Value: ${row[BEJSON.getFieldIndex(telemetryConfig, "setting_value")]}`);
});
d. Querying Records

The BEJSON.query function, provided by lib_bejson_Core_bejson_bejson.js, simplifies filtering records based on a specific field's value.

// File: example_query_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');

// Using the 'telemetryConfig' from previous examples.
const telemetryConfig = {
    Format: "BEJSON", Format_Version: "104a", Format_Creator: "Elton Boehnen",
    Records_Type: ["AppSetting"], AppName: "TelemetryService", ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging", LastUpdateTimestamp: "2026-11-01T12:34:56.789Z",
    Fields: [
        { name: "setting_key", type: "string" },
        { name: "setting_value", type: "string" },
        { name: "is_enabled", type: "boolean" },
        { name: "priority", type: "integer" }
    ],
    Values: [
        ["feature_flag_x", "true", true, 1],
        ["api_base_url", "https://api.example.com/v1", true, 0],
        ["cache_duration_minutes", "60", false, 2],
        ["max_retries", "3", true, 1],
        ["debug_mode", "false", false, 5]
    ]
};

const keyIndex = BEJSON.getFieldIndex(telemetryConfig, "setting_key");

// Query all enabled settings.
const enabledSettings = BEJSON.query(telemetryConfig, "is_enabled", true);
console.log("Enabled Settings:");
enabledSettings.forEach(row => console.log(`- ${row[keyIndex]} (Value: ${row[BEJSON.getFieldIndex(telemetryConfig, "setting_value")]})`));

// Query all disabled settings.
const disabledSettings = BEJSON.query(telemetryConfig, "is_enabled", false);
console.log("\nDisabled Settings:");
disabledSettings.forEach(row => console.log(`- ${row[keyIndex]} (Value: ${row[BEJSON.getFieldIndex(telemetryConfig, "setting_value")]})`));

/*
Expected output:

Enabled Settings:
- feature_flag_x (Value: true)
- api_base_url (Value: https://api.example.com/v1)
- max_retries (Value: 3)

Disabled Settings:
- cache_duration_minutes (Value: 60)
- debug_mode (Value: false)
*/

3. Validation of BEJSON 104a Documents

The robust validation of BEJSON documents is critical for maintaining data integrity. While lib_bejson_Core_bejson_bejson.js offers a basic isValid check, comprehensive structural and type validation for BEJSON 104a is performed by lib_bejson_validator.js. This library enforces all universal BEJSON requirements and 104a-specific rules, such as mandatory primitive types and strict positional integrity.

For the purpose of these examples, we will use a conceptual validate104a function that mirrors the key checks performed by lib_bejson_validator.js, including the error codes specified in lib_bejson_errors.js.

a. Conceptual validate104a Function
// File: conceptual_bejson_validator.js (Illustrative representation of lib_bejson_validator.js for 104a)

// Error codes, as defined in lib_bejson_errors.js
const ERROR_CODES = {
    E_INVALID_JSON: 1,
    E_MISSING_MANDATORY_KEY: 2,
    E_INVALID_FORMAT_VERSION: 3,
    E_INVALID_CREATOR: 4,
    E_INVALID_RECORDS_TYPE: 5,
    E_INVALID_FIELDS_ARRAY: 6,
    E_INVALID_VALUES_ARRAY: 7,
    E_INVALID_FIELD_DEFINITION: 8,
    E_INVALID_FIELD_TYPE: 9, // Specifically for 104a's primitive type constraint
    E_POSITIONAL_INTEGRITY_VIOLATION: 10,
    E_INVALID_ROW_TYPE: 11,
    E_INVALID_TYPE_MISMATCH: 12
};

function validate104a_conceptual(doc) {
    // 1. Universal BEJSON Requirements
    const mandatoryKeys = ["Format", "Format_Version", "Format_Creator", "Records_Type", "Fields", "Values"];
    for (const key of mandatoryKeys) {
        if (!(key in doc)) {
            throw new Error(`[${ERROR_CODES.E_MISSING_MANDATORY_KEY}] Mandatory key '${key}' is missing.`);
        }
    }
    if (doc.Format !== "BEJSON") throw new Error(`[${ERROR_CODES.E_INVALID_JSON}] 'Format' must be 'BEJSON'.`);
    if (doc.Format_Version !== "104a") throw new Error(`[${ERROR_CODES.E_INVALID_FORMAT_VERSION}] 'Format_Version' must be '104a'.`);
    if (doc.Format_Creator !== "Elton Boehnen") throw new Error(`[${ERROR_CODES.E_INVALID_CREATOR}] 'Format_Creator' must be 'Elton Boehnen'.`);
    if (!Array.isArray(doc.Records_Type) || doc.Records_Type.length !== 1 || typeof doc.Records_Type[0] !== 'string') {
        throw new Error(`[${ERROR_CODES.E_INVALID_RECORDS_TYPE}] 'Records_Type' must be an array with exactly one string.`);
    }
    if (!Array.isArray(doc.Fields) || doc.Fields.length === 0) throw new Error(`[${ERROR_CODES.E_INVALID_FIELDS_ARRAY}] 'Fields' array is invalid or empty.`);
    if (!Array.isArray(doc.Values)) throw new Error(`[${ERROR_CODES.E_INVALID_VALUES_ARRAY}] 'Values' array is invalid.`);

    // 2. BEJSON 104a Specific: Primitive Types Only
    const primitiveTypes = ["string", "integer", "number", "boolean"];
    for (const field of doc.Fields) {
        if (!field.name || typeof field.name !== 'string') throw new Error(`[${ERROR_CODES.E_INVALID_FIELD_DEFINITION}] Field missing 'name' or it's not a string.`);
        if (!field.type || typeof field.type !== 'string' || !primitiveTypes.includes(field.type)) {
            throw new Error(`[${ERROR_CODES.E_INVALID_FIELD_TYPE}] Field '${field.name}' has invalid or non-primitive type '${field.type}'. BEJSON 104a only allows primitive types.`);
        }
    }

    // 3. Positional Integrity and Type Consistency of Values
    const expectedFieldCount = doc.Fields.length;
    for (let i = 0; i < doc.Values.length; i++) {
        const row = doc.Values[i];
        if (!Array.isArray(row)) throw new Error(`[${ERROR_CODES.E_INVALID_ROW_TYPE}] Value row ${i} is not an array.`);
        if (row.length !== expectedFieldCount) {
            throw new Error(`[${ERROR_CODES.E_POSITIONAL_INTEGRITY_VIOLATION}] Row ${i} has ${row.length} values, but ${expectedFieldCount} fields are defined.`);
        }
        for (let j = 0; j < expectedFieldCount; j++) {
            const declaredType = doc.Fields[j].type;
            const actualValue = row[j];
            if (actualValue === null) continue; // Null is always allowed for padding

            if (declaredType === "string" && typeof actualValue !== "string") {
                throw new Error(`[${ERROR_CODES.E_INVALID_TYPE_MISMATCH}] Row ${i}, field '${doc.Fields[j].name}' expects string, got ${typeof actualValue}.`);
            }
            if ((declaredType === "integer" || declaredType === "number") && typeof actualValue !== "number") {
                 throw new Error(`[${ERROR_CODES.E_INVALID_TYPE_MISMATCH}] Row ${i}, field '${doc.Fields[j].name}' expects number/integer, got ${typeof actualValue}.`);
            }
            if (declaredType === "boolean" && typeof actualValue !== "boolean") {
                throw new Error(`[${ERROR_CODES.E_INVALID_TYPE_MISMATCH}] Row ${i}, field '${doc.Fields[j].name}' expects boolean, got ${typeof actualValue}.`);
            }
        }
    }
    return true; // Document is valid if no errors are thrown
}

module.exports = { validate104a_conceptual };
b. Demonstrating Validation

This example uses the conceptual validate104a_conceptual function to check a valid 104a document and then deliberately introduces errors to demonstrate how validation failures are reported.

// File: example_validation_104a.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');
const { validate104a_conceptual } = require('./conceptual_bejson_validator.js'); // Our conceptual validator

// A valid BEJSON 104a document
const validTelemetryConfig = {
    Format: "BEJSON", Format_Version: "104a", Format_Creator: "Elton Boehnen",
    Records_Type: ["AppSetting"], AppName: "TelemetryService", ConfigVersion: "1.2.0",
    DeploymentEnvironment: "Staging", LastUpdateTimestamp: "2026-11-01T12:34:56.789Z",
    Fields: [
        { name: "setting_key", type: "string" },
        { name: "setting_value", type: "string" },
        { name: "is_enabled", type: "boolean" },
        { name: "priority", type: "integer" }
    ],
    Values: [
        ["feature_flag_x", "true", true, 1],
        ["api_base_url", "https://api.example.com/v1", true, 0],
        ["cache_duration_minutes", "60", false, 2],
        ["max_retries", "3", true, 1],
        ["debug_mode", "false", false, null] // null is allowed for positional integrity
    ]
};

console.log("--- Validating a correct BEJSON 104a document ---");
try {
    validate104a_conceptual(validTelemetryConfig);
    console.log("SUCCESS: Document is valid.");
} catch (error) {
    console.error("FAILURE: Document reported as invalid:", error.message);
}

console.log("\n--- Testing invalid scenarios ---");

// Scenario 1: Missing mandatory key (e.g., 'Values')
const invalidDocMissingValues = { ...validTelemetryConfig };
delete invalidDocMissingValues.Values;
try {
    validate104a_conceptual(invalidDocMissingValues);
} catch (error) {
    console.log(`CAUGHT ERROR (Missing Key): ${error.message}`);
}

// Scenario 2: Non-primitive type in 'Fields' (e.g., 'object' or 'array')
const invalidDocNonPrimitiveField = JSON.parse(JSON.stringify(validTelemetryConfig));
invalidDocNonPrimitiveField.Fields.push({ name: "complex_settings", type: "object" }); // 104a forbids complex types
invalidDocNonPrimitiveField.Values.forEach(row => row.push(null)); // Maintain row length for now
try {
    validate104a_conceptual(invalidDocNonPrimitiveField);
} catch (error) {
    console.log(`CAUGHT ERROR (Non-primitive Field Type): ${error.message}`);
}

// Scenario 3: Positional integrity violation (row length mismatch)
const invalidDocPositionalViolation = JSON.parse(JSON.stringify(validTelemetryConfig));
invalidDocPositionalViolation.Values[0].pop(); // Remove a value from the first record
try {
    validate104a_conceptual(invalidDocPositionalViolation);
} catch (error) {
    console.log(`CAUGHT ERROR (Positional Integrity): ${error.message}`);
}

// Scenario 4: Type mismatch for a value (e.g., boolean where string is expected)
const invalidDocTypeMismatch = JSON.parse(JSON.stringify(validTelemetryConfig));
const valueIdx = BEJSON.getFieldIndex(invalidDocTypeMismatch, "setting_value");
invalidDocTypeMismatch.Values[0][valueIdx] = false; // "true" (string) -> false (boolean)
try {
    validate104a_conceptual(invalidDocTypeMismatch);
} catch (error) {
    console.log(`CAUGHT ERROR (Type Mismatch): ${error.message}`);
}

// Scenario 5: Records_Type is not an array of exactly one string
const invalidDocRecordsType = JSON.parse(JSON.stringify(validTelemetryConfig));
invalidDocRecordsType.Records_Type = ["AppSetting", "AnotherType"]; // Too many elements
try {
    validate104a_conceptual(invalidDocRecordsType);
} catch (error) {
    console.log(`CAUGHT ERROR (Invalid Records_Type): ${error.message}`);
}

/*
Expected output (error codes match conceptual_bejson_validator.js):

--- Validating a correct BEJSON 104a document ---
SUCCESS: Document is valid.

--- Testing invalid scenarios ---
CAUGHT ERROR (Missing Key): [2] Mandatory key 'Values' is missing.
CAUGHT ERROR (Non-primitive Field Type): [9] Field 'complex_settings' has invalid or non-primitive type 'object'. BEJSON 104a only allows primitive types.
CAUGHT ERROR (Positional Integrity): [10] Row 0 has 3 values, but 4 fields are defined.
CAUGHT ERROR (Type Mismatch): [12] Row 0, field 'setting_value' expects string, got boolean.
CAUGHT ERROR (Invalid Records_Type): [5] 'Records_Type' must be an array with exactly one string.
*/

These examples demonstrate how core libraries facilitate working with BEJSON 104a. The create104a function ensures initial adherence to the format, while getFieldIndex and query provide efficient data access and retrieval. Crucially, the validation mechanisms, as conceptually presented by validate104a_conceptual and executed by lib_bejson_validator.js in a production environment, rigorously enforce 104a's specific constraints regarding primitive types and structural integrity. This combination of tools ensures that BEJSON 104a documents remain consistent, predictable, and reliable for their designated roles in configuration and metadata management. The direct application of these libraries, such as BEJSON_Switch.BEJSON.create104a used in lib_bejson_Core_bejson_assets.js for asset registries, further underscores their practical utility within the BEJSON ecosystem.

Chapter 6

Chapter 6: BEJSON 104a as an MFDB Manifest – Orchestrating Multi-File Databases

Chapter 6: BEJSON 104a as an MFDB Manifest – Orchestrating Multi-File Databases

BEJSON 104a documents play a distinct and critical role as manifest files within the Multi-File Database (MFDB) architecture. While BEJSON 104a is primarily utilized for lightweight configuration and metadata, its specific characteristics—namely, its allowance for custom top-level headers and its enforcement of primitive data types—make it uniquely suited to serve as the central registry for an MFDB. This chapter details the structure and validation requirements for a BEJSON 104a document when operating as an MFDB manifest, illustrating how it orchestrates a collection of individual BEJSON 104 entity files into a cohesive database.

The Role of BEJSON 104a in MFDB Architecture

An MFDB system aggregates multiple BEJSON 104 files, referred to as "entity files," under the governance of a single BEJSON 104a manifest file. The manifest acts as the database's entry point, cataloging all entity files, their respective types, and their relative paths. This design leverages 104a's strengths:

  1. Centralized Metadata: The manifest uses 104a's custom header capability to store database-wide metadata such as MFDB_Version, DB_Name, and potentially project-specific configurations relevant to the entire database.
  2. Lightweight Structure: By restricting data within its Values array to primitive types, 104a ensures the manifest remains small and quick to parse, even in large databases with many entity files. This is consistent with its role as a registry, not a data store itself.
  3. Schema Definition for Entities: The Fields array within the manifest defines the expected structure for cataloging each entity file, including its name and file path.

MFDB Manifest Specific Requirements

For a BEJSON 104a document to function as an MFDB manifest, it must adhere to specific validation rules beyond the standard 104a format. These are enforced by lib_mfdb_validator.js and lib_mfdb_core.js.

Mandatory MFDB Manifest Criteria:

  • Format Type: The document must be a valid BEJSON 104a file.
  • Records_Type Constraint: The Records_Type array must contain exactly one string: ["mfdb"]. This explicitly identifies the document's role as an MFDB manifest.
  • Required Headers: It must include specific custom top-level headers:
    • MFDB_Version: A string indicating the MFDB standard version (e.g., "1.31").
    • DB_Name: A string specifying the name of the multi-file database.
  • Fields Array: The Fields array must include at minimum:
    • {"name": "entity_name", "type": "string"}: The logical name of an entity (e.g., "User", "Product"). This name must also match the Records_Type of the corresponding BEJSON 104 entity file.
    • {"name": "file_path", "type": "string"}: The relative path from the manifest to the entity file.
  • Path Safety: All file_path values listed in Values must be relative and confined within the database's root directory, preventing arbitrary file access.
  • Snake_Case Convention: All field names, including entity_name and file_path, must strictly follow snake_case for ecosystem compatibility.

The lib_bejson_Core_bejson_chunking.js library, as indicated by its documentation, provides mechanisms for packaging and unpacking MFDB databases, supporting both the traditional 1.31 .zip container and the newer 1.32 "Chunked-104a" format, which embeds the entire database within a single 104a file. Regardless of the packaging, the internal manifest structure remains consistent with these requirements.

Orchestration and Bidirectional Integrity

The manifest's primary function is to map logical entity_names to physical file_paths. For each entry in the manifest's Values array, there is an expectation of a corresponding BEJSON 104 entity file. This relationship is not unidirectional; each BEJSON 104 entity file must contain a Parent_Hierarchy key that points back to its manifest. This Parent_Hierarchy link includes information like the manifest's file_path and DB_Name, ensuring a bidirectional validation check can be performed. The lib_mfdb_validator.js library is responsible for ensuring this integrity, confirming that paths from the manifest lead to valid entity files, and that entity files correctly reference their parent manifest.

BEJSON 104a MFDB Manifest Scheme Example

The following is an example of a 104a.mfdb.bejson manifest file, demonstrating the required structure and custom headers.

{
  "Format": "BEJSON",
  "Format_Version": "104a",
  "Format_Creator": "Elton Boehnen",
  "Records_Type": ["mfdb"],
  "MFDB_Version": "1.31",
  "DB_Name": "ProductCatalog",
  "Created_Timestamp": "2026-07-20T10:30:00Z",
  "Last_Modified_Timestamp": "2026-07-20T14:15:00Z",
  "Fields": [
    { "name": "entity_name", "type": "string" },
    { "name": "file_path", "type": "string" },
    { "name": "description", "type": "string" },
    { "name": "is_active", "type": "boolean" }
  ],
  "Values": [
    ["Product", "entities/products.104.bejson", "Details of all products", true],
    ["Category", "entities/categories.104.bejson", "Product categories", true],
    ["Supplier", "entities/suppliers.104.bejson", "Supplier information", true],
    ["Review", "entities/reviews.104.bejson", "Customer reviews (inactive)", false]
  ]
}

In this example, Records_Type is correctly set to ["mfdb"]. The custom headers MFDB_Version, DB_Name, Created_Timestamp, and Last_Modified_Timestamp provide essential metadata for the entire database. The Fields array defines how each entity is described, including its entity_name (e.g., "Product"), its file_path (e.g., "entities/products.104.bejson"), a description, and an is_active flag. All field types are primitive, adhering to 104a's strict type policy.

Code Example: Creating and Validating an MFDB Manifest

The creation and validation of an MFDB manifest leverage functions from lib_bejson_Core_bejson_bejson.js for basic 104a structure and lib_mfdb_validator.js for MFDB-specific rules.

// File: example_mfdb_manifest.js
const BEJSON = require('./lib_bejson_Core_bejson_bejson.js');
const { mfdb_validator_validate_manifest } = require('./lib_bejson_Core_mfdb_validator.js');
const path = require('path'); // For path operations if dealing with file paths

// Define fields required for an MFDB manifest
const manifestFields = [
    { name: "entity_name", type: "string" },
    { name: "file_path", type: "string" },
    { name: "description", type: "string" },
    { name: "is_active", type: "boolean" }
];

// Define records for the manifest
const manifestValues = [
    ["Product", "entities/products.104.bejson", "Details of all products", true],
    ["Category", "entities/categories.104.bejson", "Product categories", true],
    ["Supplier", "entities/suppliers.104.bejson", "Supplier information", true],
    ["Review", "entities/reviews.104.bejson", "Customer reviews (inactive)", false]
];

// Define custom top-level headers for the MFDB manifest
const manifestMetadata = {
    MFDB_Version: "1.31",
    DB_Name: "ProductCatalog",
    Created_Timestamp: new Date().toISOString(),
    Last_Modified_Timestamp: new Date().toISOString()
};

// Create the BEJSON 104a manifest document
const mfdbManifest = BEJSON.create104a(
    "mfdb",              // Records_Type must be "mfdb" for manifests
    manifestFields,
    manifestValues,
    manifestMetadata
);

console.log("--- Created MFDB Manifest ---");
console.log(JSON.stringify(mfdbManifest, null, 2));

// --- Conceptual Validation (mfdb_validator_validate_manifest is part of the KB) ---
// For a full validation, mfdb_validator_validate_manifest would be called.
// This function performs the following checks (among others):
// - Ensures Records_Type is ["mfdb"]
// - Validates presence of MFDB_Version and DB_Name headers
// - Confirms 'entity_name' and 'file_path' fields exist and are of type 'string'
// - Verifies all listed file_paths are relative and adhere to path safety.

console.log("\n--- Attempting MFDB Manifest Validation (conceptual) ---");
try {
    // In a real scenario, this would be:
    // mfdb_validator_validate_manifest(mfdbManifest, "/path/to/db/root");
    // For this example, we'll simulate a successful outcome assuming paths are valid.
    console.log("Conceptual MFDB Manifest validation: PASSED.");

    // Simulate an invalid scenario: missing MFDB_Version
    const invalidManifest = JSON.parse(JSON.stringify(mfdbManifest));
    delete invalidManifest.MFDB_Version;
    console.log("\n--- Testing invalid scenario: Missing 'MFDB_Version' ---");
    try {
        mfdb_validator_validate_manifest(invalidManifest, "/path/to/db/root"); // This would throw an error
    } catch (error) {
        // Based on lib_bejson_errors.js and mfdb_validator_is_mfdb_manifest logic:
        console.error(`CAUGHT ERROR: Manifest validation failed due to missing 'MFDB_Version'. (Error Code: E_MFDB_NOT_MANIFEST/missing header)`);
    }

    // Simulate an invalid scenario: wrong Records_Type
    const invalidRecordsTypeManifest = JSON.parse(JSON.stringify(mfdbManifest));
    invalidRecordsTypeManifest.Records_Type = ["config"];
    console.log("\n--- Testing invalid scenario: Incorrect 'Records_Type' ---");
    try {
        mfdb_validator_validate_manifest(invalidRecordsTypeManifest, "/path/to/db/root"); // This would throw an error
    } catch (error) {
        // Based on lib_bejson_errors.js and mfdb_validator_is_mfdb_manifest logic:
        console.error(`CAUGHT ERROR: Manifest validation failed due to incorrect 'Records_Type'. (Error Code: E_MFDB_NOT_MANIFEST/wrong records_type)`);
    }

} catch (e) {
    console.error("MFDB Manifest validation encountered an unexpected error:", e.message);
}

This code demonstrates that the BEJSON.create104a function, as also seen in the prior chapter, is instrumental in constructing the foundational 104a document. Subsequently, the mfdb_validator_validate_manifest function (from lib_bejson_Core_mfdb_validator.js) would be invoked to perform the MFDB-specific structural and data integrity checks, including ensuring the correct Records_Type, mandatory MFDB headers, and field definitions. The ability to distinguish between valid MFDB manifests and generic 104a documents is crucial for the stability and reliable operation of any multi-file database environment.