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

Sourcemaps Lookup Laravel Package

spatie/sourcemaps-lookup

Fast, memory-efficient Source Map v3 lookup for PHP. Resolve JavaScript stack frames to original source file, line/column, symbol name, and enclosing scope. Optimized for the read path and high-volume error symbolicating from uploaded sourcemaps.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The package excels at symbolicating JavaScript stack traces (e.g., converting minified/bundled error positions to original source locations). This is a niche but critical need for:
    • Debugging tools (e.g., error trackers like Sentry, Rollbar).
    • IDE integrations (e.g., mapping stack traces to TypeScript/JSX files).
    • Performance monitoring (e.g., correlating errors to source code).
  • Laravel Synergy: Laravel’s ecosystem (e.g., Vite, Webpack, Laravel Mix) generates source maps for asset compilation. This package directly addresses debugging minified assets in production, a pain point for Laravel devs using frontend tooling.
  • Isolation: The package is read-only (no map generation/merging), aligning with Laravel’s typical use case of consuming pre-built source maps from bundlers.

Integration Feasibility

  • Low Friction: Requires no Laravel-specific dependencies (pure PHP 8.3+). Integration is as simple as:
    $map = SourceMapLookup::fromFile(public_path('js/bundle.js.map'));
    $position = $map->lookup(42, 17);
    
  • Asset Pipeline Hooks: Can be plugged into Laravel’s booted event or middleware to automatically resolve stack traces from frontend errors (e.g., via JavaScript window.onerror).
  • Caching Layer: The package’s lazy-parsing design (only decodes lines on demand) makes it memory-efficient for high-traffic apps. A Redis cache could store parsed maps for repeated lookups.

Technical Risk

  • Source Map Quality: Garbage in, garbage out. If upstream bundlers (e.g., Vite, Webpack) generate malformed or incomplete source maps, the package will return null or incorrect mappings. Mitigation:
    • Validate source maps during build (e.g., using source-map-resolve in Node.js).
    • Fallback to raw minified positions if symbolicating fails.
  • Performance at Scale: While benchmarks show 3.8ms for 20 lookups, high-volume apps (e.g., 10K+ errors/hour) may need:
    • Pre-parsing maps during asset compilation (tradeoff: higher build time, faster runtime).
    • Rate-limiting to avoid parsing spikes.
  • Scope Resolution Limitations: The scopeAt() feature is heuristic-only (no native scopes field support). Useful for basic scoping but not reliable for complex cases (e.g., closures in React hooks).

Key Questions

  1. Where will source maps be stored?

    • Local files (e.g., public/js/*.map)?
    • Remote URLs (e.g., CDN-hosted maps)?
    • Database (e.g., serialized JSON in a source_maps table)? Impact: Affects caching strategy and error handling.
  2. How will errors be ingested?

    • Directly from JavaScript (e.g., fetch('/api/errors', { body: error }))?
    • Via a queue (e.g., Laravel Horizon) for async processing? Impact: Determines latency requirements and concurrency needs.
  3. What’s the fallback for unresolved positions?

    • Return minified coordinates?
    • Log a warning?
    • Skip symbolicating entirely? Impact: User experience for unmapable errors.
  4. Will this be used for production errors only, or also dev-time debugging?

    • Dev: Could integrate with Laravel’s debugbar or telescope.
    • Prod: Focus on error tracking (e.g., Sentry plugins). Impact: Affects performance vs. accuracy tradeoffs.
  5. Are there existing source map tools in the stack?

    • E.g., source-map in Node.js, browser DevTools.
    • Overlap could lead to duplication or inconsistent mappings. Impact: May require coordination with frontend tooling.

Integration Approach

Stack Fit

  • Laravel Compatibility: Zero conflicts with Laravel’s core. Works alongside:
    • Frontend: Vite, Webpack, Laravel Mix (all generate source maps).
    • Error Tracking: Sentry, Bugsnag, or custom solutions.
    • Caching: Redis, Laravel Cache (for parsed maps).
  • PHP Version: Requires PHP 8.3+ (Laravel 10+). If using older Laravel, this is a blocker.
  • Dependencies: None beyond Composer autoloading.

Migration Path

  1. Phase 1: Proof of Concept

    • Add the package to composer.json.
    • Test with a single source map (e.g., resources/js/app.js.map).
    • Verify lookup() returns correct original positions.
    • Goal: Confirm the package works with your build output.
  2. Phase 2: Error Integration

    • Extend JavaScript error reporting to include source map URLs (e.g., via Error.stack or custom metadata).
    • Create a Laravel route (e.g., /api/symbolicate) to accept errors and return resolved positions.
    • Example:
      Route::post('/symbolicate', function (Request $request) {
          $error = $request->json()->all();
          $map = SourceMapLookup::fromFile($error['sourceMapUrl']);
          $position = $map->lookup($error['line'], $error['column']);
          return response()->json(['resolved' => $position]);
      });
      
  3. Phase 3: Caching & Scaling

    • Cache parsed SourceMapLookup instances (e.g., in Redis) to avoid reprocessing.
    • Implement bulk deduplication (as shown in the README) for stack traces with repeated maps.
    • Optimization: Pre-parse maps during asset compilation (e.g., in vite.config.js or Laravel Mix).
  4. Phase 4: Scope & UI Enhancements

    • Use scopeAt() to highlight function boundaries in error displays.
    • Integrate sourceLines() to show snippets of original code in error emails/notifications.
    • Example UI:
      Error in `onClick` (src/components/Button.tsx:42)
      Snippet:
        38 |   const handleClick = () => {
        39 |     setCount(c => c + 1);
      > 40 |     analytics.track('button_clicked');
        41 |   };
        42 |   return <button onClick={handleClick}>...
      

Compatibility

  • Source Map Formats: Supports v3 only (most modern bundlers use this). If using v2 or v4, this is a hard incompatibility.
  • Bundler Quirks:
    • Vite: Generates v3 maps by default (compatible).
    • Webpack: May need devtool: 'source-map' in config.
    • Rollup: Uses v3 with sourcemap: true.
  • Edge Cases:
    • Indexed/Sectioned Maps: Throws UnsupportedSourceMap. Workaround: Use a tool like source-map-resolve to flatten maps pre-processing.
    • Malformed Maps: Catches errors via InvalidSourceMap/UnsupportedSourceMap. Log these for debugging.

Sequencing

  1. Frontend Setup

    • Ensure your build process generates source maps (default in Vite/Webpack).
    • Include source map URLs in error payloads (e.g., via Sentry SDK or custom window.onerror).
  2. Backend Integration

    • Add the package to composer.json.
    • Implement the /symbolicate endpoint or middleware.
  3. Error Pipeline

    • Route errors to the symbolicator (e.g., via queue for async processing).
    • Cache resolved positions to avoid reprocessing.
  4. UI/UX Layer

    • Display resolved positions in error dashboards, Slack alerts, or email notifications.
    • Use scopeAt() and sourceLines() for context-rich debugging.

Operational Impact

Maintenance

  • Dependencies: Single Composer package with no runtime dependencies. Updates are trivial (composer update).
  • Error Handling:
    • InvalidSourceMap/UnsupportedSourceMap should be logged but not crash the app.
    • Fallback to raw positions if symbolicating fails.
  • Documentation:
    • Add internal docs for:
      • How to generate source maps in your build process.
      • How to interpret resolved positions (e.g., sourceFileName may be relative).
      • Known limitations (e.g., scopeAt() heuristics).

Support

  • Debugging Workflow:
    • Devs: Can use the package in Tinker or Laravel Debugbar to test mappings interactively.
    • Prod: Errors with resolved positions reduce time-to-diagnosis.
  • **Monitoring
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony