Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sourcemap Laravel Package

axy/sourcemap

PHP library to create, load, search, and modify Source Map files. Supports renaming/removing sources, adjusting mappings, handling insert/remove blocks, concatenating maps for concatenated outputs, and merging intermediate maps. Works with maps only, not source/output code.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require axy/sourcemap
    

    Requires PHP 8.1+.

  2. First Use Case: Load an existing source map and inspect its contents:

    use axy\sourcemap\SourceMap;
    
    $map = SourceMap::loadFromFile('path/to/file.js.map');
    echo $map->file; // Outputs the original file name
    print_r($map->sources->getNames()); // Lists source files
    
  3. Where to Look First:


Implementation Patterns

Workflow: Build a Concatenated Source Map

  1. Initialize:

    $resultMap = new SourceMap();
    $resultMap->file = 'out.js';
    $result = [];
    $lineOffset = 0;
    
  2. Process Each File:

    foreach ($files as $file) {
        $content = file_get_contents($file);
        $content = preg_replace('~//# sourceMappingURL.*$~s', '', $content);
        $result[] = $content;
        $map = SourceMap::loadFromFile($file . '.map');
        $resultMap->concat($map, $lineOffset);
        $lineOffset += substr_count($content, "\n") + 1;
    }
    
  3. Save Results:

    file_put_contents('out.js', implode("\n", $result));
    $resultMap->save('out.js.map');
    

Workflow: Merge Intermediate Maps

  1. Load Final Map:

    $finalMap = SourceMap::loadFromFile('out.js.map');
    
  2. Merge Intermediate Maps:

    $finalMap->merge('ab.js.map');
    $finalMap->merge('cd.js.map');
    
  3. Save Merged Map:

    $finalMap->save('out.js.map');
    

Integration with Laravel

  1. Service Provider:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $this->app->singleton(SourceMap::class, function () {
            return new SourceMap();
        });
    }
    
  2. Facade (Optional):

    // app/Facades/SourceMapFacade.php
    public static function load($path)
    {
        return app(SourceMap::class)->loadFromFile($path);
    }
    
  3. Artisan Command for Concatenation:

    // app/Console/Commands/ConcatenateAssets.php
    public function handle()
    {
        $map = new SourceMap();
        $map->file = 'public/assets/concatenated.js';
        // ... concatenation logic ...
        $map->save('public/assets/concatenated.js.map');
    }
    

Gotchas and Tips

Pitfalls

  1. Zero-Based Indexing: All line/column numbers and indexes (sources/names) are zero-based. Forgetting this causes off-by-one errors.

    // Wrong: Assumes 1-based
    $position = $map->getPosition(1, 1); // Fails (should be 0, 0)
    
  2. Mutable Objects in concat()/merge(): Passing a SourceMap instance to concat() or merge() mutates the original object. Clone it first if reuse is needed:

    $map1->concat(clone $map2, 10); // Safe
    $map1->concat($map2, 10);      // Unsafe (modifies $map2)
    
  3. Source Content Handling:

    • sourcesContent is optional and may be null for external files.
    • Modifying sourcesContent does not update mappings automatically.
  4. File Path Resolution: The library does not resolve paths relative to sourceRoot. Use absolute paths or handle resolution manually.

Debugging Tips

  1. Validate Mappings: Use getPosition() to verify mappings after modifications:

    $pos = $map->getPosition(5, 10);
    if (!$pos) {
        throw new \RuntimeException("Mapping missing at line 5, column 10");
    }
    
  2. Inspect Changes: Dump the raw data before/after operations:

    echo $map->toArray(); // Debug output
    
  3. Handle Edge Cases:

    • Empty sources or names arrays.
    • Invalid mappings strings (e.g., malformed VLQ).

Extension Points

  1. Custom Position Filters: Extend PosMap to add domain-specific filters:

    class CustomPosMap extends \axy\sourcemap\PosMap {
        public ?string $customField;
    }
    
  2. Pre/Post-Processing: Hook into save() to transform the map before writing:

    $map->onSave(function ($data) {
        $data['customField'] = 'value';
        return $data;
    });
    
  3. Integration with Laravel Mix/Vite: Use the package to rebuild source maps after custom transformations:

    // In a Laravel Mix extension
    mix.extend('customTransform', function () {
        $map = SourceMap::loadFromFile('input.js.map');
        // Modify $map...
        $map->save('output.js.map');
    });
    

Performance Notes

  • Large Maps: Use find() with filters instead of getAllPositions() for performance.
  • Memory: Cloning SourceMap objects can be expensive. Reuse instances where possible.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon