baja/ord/IpScheme.js

/**
 * @copyright 2018 Tridium, Inc. All Rights Reserved.
 * @author Gareth Johnson
 */

/**
 * Defines {@link baja.IpScheme}.
 * @module baja/ord/IpScheme
 */
define([
  "bajaScript/sys",
  "bajaScript/baja/ord/OrdQuery",
  "bajaScript/baja/ord/OrdScheme",
  "bajaScript/baja/ord/OrdTarget",
  "bajaScript/baja/ord/ordUtil" ], function (
    baja,
    OrdQuery,
    OrdScheme,
    OrdTarget,
    ordUtil) {
  
  "use strict";
  
  var subclass = baja.subclass,
      callSuper = baja.callSuper,
      trimToStart = ordUtil.trimToStart;

  /**
   * IP Host ORD Scheme.
   * 
   * This scheme has been added so ORDs can be normalized and relativized
   * correctly.
   *
   * As of 4.9, Workbench interop has been added so that `baja.nav.localhost`
   * will have an `ip:` nav ORD if using BajaScript while connected to a remote
   * station. This is the _only_ IP address that BajaScript can resolve, and it
   * will resolve directly to `baja.nav.localhost`. Other IP addresses will
   * still fail to resolve.
   *
   * @class
   * @alias baja.IpScheme
   * @extends baja.OrdScheme
   * @private
   */    
  var IpScheme = function IpScheme() {
    callSuper(IpScheme, this, arguments);
  };
  
  subclass(IpScheme, OrdScheme);
  
  /**
   * Default IP ORD Scheme instance.
   * @private
   * @type {baja.IpScheme}
   */
  IpScheme.DEFAULT = new IpScheme();
  
  /**
   * Called when an ORD is resolved.
   *
   * @private
   *
   * @see baja.OrdScheme#resolve
   *
   * @param {module:baja/ord/OrdTarget} target  the current ORD Target.
   * @param {baja.OrdQuery} query  the ORD Query used in resolving the ORD.
   * @param {module:baja/ord/OrdQueryListCursor} cursor  the ORD Query List 
   * cursor used for helping to asynchronously resolve the ORD.
   * @param {Object} options  options used for resolving an ORD.
   */
  IpScheme.prototype.resolve = function (target, query, cursor, options) {
    var localOrd = baja.nav.localhost.getNavOrd({ sessionAware: true }).toString();
    if (query.toString() === localOrd) {
      var newTarget = new OrdTarget(target);
      newTarget.object = baja.nav.localhost;
      return cursor.resolveNext(newTarget, options);
    }
    throw new Error('IP ORD scheme unsupported');
  };
  
  /**
   * Return an ORD Query for the scheme.
   *
   * @returns {baja.OrdQuery}
   */
  IpScheme.prototype.parse = function (schemeName, body) {
    return new OrdQuery({
      scheme: this,
      schemeName: schemeName,
      body: body,
      isHost: true,
      isSession: false,
      normalize: trimToStart
    });
  };

  return IpScheme;
});