包详细信息

@scalar/json-magic

scalar205.5kMIT0.6.1

A collection of utilities for working with JSON objects, including diffing, conflict resolution, bundling and more.

自述文件

json-magic

Version Downloads License Discord

A collection of utilities for working with JSON objects, including diffing, conflict resolution, bundling and more.

bundle

Bundle external references in a json object

Quick start

import { bundle } from '@scalar/json-magic/bundle'
import { fetchUrls } from '@scalar/json-magic/bundle/plugins/browser'

const result = await bundle({
 $ref: 'http://example.com/document.json' 
}, {
  plugins: [fetchUrls()],
  treeShake: false,
})

// get the bundled json object
console.log(result)

Plugins

If you are on a browser environment import plugins from @scalar/json-magic/bundle/plugins/browser while if you are on a node environment you can import from @scalar/json-magic/bundle/plugins/node

fetchUrls

This plugins handles all external urls. It works for both node.js and browser environment

import { bundle } from '@scalar/json-magic/bundle'
import { fetchUrls } from '@scalar/json-magic/bundle/plugins/browser'

const document = {
  openapi: '3.1.0',
  info: { title: 'Bundled API', version: '1.0.0' },
  paths: {},
  components: {
    schemas: {
      User: { $ref: 'https://example.com/user-schema.json#' }
    }
  }
}

// This will bundle all external documents and turn all references from external into internal
await bundle(document, {
  plugins: [fetchUrls()],
  treeShake: true  // <------  This flag will try to remove any unused part of the external document
})

console.log(document)
Limiting the number of concurrent requests
await bundle(document, {
  plugins: [
    fetchUrls({
      limit: 10, // it should run at most 10 requests at the same time
    }),
  ],
  treeShake: false
})
Custom headers

To pass custom headers to requests for specific domains you can configure the fetch plugin like the example

await bundle(
  document,
  {
    plugins: [
      fetchUrls({
        // Pass custom headers
        // The header will only be attached to the list of domains
        headers: [
          {
            domains: ['example.com'],
            headers: {
              'Authorization': 'Bearer <TOKEN>'
            }
          }
        ]
      }),
      readFiles(),
    ],
    treeShake: false
  },
)
Custom fetch function

For advanced use cases like proxying requests or implementing custom network logic, you can provide your own fetch implementation. This allows you to handle things like CORS restrictions, custom authentication flows, or request/response transformations.

await bundle(
  document,
  {
    plugins: [
      fetchUrls({
        // Custom fetcher function
        fetch: async (input, init) => {
          console.log('Custom fetch logic')
          return fetch(input, init)
        },
      })
      readFiles(),
    ],
    treeShake: false
  },
)
Bundle from remote url
const result = await bundle(
  'https://example.com/openapi.json',
  {
    plugins: [
      fetchUrls(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
readFiles

This plugins handles local files. Only works on node.js environment

import { bundle } from '@scalar/json-magic/bundle'
import { readFiles } from '@scalar/json-magic/bundle/plugins/node'

const document = {
  openapi: '3.1.0',
  info: { title: 'Bundled API', version: '1.0.0' },
  paths: {},
  components: {
    schemas: {
      User: { $ref: './user-schema.json#' }
    }
  }
}

// This will bundle all external documents and turn all references from external into internal
await bundle(document, {
  plugins: [readFiles()],
  treeShake: false
})

console.log(document)
Bundle from local file

You can pass the file path directly but make sure to have the correct plugins to handle reading from the local files

const result = await bundle(
  './input.json',
  {
    plugins: [
      readFiles(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
parseJson

You can pass raw json string as input

import { bundle } from '@scalar/json-magic/bundle'
import { parseJson } from '@scalar/json-magic/bundle/plugins/browser'

const result = await bundle(
  '{ "openapi": "3.1.1" }',
  {
    plugins: [
      parseJson(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)
parseYaml

You can pass raw yaml string as input

import { bundle } from '@scalar/json-magic/bundle'
import { parseYaml } from '@scalar/json-magic/bundle/plugins/browser'

const result = await bundle(
  'openapi: "3.1.1"\n',
  {
    plugins: [
      parseYaml(),
    ],
    treeShake: false
  },
)

// Bundled document
console.log(result)

Bundler Options

depth

The depth option controls how deeply the bundler will resolve $ref references. When you set depth to a number, the bundler will only follow references up to that level of nesting. This is useful for creating partial bundles or limiting resource usage.

Note: When using depth, the resulting bundle may not be fully self-contained—some nested references deeper than the specified depth may remain unresolved. If you use depth together with the visitedNodes option, be aware that parent nodes may be marked as visited even if their child references have not been fully resolved yet. Use this option with care if you require a complete bundle.

import { bundle } from '@scalar/openapi-parser'
import { fetchUrls } from '@scalar/openapi-parser/plugins-browser'

await bundle(input, {
  plugins: [fetchUrls()],
  treeShake: false,
  depth: 2,
})

dereference

Dereference all $ref pointers in a JSON object, resolving both internal and external references.

The dereference function can operate in two modes:

  • Synchronous (sync: true): Only internal references (within the same object) are resolved. The result is wrapped in a magic proxy for reactive access. No network requests are made.
  • Asynchronous (sync: false or omitted): Both internal and external references (e.g., URLs) are resolved. The function returns a Promise that resolves to the fully dereferenced object, also wrapped in a magic proxy.

Options

  • sync (boolean):
    • If true, resolves only internal references synchronously.
    • If false (default), resolves both internal and external references asynchronously and returns a Promise.

The result is an object with a success property. If dereferencing fails (e.g., due to unresolved external references), the result will include an errors array describing the issues encountered.

import { dereference } from '@scalar/json-magic/dereference'

const result = dereference({ a: 'hello', b: { $ref: '#/a' } }, { sync: true })

// Resolve internal references synchronously
console.log(result)

To resolve also external references you need to set sync: false

import { dereference } from '@scalar/json-magic/dereference'

const result = await dereference({ a: 'hello', b: { $ref: 'http://example.com/document.json#/somepath' } }, { sync: false })

// Result with all internal and external references resolved
console.log(result)

diff

This package provides a way to compare two json objects and get the differences, resolve conflicts and return conflicts that need to be resolved manually.

Quickstart

import { apply, diff, merge } from '@scalar/json-magic/diff'

const baseObject = {
  openapi: '3.0.0',
  info: {
    title: 'Simple API',
    description: 'A small OpenAPI specification example',
    version: '1.0.0',
  },
}

const objectV1 = {
  openapi: '3.0.0',
  info: {
    title: 'Simple API',
    description: 'A small OpenAPI specification example',
    version: '1.0.0',
  },
  change: 'This is a new property',
}

const objectV2 = {
  openapi: '3.0.0',
  info: {
    title: 'Simple API',
    description: 'A small OpenAPI specification example',
    version: '1.0.1',
  },
}

// Merge the changes of both versions with the same parent object
const { diffs, conflicts } = merge(
  diff(baseObject, objectV1),
  diff(baseObject, objectV2),
)

// Apply changes from v1 and v2 to the parent object to get the final object
const finalDocument = apply(baseObject, diffs)

magic-proxy

A javascript proxy which resolves internal references when accessing a property

Quick start

import { createMagicProxy, getRaw } from '@scalar/json-magic/magic-proxy'

const result = createMagicProxy({
  a: 'hello',
  b: {
    $ref: '#/a'
  }
})

/**
 * Output:
 * {
 *  a: 'hello',
 *  b: {
 *    $ref: '#/a',
 *    '$ref-value': 'hello'
 *  }
 * }
 */
console.log(result)

const rawObject = getRaw(result)
/**
 * {
 *  a: 'hello',
 *  b: {
 *    $ref: '#/a'
 *  }
 * }
 */
console.log(rawObject)

更新日志

@scalar/json-magic

0.6.1

Patch Changes

  • 2089748: chore: add logs when fetching unsupported formats
  • 8a7fb2a: fix: schema properties starting with an underscore are hidden
  • Updated dependencies [3f6d0b9]
    • @scalar/helpers@0.0.12

0.6.0

Minor Changes

  • 4951456: feat: merge yaml aliases for in-mem representation

0.5.2

Patch Changes

  • 6462733: fix: comment out flaky test for now

0.5.1

Patch Changes

  • 41d8600: feat: add local ref bundling to bundler

0.5.0

Minor Changes

  • fe46413: feat: support for $id and $anchor

Patch Changes

  • dcf50ef: refactor: move escapeJsonPointer to @scalar/json-magic

0.4.3

Patch Changes

  • Updated dependencies [bff46e5]
    • @scalar/helpers@0.0.11

0.4.2

Patch Changes

  • 3bd1209: fix: do not throw when we set on an invalid ref
  • 1943b99: chore: emit warning when trying to set an invalid ref

0.4.1

Patch Changes

  • Updated dependencies [821717b]
    • @scalar/helpers@0.0.10

0.4.0

Minor Changes

  • 99894bc: feat: correctly validate the schemas

Patch Changes

  • 06a46f0: fix: add proxy cache to fix reactivity issues
  • 63283aa: fix: use hidden properties during validation
  • Updated dependencies [98c55d0]
  • Updated dependencies [0e747c7]
    • @scalar/helpers@0.0.9

0.3.1

Patch Changes

  • 88385b1: fix: external ref linking when starting with a /

0.3.0

Minor Changes

  • b93e1fe: feat(workspace-store): support relative external references
  • c4bf497: fix(workspace-store): correctly propagate documents from one state to the other
  • d8adbed: feat(workspace-store): resolve multi level refs
  • 0c80ef0: feat(json-magic): change the way we resolve refs

Patch Changes

  • 0fcd446: feat(workspace-store): performance improvements
  • Updated dependencies [66b18fc]
    • @scalar/helpers@0.0.8

0.2.0

Minor Changes

  • 0afc40c: feat(json-magic): introduce type-safe apply function with tracked target type in diff results
  • 128af48: feat(workspace-store, json-magic): support externalValue fields on example object

0.1.0

Minor Changes

  • 952bde2: feat(json-magic): move json tooling to the new package