:lipstick: Change comment.

:lipstick: Change comment.

jsoniq version "1.0";

(:
 : Copyright 2012-2015 28msec Inc.
 :)

(:~
 :
This module provides functionality for exporting archives to the XBRL format.

 :
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :)
module namespace xbrl-export = "http://28.io/modules/xbrl/export";

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace networks = "http://28.io/modules/xbrl/networks";
import module namespace labels = "http://28.io/modules/xbrl/labels";
import module namespace references = "http://28.io/modules/xbrl/references";

import module namespace archive = "http://zorba.io/modules/archive";
import module namespace credentials = "http://www.28msec.com/modules/credentials";
import schema namespace mongos = "http://www.28msec.com/modules/mongodb/types";

declare variable $xbrl-export:serialization-parameters :=
    <serialization-parameters xmlns="http://www.w3.org/2010/xslt-xquery-serialization">
      <method value="xml"/>
      <indent value="yes"/>
      <encoding value="UTF-8"/>
    </serialization-parameters>;

declare %private function xbrl-export:comment($options as object?) as comment()
{
  comment { "
    Generated: " || current-dateTime() || " (" || credentials:credentials("MongoDB", "xbrl").db || ")
    "||($options.Comment, "")[1]||"
    Generated by 28msec, Inc.
    http://github.com/28msec/cellstore
  " }
};

declare function xbrl-export:schema(
    $archive as object,
    $options as object?)
as object
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  let $prefixes := distinct-values($components.Concepts[].Name ! (tokenize($$, ":")[1]))[not $$ = ("sec", "xbrl", "xbrl28", "fsa")]
  return {|
    for $concepts as object in $components.Concepts[]
    where [not $concepts.Name = $concepts:BUILT_IN_REPORT_ELEMENTS]
    let $prefix as string* :=  $concepts.Name ! (tokenize($$, ":")[1])
    where not $prefix = ("sec", "xbrl", "xbrl28", "fsa")
    group by $prefix
    let $concepts :=
      for $concept in $concepts
      group by $concept.Name
      return $concept[1]
    let $namespace as string := ($archive.Namespaces.$prefix, "http://28.io/unknown/" || $prefix)[1]
    return { $prefix: [

      xbrl-export:comment($options),

      <schema targetNamespace="{$namespace}"
          elementFormDefault="qualified"
          xmlns="http://www.w3.org/2001/XMLSchema"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:link="http://www.xbrl.org/2003/linkbase"
          xmlns:xbrli="http://www.xbrl.org/2003/instance"
          xmlns:xbrldt="http://xbrl.org/2005/xbrldt"
          xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric">
      {
          for $any-prefix in keys($archive.Namespaces)
          return namespace { $any-prefix } { $archive.Namespaces.$any-prefix },

          for $other-prefix as string in $prefixes
          where $other-prefix ne $prefix
          let $other-namespace as string :=
            ($archive.Namespaces.$other-prefix,
             "http://28.io/unknown/" || $other-prefix)[1]
          return <import namespace="{$other-namespace}"
                         schemaLocation="{$taxonomyName}-{$other-prefix}.xsd"/>,

          <import
              namespace="http://www.xbrl.org/2003/instance"
              schemaLocation="http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd"/>,
          <import
              namespace="http://xbrl.org/2005/xbrldt"
              schemaLocation="http://www.xbrl.org/2005/xbrldt-2005.xsd" />,
          <import
              namespace="http://www.xbrl.org/dtr/type/non-numeric"
              schemaLocation="http://www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd" />,
          <import
              namespace="http://www.xbrl.org/2006/ref"
              schemaLocation="http://www.xbrl.org/2006/ref-2006-02-27.xsd"/>,

          if(count($prefixes) le 1)
          then
            components:to-xbrl-annotation($components, $taxonomyName)
          else
            (),

          for $concept as element() in concepts:to-xbrl($concepts)
          group by $name := $concept/@name
          return $concept[1]
      }
      </schema>

    ] },
    { "entry-point": [

      xbrl-export:comment($options),

      <schema targetNamespace="http://28.io/xbrl/entry-point"
          elementFormDefault="qualified"
          xmlns="http://www.w3.org/2001/XMLSchema"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:link="http://www.xbrl.org/2003/linkbase"
          xmlns:xbrli="http://www.xbrl.org/2003/instance"
          xmlns:xbrldt="http://xbrl.org/2005/xbrldt"
          xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric">
      {
          for $prefix as string in $prefixes
          let $namespace as string :=
            ($archive.Namespaces.$prefix,
             "http://28.io/unknown/" || $prefix)[1]
          return <import namespace="{$namespace}"
                         schemaLocation="{$taxonomyName}-{$prefix}.xsd"/>,

          <import
              namespace="http://www.xbrl.org/2003/instance"
              schemaLocation="http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd"/>,
          <import
              namespace="http://xbrl.org/2005/xbrldt"
              schemaLocation="http://www.xbrl.org/2005/xbrldt-2005.xsd" />,
          <import
              namespace="http://www.xbrl.org/dtr/type/non-numeric"
              schemaLocation="http://www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd" />,
          components:to-xbrl-annotation($components, $taxonomyName)
      }
      </schema>

    ] }[count($prefixes) gt 1]
  |}
};

declare function xbrl-export:labels(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      labels:to-xbrl($components.Concepts[], $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:presentation(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      components:to-xbrl-roleRefs($components, $taxonomyName),
      for $component in $components
      let $presentationNetwork as object? := networks:networks-for-components-and-short-names($component, $networks:PRESENTATION_NETWORK)
      where exists($presentationNetwork) and $component.Role ne null
      return networks:to-xbrl($presentationNetwork, $component, $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:calculation(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      components:to-xbrl-roleRefs($components, $taxonomyName),
      for $component in $components
      let $calculationNetwork as object? := networks:networks-for-components-and-short-names($component, $networks:CALCULATION_NETWORK)
      where exists($calculationNetwork) and $component.Role ne null
      return networks:to-xbrl($calculationNetwork, $component, $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:definition(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
      {
        for $ns in keys($archive.Namespaces)
        return namespace { $ns } { $archive.Namespaces.$ns },
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/all" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#all"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/dimension-domain" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-domain"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/domain-member" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#domain-member"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/hypercube-dimension" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#hypercube-dimension"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/notAll" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#notAll"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/dimension-default" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-default"/>,
        components:to-xbrl-roleRefs($components, $taxonomyName),
        for $component in $components
        for $hypercube in values($component.Hypercubes)
        where $component.Role ne null
        return networks:to-xbrl($hypercube, $component, $taxonomyName)
      }
    </linkbase>
  )
};

declare function xbrl-export:archive(
    $archive as item
) as item()*
{
  xbrl-export:archive($archive, {})
};

declare function xbrl-export:archive(
    $archive as item,
    $options as object?)
as item()*
{
  let $archive as object := archives:archives($archive)
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $schemas as object := {|
    let $schemas-by-prefix := xbrl-export:schema($archive, $options)
    for $prefix in keys($schemas-by-prefix)
    let $nodes as node()* := $schemas-by-prefix.$prefix[]
    return { $prefix: serialize($nodes, $xbrl-export:serialization-parameters) }
  |}
  let $labels as string := serialize(xbrl-export:labels($archive, $options), $xbrl-export:serialization-parameters)
  let $presentation as string := serialize(xbrl-export:presentation($archive, $options), $xbrl-export:serialization-parameters)
  let $calculation as string := serialize(xbrl-export:calculation($archive, $options), $xbrl-export:serialization-parameters)
  let $definition as string := serialize(xbrl-export:definition($archive, $options), $xbrl-export:serialization-parameters)
  let $references as string := serialize(xbrl-export:references($archive, $options), $xbrl-export:serialization-parameters)
  let $archive as xs:base64Binary := archive:create(
    (
      { "type" : "directory", "name" : $taxonomyName },
      for $prefix as string in keys($schemas)
      return { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "-" || $prefix || ".xsd" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_lab.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_pre.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_cal.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_def.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_ref.xml" }
    ),
    (
      values($schemas),
      $labels,
      $presentation,
      $calculation,
      $definition,
      $references
    )
  )
  return
    (
      {
        "content-type": "application/zip",
        "serialization":
        {
          "method": "binary"
        },
        "headers": {
          "Pragma": "public",
          "Expires": "0",
          "Cache-Control": "must-revalidate, post-check=0, pre-check=0",
          "Content-Disposition": "attachment; filename='" || $taxonomyName || ".xbrlx';",
          "Content-Transfer-Encoding": "binary"
        }
      },
      $archive
    )
};

declare function xbrl-export:references(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      references:to-xbrl($archive, $components.Concepts[], $taxonomyName)
    }
    </linkbase>
  )
};

jsoniq version "1.0";

(:
 : Copyright 2012-2015 28msec Inc.
 :)

(:~
 :
This module provides functionality for exporting archives to the XBRL format.

 :
 : @author Dennis Knochenwefel
 : @author Ghislain Fourny
 :)
module namespace xbrl-export = "http://28.io/modules/xbrl/export";

import module namespace archives = "http://28.io/modules/xbrl/archives";
import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace components = "http://28.io/modules/xbrl/components";
import module namespace networks = "http://28.io/modules/xbrl/networks";
import module namespace labels = "http://28.io/modules/xbrl/labels";
import module namespace references = "http://28.io/modules/xbrl/references";

import module namespace archive = "http://zorba.io/modules/archive";
import module namespace credentials = "http://www.28msec.com/modules/credentials";
import schema namespace mongos = "http://www.28msec.com/modules/mongodb/types";

declare variable $xbrl-export:serialization-parameters :=
    <serialization-parameters xmlns="http://www.w3.org/2010/xslt-xquery-serialization">
      <method value="xml"/>
      <indent value="yes"/>
      <encoding value="UTF-8"/>
    </serialization-parameters>;

declare %private function xbrl-export:comment($options as object?) as comment()
{
  comment { "
    Generated: " || current-dateTime() || " (" || credentials:credentials("MongoDB", "xbrl").db || ")
    "||($options.Comment, "")[1]||"
    Generated by 28msec (CellStore/28.io)
  " }
};

declare function xbrl-export:schema(
    $archive as object,
    $options as object?)
as object
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  let $prefixes := distinct-values($components.Concepts[].Name ! (tokenize($$, ":")[1]))[not $$ = ("sec", "xbrl", "xbrl28", "fsa")]
  return {|
    for $concepts as object in $components.Concepts[]
    where [not $concepts.Name = $concepts:BUILT_IN_REPORT_ELEMENTS]
    let $prefix as string* :=  $concepts.Name ! (tokenize($$, ":")[1])
    where not $prefix = ("sec", "xbrl", "xbrl28", "fsa")
    group by $prefix
    let $concepts :=
      for $concept in $concepts
      group by $concept.Name
      return $concept[1]
    let $namespace as string := ($archive.Namespaces.$prefix, "http://28.io/unknown/" || $prefix)[1]
    return { $prefix: [

      xbrl-export:comment($options),

      <schema targetNamespace="{$namespace}"
          elementFormDefault="qualified"
          xmlns="http://www.w3.org/2001/XMLSchema"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:link="http://www.xbrl.org/2003/linkbase"
          xmlns:xbrli="http://www.xbrl.org/2003/instance"
          xmlns:xbrldt="http://xbrl.org/2005/xbrldt"
          xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric">
      {
          for $any-prefix in keys($archive.Namespaces)
          return namespace { $any-prefix } { $archive.Namespaces.$any-prefix },

          for $other-prefix as string in $prefixes
          where $other-prefix ne $prefix
          let $other-namespace as string :=
            ($archive.Namespaces.$other-prefix,
             "http://28.io/unknown/" || $other-prefix)[1]
          return <import namespace="{$other-namespace}"
                         schemaLocation="{$taxonomyName}-{$other-prefix}.xsd"/>,

          <import
              namespace="http://www.xbrl.org/2003/instance"
              schemaLocation="http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd"/>,
          <import
              namespace="http://xbrl.org/2005/xbrldt"
              schemaLocation="http://www.xbrl.org/2005/xbrldt-2005.xsd" />,
          <import
              namespace="http://www.xbrl.org/dtr/type/non-numeric"
              schemaLocation="http://www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd" />,
          <import
              namespace="http://www.xbrl.org/2006/ref"
              schemaLocation="http://www.xbrl.org/2006/ref-2006-02-27.xsd"/>,

          if(count($prefixes) le 1)
          then
            components:to-xbrl-annotation($components, $taxonomyName)
          else
            (),

          for $concept as element() in concepts:to-xbrl($concepts)
          group by $name := $concept/@name
          return $concept[1]
      }
      </schema>

    ] },
    { "entry-point": [

      xbrl-export:comment($options),

      <schema targetNamespace="http://28.io/xbrl/entry-point"
          elementFormDefault="qualified"
          xmlns="http://www.w3.org/2001/XMLSchema"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:link="http://www.xbrl.org/2003/linkbase"
          xmlns:xbrli="http://www.xbrl.org/2003/instance"
          xmlns:xbrldt="http://xbrl.org/2005/xbrldt"
          xmlns:nonnum="http://www.xbrl.org/dtr/type/non-numeric">
      {
          for $prefix as string in $prefixes
          let $namespace as string :=
            ($archive.Namespaces.$prefix,
             "http://28.io/unknown/" || $prefix)[1]
          return <import namespace="{$namespace}"
                         schemaLocation="{$taxonomyName}-{$prefix}.xsd"/>,

          <import
              namespace="http://www.xbrl.org/2003/instance"
              schemaLocation="http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd"/>,
          <import
              namespace="http://xbrl.org/2005/xbrldt"
              schemaLocation="http://www.xbrl.org/2005/xbrldt-2005.xsd" />,
          <import
              namespace="http://www.xbrl.org/dtr/type/non-numeric"
              schemaLocation="http://www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd" />,
          components:to-xbrl-annotation($components, $taxonomyName)
      }
      </schema>

    ] }[count($prefixes) gt 1]
  |}
};

declare function xbrl-export:labels(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      labels:to-xbrl($components.Concepts[], $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:presentation(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      components:to-xbrl-roleRefs($components, $taxonomyName),
      for $component in $components
      let $presentationNetwork as object? := networks:networks-for-components-and-short-names($component, $networks:PRESENTATION_NETWORK)
      where exists($presentationNetwork) and $component.Role ne null
      return networks:to-xbrl($presentationNetwork, $component, $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:calculation(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      components:to-xbrl-roleRefs($components, $taxonomyName),
      for $component in $components
      let $calculationNetwork as object? := networks:networks-for-components-and-short-names($component, $networks:CALCULATION_NETWORK)
      where exists($calculationNetwork) and $component.Role ne null
      return networks:to-xbrl($calculationNetwork, $component, $taxonomyName)
    }
    </linkbase>
  )
};

declare function xbrl-export:definition(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
      {
        for $ns in keys($archive.Namespaces)
        return namespace { $ns } { $archive.Namespaces.$ns },
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/all" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#all"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/dimension-domain" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-domain"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/domain-member" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#domain-member"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/hypercube-dimension" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#hypercube-dimension"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/notAll" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#notAll"/>,
        <arcroleRef arcroleURI="http://xbrl.org/int/dim/arcrole/dimension-default" xlink:type="simple" xlink:href="http://www.xbrl.org/2005/xbrldt-2005.xsd#dimension-default"/>,
        components:to-xbrl-roleRefs($components, $taxonomyName),
        for $component in $components
        for $hypercube in values($component.Hypercubes)
        where $component.Role ne null
        return networks:to-xbrl($hypercube, $component, $taxonomyName)
      }
    </linkbase>
  )
};

declare function xbrl-export:archive(
    $archive as item
) as item()*
{
  xbrl-export:archive($archive, {})
};

declare function xbrl-export:archive(
    $archive as item,
    $options as object?)
as item()*
{
  let $archive as object := archives:archives($archive)
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $schemas as object := {|
    let $schemas-by-prefix := xbrl-export:schema($archive, $options)
    for $prefix in keys($schemas-by-prefix)
    let $nodes as node()* := $schemas-by-prefix.$prefix[]
    return { $prefix: serialize($nodes, $xbrl-export:serialization-parameters) }
  |}
  let $labels as string := serialize(xbrl-export:labels($archive, $options), $xbrl-export:serialization-parameters)
  let $presentation as string := serialize(xbrl-export:presentation($archive, $options), $xbrl-export:serialization-parameters)
  let $calculation as string := serialize(xbrl-export:calculation($archive, $options), $xbrl-export:serialization-parameters)
  let $definition as string := serialize(xbrl-export:definition($archive, $options), $xbrl-export:serialization-parameters)
  let $references as string := serialize(xbrl-export:references($archive, $options), $xbrl-export:serialization-parameters)
  let $archive as xs:base64Binary := archive:create(
    (
      { "type" : "directory", "name" : $taxonomyName },
      for $prefix as string in keys($schemas)
      return { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "-" || $prefix || ".xsd" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_lab.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_pre.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_cal.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_def.xml" },
      { "encoding" : "utf-8", "type" : "regular", "name" : $taxonomyName || "/" || $taxonomyName || "_ref.xml" }
    ),
    (
      values($schemas),
      $labels,
      $presentation,
      $calculation,
      $definition,
      $references
    )
  )
  return
    (
      {
        "content-type": "application/zip",
        "serialization":
        {
          "method": "binary"
        },
        "headers": {
          "Pragma": "public",
          "Expires": "0",
          "Cache-Control": "must-revalidate, post-check=0, pre-check=0",
          "Content-Disposition": "attachment; filename='" || $taxonomyName || ".xbrlx';",
          "Content-Transfer-Encoding": "binary"
        }
      },
      $archive
    )
};

declare function xbrl-export:references(
    $archive as object,
    $options as object?)
as node()*
{
  let $taxonomyName as string := ($options.TaxonomyName, string($archive._id))[1]
  let $components as object* := components:components-for-archives($archive)
  return (
    xbrl-export:comment($options),
    <linkbase
        xmlns="http://www.xbrl.org/2003/linkbase"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        xmlns:xbrli="http://www.xbrl.org/2003/instance"
        xsi:schemaLocation="http://www.xbrl.org/2003/linkbase http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd">
    {
      for $ns in keys($archive.Namespaces)
      return namespace { $ns } { $archive.Namespaces.$ns },
      references:to-xbrl($archive, $components.Concepts[], $taxonomyName)
    }
    </linkbase>
  )
};


:lipstick: Adding IDs to company labels.

jsoniq version "1.0";
(:
 : Copyright 2015 28msec Inc.
 :)

(:~
 :
This module provides functionality for retrieving labels.

 :
 : @author Federico Cavalieri, Ghislain Fourny
 :)
module namespace labels = "http://28.io/modules/xbrl/labels";

import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace entities = "http://28.io/modules/xbrl/entities";

declare namespace xbrli = "http://www.xbrl.org/2003/instance";
declare namespace xlink = "http://www.w3.org/1999/xlink";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : A helper variable holding the default language ("en-US")
 :)
declare variable $labels:AMERICAN_ENGLISH as xs:string := "en-US";

(:~
 : The standard label role.
 :)
declare variable $labels:STANDARD_LABEL_ROLE as xs:string :=
    "http://www.xbrl.org/2003/role/label";

(:~
 : The verbose label role.
 :)
declare variable $labels:VERBOSE_LABEL_ROLE as xs:string :=
    "http://www.xbrl.org/2003/role/verboseLabel";

declare variable $labels:standard-concepts as object* :=
(
    {
      Name: "xbrl:Concept",
      Label: "Concept [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Concept [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Konzept [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Concept [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "項目(Concept)"
        }
      ]
    },
    {
      Name: "xbrl:Period",
      Label: "Period [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Période [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Period [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Periode [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "期間(Period)"
        }
      ]
    },
    {
      Name: "xbrl:Entity",
      Label: "Entity [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Entität [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Entité [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Reporting Entity [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "企業名(Entity)"
        }
      ]
    },
    {
      Name: "xbrl28:Archive",
      Label: "Archiv [Achse]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Archive [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Archiv [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Archive [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "ファイル(Archive)"
        }
      ]
    },
    {
      Name: "fsa:FiscalYear",
      Label: "Fiscal Year [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Année fiscale [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerjahr [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計年度(Fiscal Year)"
        }
      ]
    },
    {
      Name: "fsa:FiscalPeriod",
      Label: "Fiscal Period [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計期間(Fiscal Period)"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Fiscal Period [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Période fiscal [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerperiode [Achse]"
        }
      ]
    },
    {
      Name: "fsa:FiscalPeriodType",
      Label: "Fiscal Period Type [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計期間タイプ(Fiscal Period Type)"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Fiscal Period Type [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Type de période fiscale [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerperiodeart [Achse]"
        }
      ]
    }
);

(:~
 :
Retrieves all the labels with the given label role and language in the
 : matching concepts, one label for each concept.

 :
 :
Matching concepts are those which:
 :  - concept name and archive number match a given one;
 :  - component role matches a given one or is the default
 :    component role.
 :

 :
 :
The set of concepts to search in is specified as a parameter.

 :
 :
Language matching can either be exact, if no options are given,
 : or approximated, if at least one of the following options is given:

 :

 :
MatchDown: whether to match a more specific language, e.g.:
 :       "en" will match labels which language is "en" or "en-US".

 :
MatchUp: whether to match a less specific language, e.g.:
 :       "en-US" will match labels which language is "en-US" or "en".

 :
MatchAnyVariant: whether to match a different variant of the same
 :       language, e.g.: "en-US" will match labels which language is "en-US"
 :       or "en-UK".

 :

 :
 : @param $concept-names the concepts names.
 : @param $label-roles the label role.
 : @param $languages the label language.
 : @param $concepts the concepts in which the labels will be
 :                  searched.
 : @param $entities the entities in which entity labels will be searched.
 : @param $options Optional parameters to control language matching.
 :
 : @return the matching labels (one associated with each input concept, as
 : an object).
 :)
declare function labels:labels(
    $concept-names as string*,
    $label-roles as string*,
    $languages as string*,
    $concepts as object*,
    $entities as object*,
    $options as object?
  ) as object
{
  let $concepts := ($labels:standard-concepts, $concepts)
  return {|
    let $normalized-languages as string* := $languages ! labels:normalize-language($$)
    return (
      for $concept as object in $concepts
      where ($concepts:ALL_CONCEPT_NAMES, $concept.$concepts:NAME) = $concept-names
      group by $concept.$concepts:NAME
      let $concept-labels as object* :=
        for $label-role in $label-roles
        return $concept.$concepts:LABELS[][$$.Role = $label-role]
      let $available-languages as string* :=
        distinct-values($concept-labels.Language)
      let $approximate-languages as string* := labels:approximate-languages(
        $available-languages,
        $normalized-languages,
        $options
      )
      let $english-languages as string* := labels:approximate-languages(
        $available-languages,
        "en",
        $options
      )
      let $perfect-matches as object* :=
        $concept-labels[$$.Language = $normalized-languages]
      let $approximate-matches as object* :=
        $concept-labels[$$.Language = $approximate-languages]
      let $english-matches as object* :=
        $concept-labels[$$.Language = $english-languages]
      let $label as string? :=
        ($perfect-matches.Value,
         $approximate-matches.Value,
         $english-matches.Value,
         $concept-labels.Value,
         $concept.Label)[not $$ instance of null][1]
      where exists($label)
      return {
        $concept.Name : $label
      },

      for $concept in $concept-names
      where not (($concepts:ALL_CONCEPT_NAMES, $concepts.$concepts:NAME) = $concept)
      let $label as string* :=
          switch(true)
            case starts-with($concept, "iso4217:")
            return substring($concept, 9)
            case $concept castable as date
            return format-date(date($concept), "[MNn] [D], [Y]", "en", (), ())
            case (every $date in tokenize($concept, "/") satisfies $date castable as date)
            return "From " || string-join(
                     for $date in tokenize($concept, "/")
                     return format-date(date($date), "[MNn] [D], [Y]", "en", (), ()),
                   " to ")
            case contains($concept, " ")
            return
              switch(true)
              case $concept = entities:eid($entities) and $normalized-languages = ("ja")
              return ($entities[entities:eid($$) = $concept].Profiles.SEC.EntityRegistrantName,
                       $entities[entities:eid($$) = $concept].Profiles.FSA.SubmitterName !
                           ($$ || " (" || tokenize($concept, " ")[2] || ")")
                     )[1]
              case $concept = entities:eid($entities)
              return ($entities[entities:eid($$) = $concept].Profiles.SEC.CompanyName !
                          ($$ || " (" || string(integer(tokenize($concept, " ")[2])) || ")"),
                      $entities[entities:eid($$) = $concept].Profiles.FSA.SubmitterNameAlphabetic !
                          ($$ || " (" || tokenize($concept, " ")[2] || ")")
                     )[1]
              default return ()
           default return ()
      where exists($label)
      return {
        $concept : $label
      }
    )
  |}
};

(:~
 :
Retrieves all the labels with the given label role and language for
 : all concepts used in the fact and matching a concept in the list of
 : concepts. Concepts used in a fact include not only those from the
 : 'xbrl:Concept' aspect, but also Members of any custom axis.

 :
 :
Matching concepts are those which:
 :  - concept name matches a given one,
 :  - archive number matches that of a given component,
 :  - component role matches that of a given component or is the default
 :    component role.
 :

 :
 :
The set of concepts to search in is specified as a parameter.

 :
 :
Language matching can either be exact, if no options are given,
 : or approximated, if at least one of the following options is given:

 :

 :
MatchDown: whether to match a more specific language, e.g.:
 :       "en" will match labels which language is "en" or "en-US".

 :
MatchUp: whether to match a less specific language, e.g.:
 :       "en-US" will match labels which language is "en-US" or "en".

 :
MatchAnyVariant: whether to match a different variant of the same
 :       language, e.g.: "en-US" will match labels which language is "en-US"
 :       or "en-UK".

 :

 :
 : @param $facts a sequence of facts.
 : @param $label-role the label role.
 : @param $language the label language.
 : @param $concepts the concepts in which the labels will be
 :                  searched (in the version-7 format).
 : @param $options optional parameters to control language matching.
 :
 : @return an object with matching concepts as keys and labels as values.
 :)
declare function labels:labels-for-facts(
    $facts as object*,
    $label-role as string,
    $language as string,
    $concepts as object*,
    $entities as object*,
    $options as object?
  ) as object?
{
    for $facts in $facts
    group by $archive := $facts."Aspects"."xbrl28:Archive"
    let $concept-names as string* :=
        distinct-values((
          values($facts.Aspects),
          keys($facts.Aspects)
    )[$$ instance of string])
    return
        {|
            labels:labels(
                    $concept-names,
                    $label-role,
                    $language,
                    $concepts,
                    $entities,
                    $options)
        |}
};

(:~
 :
Normalizes the language code. This normalized language code can then
 : be used to find the right labels in the concepts collection.

 :
 : @param $language the language identifier.
 :
 : @return the normalized language.
 :)
declare function labels:normalize-language($language as string) as string
{
  replace(lower-case($language), "_", "-")
};

declare %private function labels:approximate-languages(
    $all-languages as string*,
    $normalized-language as string,
    $options as object?
  ) as string*
{
    if(not $options.MatchDown cast as boolean? eq false)
    then $all-languages[starts-with($$, $normalized-language)]
    else (),
    if(not $options.MatchUp cast as boolean? eq false)
    then $all-languages[starts-with($normalized-language, $$)]
    else (),
    if ((not $options.MatchAnyVariant cast as boolean? eq false) and contains($normalized-language, "-"))
    then
      $all-languages[starts-with($$, substring-before($normalized-language, "-") || "-")]
    else ()
};

(:~
 :
Transforms concept labels into XBRL labelLink.

 :
 : @param $concepts the concepts to transform.
 :
 : @return the labelLink element to be put into a linkbase.
 :)
declare function labels:to-xbrl(
    $concepts as object*,
    $taxonomyName as string) as element()
{
  <link:labelLink xmlns:link="http://www.xbrl.org/2003/linkbase" xlink:type="extended" xlink:role="http://www.xbrl.org/2003/role/link">
  {
    for $concept as object in $concepts
    where not $concept.Name = $concepts:BUILT_IN_REPORT_ELEMENTS
    group by $concept.Name
    let $id as string := replace($concept.Name[1], ":", "_")
    return
      (
        <link:loc xlink:type="locator" xlink:href="{$taxonomyName||"-"||tokenize($concept.Name[1], ":")[1]}.xsd#{$id}" xlink:label="{$id}" />,
        for $label at $pos in $concept.Labels[]
        let $role as string := ($label.Role, "http://www.xbrl.org/2003/role/label")[1]
        let $lang as string := ($label.Language, "de")[1]
        group by $role, $lang
        let $value as string? := ($label.Value)[$$ instance of string][1]
        let $labelID as string := $id || "_label" || $pos[1]
        return (
            <link:label xlink:role="{$role}"
                   xlink:label="{$labelID}"
                   id="{$labelID}"
                   xml:lang="{$lang}"
                   xlink:type="resource">{$value}</link:label>,
            <link:labelArc xlink:type="arc"
                      xlink:arcrole="http://www.xbrl.org/2003/arcrole/concept-label"
                      xlink:from="{$id}"
                      xlink:to="{$labelID}" />
        )
      )
  }</link:labelLink>
};

jsoniq version "1.0";
(:
 : Copyright 2015 28msec Inc.
 :)

(:~
 :
This module provides functionality for retrieving labels.

 :
 : @author Federico Cavalieri, Ghislain Fourny
 :)
module namespace labels = "http://28.io/modules/xbrl/labels";

import module namespace concepts = "http://28.io/modules/xbrl/concepts";
import module namespace entities = "http://28.io/modules/xbrl/entities";

declare namespace xbrli = "http://www.xbrl.org/2003/instance";
declare namespace xlink = "http://www.w3.org/1999/xlink";

declare namespace ver = "http://zorba.io/options/versioning";
declare option ver:module-version "1.0";

(:~
 : A helper variable holding the default language ("en-US")
 :)
declare variable $labels:AMERICAN_ENGLISH as xs:string := "en-US";

(:~
 : The standard label role.
 :)
declare variable $labels:STANDARD_LABEL_ROLE as xs:string :=
    "http://www.xbrl.org/2003/role/label";

(:~
 : The verbose label role.
 :)
declare variable $labels:VERBOSE_LABEL_ROLE as xs:string :=
    "http://www.xbrl.org/2003/role/verboseLabel";

declare variable $labels:standard-concepts as object* :=
(
    {
      Name: "xbrl:Concept",
      Label: "Concept [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Concept [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Konzept [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Concept [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "項目(Concept)"
        }
      ]
    },
    {
      Name: "xbrl:Period",
      Label: "Period [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Période [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Period [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Periode [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "期間(Period)"
        }
      ]
    },
    {
      Name: "xbrl:Entity",
      Label: "Entity [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Entität [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Entité [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Reporting Entity [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "企業名(Entity)"
        }
      ]
    },
    {
      Name: "xbrl28:Archive",
      Label: "Archiv [Achse]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Archive [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Archiv [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Archive [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "ファイル(Archive)"
        }
      ]
    },
    {
      Name: "fsa:FiscalYear",
      Label: "Fiscal Year [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Année fiscale [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerjahr [Achse]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計年度(Fiscal Year)"
        }
      ]
    },
    {
      Name: "fsa:FiscalPeriod",
      Label: "Fiscal Period [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計期間(Fiscal Period)"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Fiscal Period [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Période fiscal [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerperiode [Achse]"
        }
      ]
    },
    {
      Name: "fsa:FiscalPeriodType",
      Label: "Fiscal Period Type [Axis]",
      Kind: "Dimension",
      IsNillable: true,
      IsAbstract: true,
      PeriodType: "duration",
      SubstitutionGroup: "xbrldt:dimensionItem",
      DataType: "nonnum:domainItemType",
      BaseType: "string",
      ClosestSchemaBuiltinType: "xs:string",
      IsTextBlock: false,
      Labels: [
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "ja",
          Value: "会計期間タイプ(Fiscal Period Type)"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "en-us",
          Value: "Fiscal Period Type [Axis]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "fr",
          Value: "Type de période fiscale [Axe]"
        },
        {
          Role: "http://www.xbrl.org/2003/role/label",
          Language: "de",
          Value: "Steuerperiodeart [Achse]"
        }
      ]
    }
);

(:~
 :
Retrieves all the labels with the given label role and language in the
 : matching concepts, one label for each concept.

 :
 :
Matching concepts are those which:
 :  - concept name and archive number match a given one;
 :  - component role matches a given one or is the default
 :    component role.
 :

 :
 :
The set of concepts to search in is specified as a parameter.

 :
 :
Language matching can either be exact, if no options are given,
 : or approximated, if at least one of the following options is given:

 :

 :
MatchDown: whether to match a more specific language, e.g.:
 :       "en" will match labels which language is "en" or "en-US".

 :
MatchUp: whether to match a less specific language, e.g.:
 :       "en-US" will match labels which language is "en-US" or "en".

 :
MatchAnyVariant: whether to match a different variant of the same
 :       language, e.g.: "en-US" will match labels which language is "en-US"
 :       or "en-UK".

 :

 :
 : @param $concept-names the concepts names.
 : @param $label-roles the label role.
 : @param $languages the label language.
 : @param $concepts the concepts in which the labels will be
 :                  searched.
 : @param $entities the entities in which entity labels will be searched.
 : @param $options Optional parameters to control language matching.
 :
 : @return the matching labels (one associated with each input concept, as
 : an object).
 :)
declare function labels:labels(
    $concept-names as string*,
    $label-roles as string*,
    $languages as string*,
    $concepts as object*,
    $entities as object*,
    $options as object?
  ) as object
{
  let $concepts := ($labels:standard-concepts, $concepts)
  return {|
    let $normalized-languages as string* := $languages ! labels:normalize-language($$)
    return (
      for $concept as object in $concepts
      where ($concepts:ALL_CONCEPT_NAMES, $concept.$concepts:NAME) = $concept-names
      group by $concept.$concepts:NAME
      let $concept-labels as object* :=
        for $label-role in $label-roles
        return $concept.$concepts:LABELS[][$$.Role = $label-role]
      let $available-languages as string* :=
        distinct-values($concept-labels.Language)
      let $approximate-languages as string* := labels:approximate-languages(
        $available-languages,
        $normalized-languages,
        $options
      )
      let $english-languages as string* := labels:approximate-languages(
        $available-languages,
        "en",
        $options
      )
      let $perfect-matches as object* :=
        $concept-labels[$$.Language = $normalized-languages]
      let $approximate-matches as object* :=
        $concept-labels[$$.Language = $approximate-languages]
      let $english-matches as object* :=
        $concept-labels[$$.Language = $english-languages]
      let $label as string? :=
        ($perfect-matches.Value,
         $approximate-matches.Value,
         $english-matches.Value,
         $concept-labels.Value,
         $concept.Label)[not $$ instance of null][1]
      where exists($label)
      return {
        $concept.Name : $label
      },

      for $concept in $concept-names
      where not (($concepts:ALL_CONCEPT_NAMES, $concepts.$concepts:NAME) = $concept)
      let $label as string* :=
          switch(true)
            case starts-with($concept, "iso4217:")
            return substring($concept, 9)
            case $concept castable as date
            return format-date(date($concept), "[MNn] [D], [Y]", "en", (), ())
            case (every $date in tokenize($concept, "/") satisfies $date castable as date)
            return "From " || string-join(
                     for $date in tokenize($concept, "/")
                     return format-date(date($date), "[MNn] [D], [Y]", "en", (), ()),
                   " to ")
            case contains($concept, " ")
            return
              switch(true)
              case $concept = entities:eid($entities) and $normalized-languages = ("ja")
              return ($entities[entities:eid($$) = $concept].Profiles.SEC.EntityRegistrantName,
                       $entities[entities:eid($$) = $concept].Profiles.FSA.SubmitterName)[1]
              case $concept = entities:eid($entities)
              return ($entities[entities:eid($$) = $concept].Profiles.SEC.CompanyName,
                       $entities[entities:eid($$) = $concept].Profiles.FSA.SubmitterNameAlphabetic)[1]
              default return ()
           default return ()
      where exists($label)
      return {
        $concept : $label
      }
    )
  |}
};

(:~
 :
Retrieves all the labels with the given label role and language for
 : all concepts used in the fact and matching a concept in the list of
 : concepts. Concepts used in a fact include not only those from the
 : 'xbrl:Concept' aspect, but also Members of any custom axis.

 :
 :
Matching concepts are those which:
 :  - concept name matches a given one,
 :  - archive number matches that of a given component,
 :  - component role matches that of a given component or is the default
 :    component role.
 :

 :
 :
The set of concepts to search in is specified as a parameter.

 :
 :
Language matching can either be exact, if no options are given,
 : or approximated, if at least one of the following options is given:

 :

 :
MatchDown: whether to match a more specific language, e.g.:
 :       "en" will match labels which language is "en" or "en-US".

 :
MatchUp: whether to match a less specific language, e.g.:
 :       "en-US" will match labels which language is "en-US" or "en".

 :
MatchAnyVariant: whether to match a different variant of the same
 :       language, e.g.: "en-US" will match labels which language is "en-US"
 :       or "en-UK".

 :

 :
 : @param $facts a sequence of facts.
 : @param $label-role the label role.
 : @param $language the label language.
 : @param $concepts the concepts in which the labels will be
 :                  searched (in the version-7 format).
 : @param $options optional parameters to control language matching.
 :
 : @return an object with matching concepts as keys and labels as values.
 :)
declare function labels:labels-for-facts(
    $facts as object*,
    $label-role as string,
    $language as string,
    $concepts as object*,
    $entities as object*,
    $options as object?
  ) as object?
{
    for $facts in $facts
    group by $archive := $facts."Aspects"."xbrl28:Archive"
    let $concept-names as string* :=
        distinct-values((
          values($facts.Aspects),
          keys($facts.Aspects)
    )[$$ instance of string])
    return
        {|
            labels:labels(
                    $concept-names,
                    $label-role,
                    $language,
                    $concepts,
                    $entities,
                    $options)
        |}
};

(:~
 :
Normalizes the language code. This normalized language code can then
 : be used to find the right labels in the concepts collection.

 :
 : @param $language the language identifier.
 :
 : @return the normalized language.
 :)
declare function labels:normalize-language($language as string) as string
{
  replace(lower-case($language), "_", "-")
};

declare %private function labels:approximate-languages(
    $all-languages as string*,
    $normalized-language as string,
    $options as object?
  ) as string*
{
    if(not $options.MatchDown cast as boolean? eq false)
    then $all-languages[starts-with($$, $normalized-language)]
    else (),
    if(not $options.MatchUp cast as boolean? eq false)
    then $all-languages[starts-with($normalized-language, $$)]
    else (),
    if ((not $options.MatchAnyVariant cast as boolean? eq false) and contains($normalized-language, "-"))
    then
      $all-languages[starts-with($$, substring-before($normalized-language, "-") || "-")]
    else ()
};

(:~
 :
Transforms concept labels into XBRL labelLink.

 :
 : @param $concepts the concepts to transform.
 :
 : @return the labelLink element to be put into a linkbase.
 :)
declare function labels:to-xbrl(
    $concepts as object*,
    $taxonomyName as string) as element()
{
  <link:labelLink xmlns:link="http://www.xbrl.org/2003/linkbase" xlink:type="extended" xlink:role="http://www.xbrl.org/2003/role/link">
  {
    for $concept as object in $concepts
    where not $concept.Name = $concepts:BUILT_IN_REPORT_ELEMENTS
    group by $concept.Name
    let $id as string := replace($concept.Name[1], ":", "_")
    return
      (
        <link:loc xlink:type="locator" xlink:href="{$taxonomyName||"-"||tokenize($concept.Name[1], ":")[1]}.xsd#{$id}" xlink:label="{$id}" />,
        for $label at $pos in $concept.Labels[]
        let $role as string := ($label.Role, "http://www.xbrl.org/2003/role/label")[1]
        let $lang as string := ($label.Language, "de")[1]
        group by $role, $lang
        let $value as string? := ($label.Value)[$$ instance of string][1]
        let $labelID as string := $id || "_label" || $pos[1]
        return (
            <link:label xlink:role="{$role}"
                   xlink:label="{$labelID}"
                   id="{$labelID}"
                   xml:lang="{$lang}"
                   xlink:type="resource">{$value}</link:label>,
            <link:labelArc xlink:type="arc"
                      xlink:arcrole="http://www.xbrl.org/2003/arcrole/concept-label"
                      xlink:from="{$id}"
                      xlink:to="{$labelID}" />
        )
      )
  }</link:labelLink>
};


switch cloudfoundry/dns-release

switch cloudfoundry/dns-release

include "./concourse/pipeline-helpers";

{
  "jobs": [
    import_repo_release("github.com/dpb587/openvpn-bosh-release"),
    import_repo_release("github.com/dpb587/ssoca-bosh-release"),

    compile_boshio_release("cloudfoundry/bosh"; "ubuntu-trusty"),
    compile_boshio_release("concourse/concourse"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/garden-runc-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/uaa-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry-community/docker-registry-boshrelease"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/syslog-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/bosh-dns-release"; "ubuntu-trusty"),

    {
      "name": "import-cf-deployment",
      "plan": [
        {
          "get": "cf-deployment",
          "trigger": true
        },
        {
          "get": "repo"
        },
        {
          "task": "import-cf-deployment",
          "file": "repo/concourse/tasks/import-cf-deployment/config.yml",
          "params": {
            "git_user_email": "((maintainer_email))",
            "git_user_name": "((maintainer_name))"
          }
        },
        {
          "put": "repo",
          "params": {
            "rebase": true,
            "repository": "repo"
          }
        }
      ]
    },

    {
      "name": "push-app",
      "serial": true,
      "plan": [
        {
          "get": "repo",
          "trigger": true
        },
        {
          "task": "build-app",
          "file": "repo/concourse/tasks/build-app/config.yml"
        },
        {
          "put": "app",
          "params": {
            "manifest": "app/manifest.yml"
          }
        }
      ]
    }
  ],
  "resources": [
    {
      "name": "repo",
      "type": "git",
      "source": {
        "branch": "master",
        "private_key": "((git_private_key))",
        "uri": "git@github.com:dpb587/bosh-compiled-releases.git"
      }
    },
    {
      "name": "release-compiler",
      "type": "git",
      "source": {
        "uri": "https://github.com/dpb587/bosh-release-compiler.git"
      }
    },
    {
      "name": "ubuntu-trusty",
      "type": "metalink-repository",
      "source": {
        "uri": "https://dpb587.github.io/upstream-blob-mirror/repository/bosh.io/stemcell/bosh-warden-boshlite-ubuntu-trusty-go_agent/index.xml"
      }
    },

    repo_release("github.com/dpb587/openvpn-bosh-release"; {"uri": "https://github.com/dpb587/openvpn-bosh-release.git"}),
    repo_release("github.com/dpb587/ssoca-bosh-release"; {"uri": "https://github.com/dpb587/ssoca-bosh-release.git"}),

    boshio_release("cloudfoundry/bosh"),
    boshio_release("concourse/concourse"),
    boshio_release("cloudfoundry/garden-runc-release"),
    boshio_release("cloudfoundry/uaa-release"),
    boshio_release("cloudfoundry-community/docker-registry-boshrelease"),
    boshio_release("cloudfoundry/syslog-release"),
    boshio_release("cloudfoundry/bosh-dns-release"),

    {
      "name": "cf-deployment",
      "type": "git",
      "source": {
        "uri": "https://github.com/cloudfoundry/cf-deployment.git",
        "paths": [
          "operations/use-compiled-releases.yml"
        ]
      }
    },

    {
      "name": "app",
      "type": "cf",
      "source": {
        "api": "((cf_api))",
        "username": "((cf_username))",
        "password": "((cf_password))",
        "organization": "((cf_organization))",
        "space": "((cf_space))"
      }
    }
  ],
  "resource_types": [
    {
      "name": "metalink-repository",
      "type": "docker-image",
      "source": {
        "repository": "dpb587/metalink-repository-resource"
      }
    }
  ]
}

include "./concourse/pipeline-helpers";

{
  "jobs": [
    import_repo_release("github.com/dpb587/openvpn-bosh-release"),
    import_repo_release("github.com/dpb587/ssoca-bosh-release"),

    compile_boshio_release("cloudfoundry/bosh"; "ubuntu-trusty"),
    compile_boshio_release("concourse/concourse"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/garden-runc-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/uaa-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry-community/docker-registry-boshrelease"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/syslog-release"; "ubuntu-trusty"),
    compile_boshio_release("cloudfoundry/dns-release"; "ubuntu-trusty"),

    {
      "name": "import-cf-deployment",
      "plan": [
        {
          "get": "cf-deployment",
          "trigger": true
        },
        {
          "get": "repo"
        },
        {
          "task": "import-cf-deployment",
          "file": "repo/concourse/tasks/import-cf-deployment/config.yml",
          "params": {
            "git_user_email": "((maintainer_email))",
            "git_user_name": "((maintainer_name))"
          }
        },
        {
          "put": "repo",
          "params": {
            "rebase": true,
            "repository": "repo"
          }
        }
      ]
    },

    {
      "name": "push-app",
      "serial": true,
      "plan": [
        {
          "get": "repo",
          "trigger": true
        },
        {
          "task": "build-app",
          "file": "repo/concourse/tasks/build-app/config.yml"
        },
        {
          "put": "app",
          "params": {
            "manifest": "app/manifest.yml"
          }
        }
      ]
    }
  ],
  "resources": [
    {
      "name": "repo",
      "type": "git",
      "source": {
        "branch": "master",
        "private_key": "((git_private_key))",
        "uri": "git@github.com:dpb587/bosh-compiled-releases.git"
      }
    },
    {
      "name": "release-compiler",
      "type": "git",
      "source": {
        "uri": "https://github.com/dpb587/bosh-release-compiler.git"
      }
    },
    {
      "name": "ubuntu-trusty",
      "type": "metalink-repository",
      "source": {
        "uri": "https://dpb587.github.io/upstream-blob-mirror/repository/bosh.io/stemcell/bosh-warden-boshlite-ubuntu-trusty-go_agent/index.xml"
      }
    },

    repo_release("github.com/dpb587/openvpn-bosh-release"; {"uri": "https://github.com/dpb587/openvpn-bosh-release.git"}),
    repo_release("github.com/dpb587/ssoca-bosh-release"; {"uri": "https://github.com/dpb587/ssoca-bosh-release.git"}),

    boshio_release("cloudfoundry/bosh"),
    boshio_release("concourse/concourse"),
    boshio_release("cloudfoundry/garden-runc-release"),
    boshio_release("cloudfoundry/uaa-release"),
    boshio_release("cloudfoundry-community/docker-registry-boshrelease"),
    boshio_release("cloudfoundry/syslog-release"),
    boshio_release("cloudfoundry/dns-release"),

    {
      "name": "cf-deployment",
      "type": "git",
      "source": {
        "uri": "https://github.com/cloudfoundry/cf-deployment.git",
        "paths": [
          "operations/use-compiled-releases.yml"
        ]
      }
    },

    {
      "name": "app",
      "type": "cf",
      "source": {
        "api": "((cf_api))",
        "username": "((cf_username))",
        "password": "((cf_password))",
        "organization": "((cf_organization))",
        "space": "((cf_space))"
      }
    }
  ],
  "resource_types": [
    {
      "name": "metalink-repository",
      "type": "docker-image",
      "source": {
        "repository": "dpb587/metalink-repository-resource"
      }
    }
  ]
}


Restored reports export

Restored reports export

jsoniq version "1.0";
module namespace export = "http://apps.28.io/reports-export";

import module namespace random = "http://zorba.io/modules/random";

declare %an:sequential function export:cleanup($report as item) as item*
{
    (: add Ids everywhere :)
    for $object in descendant-objects($report)
    where exists($object.Name) and not(exists($object.Id))
    return
      insert json { "Id": random:uuid() } into $object;;

    export:cleanupImpl($report)
};

declare %private function export:cleanupImpl($report as item) as item*
{
    typeswitch($report)
    case $object as object return {|
        for $key in keys($object)
        return
            switch($key)
            case "Trees"
            case "To" return { $key : [
                (
                    if($object.$key instance of array)
                    then $object.$key[]
                    else values($object.$key)
                ) ! (export:cleanupImpl($$)) ] }
            case "Members" return { $key : [
                            (
                                if($object.$key instance of array)
                                then $object.$key[]
                                else values($object.$key)
                            ) ! (export:cleanupImpl($$)) ] }
            case "children" return ()
            case "expanded" return ()
            case "$$hashKey" return ()
            default return { $key : export:cleanupImpl($object.$key) }
    |}
    case $array as array return [ ($array[]) ! (export:cleanupImpl($$)) ]
    default return $report
};

jsoniq version "1.0";
module namespace export = "http://apps.28.io/reports-export";

import module namespace random = "http://zorba.io/modules/random";

declare %an:nondeterministic function export:cleanup($report as item) as item*
{
    (: add Ids everywhere :)
    copy $report := $report
    modify
    (
      for $object in descendant-objects($report)
      where exists($object.Name) and not(exists($object.Id))
      return
        insert json { "Id": random:uuid() } into $object
    )
    return export:cleanupImpl($report)
};

declare %private function export:cleanupImpl($report as item) as item*
{
    typeswitch($report)
    case $object as object return {|
        for $key in keys($object)
        return
            switch($key)
            case "Trees"
            case "To" return { $key : [
                (
                    if($object.$key instance of array)
                    then $object.$key[]
                    else values($object.$key)
                ) ! (export:cleanupImpl($$)) ] }
            case "Members" return { $key : [
                            (
                                if($object.$key instance of array)
                                then $object.$key[]
                                else values($object.$key)
                            ) ! (export:cleanupImpl($$)) ] }
            case "children" return ()
            case "expanded" return ()
            case "$$hashKey" return ()
            default return { $key : export:cleanupImpl($object.$key) }
    |}
    case $array as array return [ ($array[]) ! (export:cleanupImpl($$)) ]
    default return $report
};