The DTMS Library Management API provides automatic update capabilities for frontend libraries (AlpineJS and HTMX). This system ensures DTMS always has access to the latest, secure, and performance-optimized versions of essential frontend frameworks.
http://dtms.localhost/core/api/libraries
Currently, the Library Management API uses the same authentication mechanism as other DTMS core APIs. CSRF protection is implemented for state-changing operations.
Get information about available library updates.
Endpoint: GET /libraries/check-updates
Response:
{
"alpine": {
"current_version": "3.13.3",
"latest_version": "3.14.9",
"has_update": true,
"download_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
},
"htmx": {
"current_version": "1.9.8",
"latest_version": "2.0.6",
"has_update": true,
"download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
}
}Error Response:
{
"alpine": {
"error": "Failed to fetch Alpine.js releases from GitHub API"
},
"htmx": {
"current_version": "1.9.8",
"latest_version": "2.0.6",
"has_update": true,
"download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
}
}Update a specific library to the latest version or force update.
Endpoint: POST /libraries/update
Request Body:
{
"library": "alpine", // Required: "alpine" or "htmx"
"force": false // Optional: force update even if already latest
}Success Response (Updated):
{
"updated": true,
"message": "Updated from 3.13.3 to 3.14.9",
"previous_version": "3.13.3",
"new_version": "3.14.9",
"file_size": "43.7KB",
"integrity": "sha384-9Ax3MmS9AClxJyd5/zafcXXjxmwFhZCdsT6HJoJjarvCaAkJlk5QDzjLJm+Wdx5F"
}Success Response (Already Updated):
{
"updated": false,
"message": "Already on latest version 3.14.9",
"current_version": "3.14.9",
"latest_version": "3.14.9"
}Error Response:
{
"error": "Failed to download from https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
}| Status Code | Description |
|---|---|
200 |
Success |
400 |
Bad Request (invalid library name, malformed JSON) |
405 |
Method Not Allowed (wrong HTTP method) |
500 |
Internal Server Error (download failure, file system error) |
// Check for updates
async function checkLibraryUpdates() {
try {
const response = await fetch("/core/api/libraries/check-updates");
const updates = await response.json();
console.log("Available updates:", updates);
return updates;
} catch (error) {
console.error("Failed to check updates:", error);
throw error;
}
}
// Update a library
async function updateLibrary(libraryName, force = false) {
try {
const response = await fetch("/core/api/libraries/update", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": await getCSRFToken(), // Implement as needed
},
body: JSON.stringify({
library: libraryName,
force: force,
}),
});
const result = await response.json();
if (!response.ok) {
throw new Error(result.error || "Update failed");
}
console.log("Update result:", result);
return result;
} catch (error) {
console.error("Failed to update library:", error);
throw error;
}
}
// Example usage
async function updateAllLibraries() {
const updates = await checkLibraryUpdates();
for (const [lib, info] of Object.entries(updates)) {
if (info.has_update) {
console.log(`Updating ${lib}...`);
const result = await updateLibrary(lib);
if (result.updated) {
console.log(`✅ ${lib} updated successfully!`);
}
}
}
}# Check for updates
curl -s "http://dtms.localhost/core/api/libraries/check-updates" | jq '.'
# Update AlpineJS
curl -X POST "http://dtms.localhost/core/api/libraries/update" \
-H "Content-Type: application/json" \
-d '{"library":"alpine","force":false}' | jq '.'
# Force update HTMX
curl -X POST "http://dtms.localhost/core/api/libraries/update" \
-H "Content-Type: application/json" \
-d '{"library":"htmx","force":true}' | jq '.'<?php
class DTMSLibraryClient
{
private $baseUrl;
private $csrfToken;
public function __construct($baseUrl = 'http://dtms.localhost/core/api/libraries')
{
$this->baseUrl = $baseUrl;
}
public function checkUpdates(): array
{
$response = file_get_contents($this->baseUrl . '/check-updates');
if ($response === false) {
throw new Exception('Failed to fetch update information');
}
return json_decode($response, true);
}
public function updateLibrary(string $library, bool $force = false): array
{
$data = [
'library' => $library,
'force' => $force
];
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => [
'Content-Type: application/json',
// Add CSRF token if available
// 'X-CSRF-Token: ' . $this->csrfToken
],
'content' => json_encode($data)
]
]);
$response = file_get_contents($this->baseUrl . '/update', false, $context);
if ($response === false) {
throw new Exception('Failed to update library');
}
return json_decode($response, true);
}
public function updateAll(): array
{
$updates = $this->checkUpdates();
$results = [];
foreach ($updates as $library => $info) {
if (isset($info['has_update']) && $info['has_update']) {
try {
$result = $this->updateLibrary($library);
$results[$library] = $result;
} catch (Exception $e) {
$results[$library] = ['error' => $e->getMessage()];
}
}
}
return $results;
}
}
// Usage example
$client = new DTMSLibraryClient();
try {
// Check what updates are available
$updates = $client->checkUpdates();
echo "Available updates:\n";
print_r($updates);
// Update all libraries
$results = $client->updateAll();
echo "Update results:\n";
print_r($results);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}DTMS includes a command-line script for batch operations:
# Check for updates
./scripts/update-libraries.sh check
# Update all libraries
./scripts/update-libraries.sh update-all
# Force update all libraries
./scripts/update-libraries.sh force-update-allCheck Updates:
🔍 Vérification des mises à jour disponibles...
{
"alpine": {
"current_version": "3.14.9",
"latest_version": "3.14.9",
"has_update": false,
"download_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js"
},
"htmx": {
"current_version": "2.0.6",
"latest_version": "2.0.6",
"has_update": false,
"download_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js"
}
}Update All:
🚀 Mise à jour de toutes les bibliothèques...
📦 Mise à jour de alpine...
{
"updated": false,
"message": "Already on latest version 3.14.9",
"current_version": "3.14.9",
"latest_version": "3.14.9"
}
ℹ️ alpine: Already on latest version 3.14.9
📦 Mise à jour de htmx...
{
"updated": false,
"message": "Already on latest version 2.0.6",
"current_version": "2.0.6",
"latest_version": "2.0.6"
}
ℹ️ htmx: Already on latest version 2.0.6
✨ Mise à jour terminée. Vérification finale...
# ... final status checkThe library management system maintains the following structure:
public/assets/js/lib/
├── dtms-lib-manager.js # Intelligent library loader
├── alpine.min.js # AlpineJS library file
├── htmx.min.js # HTMX library file
└── versions.json # Version tracking and metadata
{
"alpine": {
"current_version": "3.14.9",
"local_file": "alpine.min.js",
"cdn_url": "https://cdn.jsdelivr.net/npm/alpinejs@3.14.9/dist/cdn.min.js",
"last_updated": "2025-08-23T13:37:55+08:00",
"file_size": "43.7KB",
"integrity": "sha384-9Ax3MmS9AClxJyd5/zafcXXjxmwFhZCdsT6HJoJjarvCaAkJlk5QDzjLJm+Wdx5F"
},
"htmx": {
"current_version": "2.0.6",
"local_file": "htmx.min.js",
"cdn_url": "https://unpkg.com/htmx.org@2.0.6/dist/htmx.min.js",
"last_updated": "2025-08-23T13:38:56+08:00",
"file_size": "49.8KB",
"integrity": "sha384-Akqfrbj/HpNVo8k11SXBb6TlBWmXXlYQrCSqEWmyKJe+hDm3Z/B2WVG4smwBkRVm"
},
"update_strategy": "cdn-with-fallback",
"last_check": "2025-08-23T13:38:56+08:00",
"admin_notes": "Installed via DTMS lib manager"
}The system uses a hybrid approach for version detection:
- AlpineJS:
https://api.github.com/repos/alpinejs/alpine/releases/latest - HTMX:
https://api.github.com/repos/bigskysoftware/htmx/releases/latest
If GitHub API is unavailable, the system falls back to hardcoded latest known versions:
- AlpineJS: v3.14.9
- HTMX: v2.0.6
This ensures the update system remains functional even in environments with restricted internet access.
All downloaded libraries are verified using SHA384 checksums:
// Generate and verify integrity
$content = file_get_contents($downloadUrl);
$integrity = 'sha384-' . base64_encode(hash('sha384', $content, true));
// Store in versions.json for future verification
$versions[$library]['integrity'] = $integrity;Before updating, the system creates automatic backups:
// Backup current file
if (file_exists($targetFile)) {
copy($targetFile, $targetFile . '.backup');
}
// Rollback on failure
if ($updateFailed && file_exists($backupFile)) {
copy($backupFile, $targetFile);
}Basic validation prevents corrupted downloads:
// Verify minimum file size
if (strlen($newContent) < 1000) {
throw new Exception("Downloaded file too small, possible error");
}The API provides comprehensive error handling:
-
Network Issues
- GitHub API unavailable
- CDN download failures
- Timeout errors
-
File System Issues
- Permission errors
- Disk space problems
- Write failures
-
Validation Errors
- Corrupted downloads
- Invalid JSON responses
- Missing version information
{
"error": "Descriptive error message",
"error_code": "DOWNLOAD_FAILED", // Optional error code
"details": {
// Optional additional details
"url": "https://...",
"http_status": 404
}
}- Version information is cached in
versions.json - Update checks use conditional requests when possible
- Local files serve as fallback for performance
- GitHub API calls are rate-limited (60 requests/hour for unauthenticated)
- Fallback versions prevent API exhaustion
- Update checks are typically manual or scheduled
- Files are streamed directly to disk
- Progress tracking for large downloads
- Resume capability for interrupted downloads (future feature)
Library operations are logged through DTMS's standard logging system:
error_log("DTMS Library Manager: Updated {$library} from {$oldVersion} to {$newVersion}");Web-based monitoring available at /admin/libraries.html:
- Real-time update status
- Version history
- Manual update triggers
- System health indicators
For production environments, consider scheduling regular update checks:
#!/bin/bash
# Add to crontab: 0 2 * * 0 /path/to/update-libraries.sh update-all
cd /path/to/dtms
./scripts/update-libraries.sh update-all >> /var/log/dtms-library-updates.log 2>&1# GitHub Actions example
name: Update DTMS Libraries
on:
schedule:
- cron: "0 2 * * 1" # Weekly on Monday 2 AM
workflow_dispatch:
jobs:
update-libraries:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Update Libraries
run: |
./scripts/update-libraries.sh update-all
git add public/assets/js/lib/
git commit -m "Auto-update frontend libraries" || echo "No updates"
git push-
Additional Libraries
- Vue.js support
- React integration
- Custom library definitions
-
Advanced Update Strategies
- Staged rollouts
- A/B testing support
- Automatic rollback on errors
-
Enhanced Security
- GPG signature verification
- Subresource Integrity (SRI) enforcement
- Vulnerability scanning
-
Better Monitoring
- Usage analytics
- Performance metrics
- Update success rates