fhir-package-installer
Version:
A utility module for downloading, indexing, caching, and managing FHIR packages from the FHIR Package Registry and Simplifier
1,289 lines (1,154 loc) • 69.8 kB
JavaScript
import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module";
/******/ var __webpack_modules__ = ({
/***/ 860:
/***/ ((module) => {
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
var __extends;
var __assign;
var __rest;
var __decorate;
var __param;
var __esDecorate;
var __runInitializers;
var __propKey;
var __setFunctionName;
var __metadata;
var __awaiter;
var __generator;
var __exportStar;
var __values;
var __read;
var __spread;
var __spreadArrays;
var __spreadArray;
var __await;
var __asyncGenerator;
var __asyncDelegator;
var __asyncValues;
var __makeTemplateObject;
var __importStar;
var __importDefault;
var __classPrivateFieldGet;
var __classPrivateFieldSet;
var __classPrivateFieldIn;
var __createBinding;
var __addDisposableResource;
var __disposeResources;
var __rewriteRelativeImportExtension;
(function (factory) {
var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
if (typeof define === "function" && define.amd) {
define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
}
else if ( true && typeof module.exports === "object") {
factory(createExporter(root, createExporter(module.exports)));
}
else {
factory(createExporter(root));
}
function createExporter(exports, previous) {
if (exports !== root) {
if (typeof Object.create === "function") {
Object.defineProperty(exports, "__esModule", { value: true });
}
else {
exports.__esModule = true;
}
}
return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
}
})
(function (exporter) {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
__extends = function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
__rest = function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
__decorate = function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
__param = function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
__esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
__runInitializers = function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
__propKey = function (x) {
return typeof x === "symbol" ? x : "".concat(x);
};
__setFunctionName = function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
__metadata = function (metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
};
__awaiter = function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
__generator = function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
__exportStar = function(m, o) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
};
__createBinding = Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
__values = function (o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
__read = function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
/** @deprecated */
__spread = function () {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
};
/** @deprecated */
__spreadArrays = function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
__spreadArray = function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
__await = function (v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
};
__asyncGenerator = function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
__asyncDelegator = function (o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
};
__asyncValues = function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
__makeTemplateObject = function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
var __setModuleDefault = Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
};
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
__importStar = function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
__importDefault = function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
__classPrivateFieldGet = function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
__classPrivateFieldSet = function (receiver, state, value, kind, f) {
if (kind === "m") throw new TypeError("Private method is not writable");
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
__classPrivateFieldIn = function (state, receiver) {
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
return typeof state === "function" ? receiver === state : state.has(receiver);
};
__addDisposableResource = function (env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
};
var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
__disposeResources = function (env) {
function fail(e) {
env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
__rewriteRelativeImportExtension = function (path, preserveJsx) {
if (typeof path === "string" && /^\.\.?\//.test(path)) {
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
});
}
return path;
};
exporter("__extends", __extends);
exporter("__assign", __assign);
exporter("__rest", __rest);
exporter("__decorate", __decorate);
exporter("__param", __param);
exporter("__esDecorate", __esDecorate);
exporter("__runInitializers", __runInitializers);
exporter("__propKey", __propKey);
exporter("__setFunctionName", __setFunctionName);
exporter("__metadata", __metadata);
exporter("__awaiter", __awaiter);
exporter("__generator", __generator);
exporter("__exportStar", __exportStar);
exporter("__createBinding", __createBinding);
exporter("__values", __values);
exporter("__read", __read);
exporter("__spread", __spread);
exporter("__spreadArrays", __spreadArrays);
exporter("__spreadArray", __spreadArray);
exporter("__await", __await);
exporter("__asyncGenerator", __asyncGenerator);
exporter("__asyncDelegator", __asyncDelegator);
exporter("__asyncValues", __asyncValues);
exporter("__makeTemplateObject", __makeTemplateObject);
exporter("__importStar", __importStar);
exporter("__importDefault", __importDefault);
exporter("__classPrivateFieldGet", __classPrivateFieldGet);
exporter("__classPrivateFieldSet", __classPrivateFieldSet);
exporter("__classPrivateFieldIn", __classPrivateFieldIn);
exporter("__addDisposableResource", __addDisposableResource);
exporter("__disposeResources", __disposeResources);
exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
});
0 && (0);
/***/ }),
/***/ 955:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs-extra");
/***/ }),
/***/ 611:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
/***/ }),
/***/ 692:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
/***/ }),
/***/ 857:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
/***/ }),
/***/ 928:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
/***/ }),
/***/ 786:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/promises");
/***/ }),
/***/ 101:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tar-stream");
/***/ }),
/***/ 609:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("temp");
/***/ }),
/***/ 106:
/***/ ((module) => {
module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
/***/ }),
/***/ 370:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => {
// ESM COMPAT FLAG
__nccwpck_require__.r(__webpack_exports__);
// EXPORTS
__nccwpck_require__.d(__webpack_exports__, {
"default": () => (/* binding */ pLimit),
limitFunction: () => (/* binding */ limitFunction)
});
;// CONCATENATED MODULE: ./node_modules/yocto-queue/index.js
/*
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
peek() {
if (!this.#head) {
return;
}
return this.#head.value;
// TODO: Node.js 18.
// return this.#head?.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
* drain() {
while (this.#head) {
yield this.dequeue();
}
}
}
;// CONCATENATED MODULE: ./node_modules/p-limit/index.js
function pLimit(concurrency) {
validateConcurrency(concurrency);
const queue = new Queue();
let activeCount = 0;
const resumeNext = () => {
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
// Since `pendingCount` has been decreased by one, increase `activeCount` by one.
activeCount++;
}
};
const next = () => {
activeCount--;
resumeNext();
};
const run = async (function_, resolve, arguments_) => {
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
next();
};
const enqueue = (function_, resolve, arguments_) => {
// Queue `internalResolve` instead of the `run` function
// to preserve asynchronous context.
new Promise(internalResolve => {
queue.enqueue(internalResolve);
}).then(
run.bind(undefined, function_, resolve, arguments_),
);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// after the `internalResolve` function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < concurrency) {
resumeNext();
}
})();
};
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount,
},
pendingCount: {
get: () => queue.size,
},
clearQueue: {
value() {
queue.clear();
},
},
concurrency: {
get: () => concurrency,
set(newConcurrency) {
validateConcurrency(newConcurrency);
concurrency = newConcurrency;
queueMicrotask(() => {
// eslint-disable-next-line no-unmodified-loop-condition
while (activeCount < concurrency && queue.size > 0) {
resumeNext();
}
});
},
},
});
return generator;
}
function limitFunction(function_, option) {
const {concurrency} = option;
const limit = pLimit(concurrency);
return (...arguments_) => limit(() => function_(...arguments_));
}
function validateConcurrency(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
}
/***/ }),
/***/ 287:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __nccwpck_require__) => {
__nccwpck_require__.r(__webpack_exports__);
/* harmony export */ __nccwpck_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ shallowParse)
/* harmony export */ });
/* eslint-disable no-useless-escape */
/**
* © Copyright Outburn Ltd. 2022-2025 All Rights Reserved
* Project name: FHIR-Package-Installer
*/
/**
* A shallow parser for JSON objects.
* This function parses a JSON object string and returns a JavaScript object with only top-level primitive values.
* All nested objects and arrays are ignored.
* @param {string} input
* @returns Object
* @throws {TypeError} If the input is not a JSON object string.
*/
function shallowParse(input) {
if (typeof input !== 'string') {
throw new TypeError('Input must be a string');
}
input = input.trim();
if (!input.startsWith('{') || !input.endsWith('}')) {
throw new SyntaxError('Input must be a JSON object');
}
const result = {};
let i = 1; // skip '{'
const len = input.length;
while (i < len - 1) {
// Skip whitespace
while (/\s/.test(input[i])) i++;
if (input[i] === '}') break; // end of object
if (input[i] !== '"') throw new SyntaxError(`Expected key string at position ${i}`);
// Parse key
let key = '';
i++; // skip opening quote
while (i < len) {
if (input[i] === '"') {
let backslashes = 0;
let j = i - 1;
while (j >= 0 && input[j] === '\\') {
backslashes++;
j--;
}
if (backslashes % 2 === 0) break; // even number of backslashes = not escaped
}
key += input[i++];
}
i++; // skip closing quote
// Skip whitespace and colon
while (/\s/.test(input[i])) i++;
if (input[i] !== ':') throw new SyntaxError(`Expected ':' after key at position ${i}`);
i++; // skip ':'
while (/\s/.test(input[i])) i++;
// Parse value (only primitives allowed)
let value;
if (input[i] === '"') {
// String value: grab the raw quoted string including escapes
const start = i;
i++; // skip opening quote
while (i < len) {
if (input[i] === '"') {
let backslashes = 0;
let j = i - 1;
while (j >= 0 && input[j] === '\\') {
backslashes++;
j--;
}
if (backslashes % 2 === 0) break; // even number of backslashes = not escaped
}
i++;
}
i++; // skip closing quote
const rawString = input.slice(start, i); // includes quotes
value = JSON.parse(rawString); // safely handles all escape sequences
} else if (/[\d\-]/.test(input[i])) {
// Number
let numStr = '';
while (i < len && /[\dEe\+\-\.]/.test(input[i])) {
numStr += input[i++];
}
value = Number(numStr);
} else if (input.startsWith('true', i)) {
value = true;
i += 4;
} else if (input.startsWith('false', i)) {
value = false;
i += 5;
} else if (input.startsWith('null', i)) {
value = null;
i += 4;
} else {
// Non-primitive (array/object/invalid) → skip this value entirely
let stack = [];
if (input[i] === '{' || input[i] === '[') {
stack.push(input[i]);
i++;
while (i < len && stack.length > 0) {
if (input[i] === '"') {
// Skip string inside object/array
i++;
while (i < len) {
if (input[i] === '"') {
let backslashes = 0;
let j = i - 1;
while (j >= 0 && input[j] === '\\') {
backslashes++;
j--;
}
if (backslashes % 2 === 0) break;
}
i++;
}
i++; // closing quote
} else if (input[i] === '{' || input[i] === '[') {
stack.push(input[i]);
i++;
} else if (input[i] === '}' && stack[stack.length - 1] === '{') {
stack.pop();
i++;
} else if (input[i] === ']' && stack[stack.length - 1] === '[') {
stack.pop();
i++;
} else {
i++;
}
}
} else {
// Unknown token, skip until next comma or closing brace
while (i < len && input[i] !== ',' && input[i] !== '}') i++;
}
value = undefined;
}
if (value !== undefined) {
result[key] = value;
}
// Skip whitespace and comma
while (/\s/.test(input[i])) i++;
if (input[i] === ',') i++;
}
return result;
}
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __nccwpck_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __nccwpck_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* © Copyright Outburn Ltd. 2022-2025 All Rights Reserved
* Project name: FHIR-Package-Installer
*/
Object.defineProperty(exports, "BJ", ({ value: true }));
exports.aM = void 0;
const tslib_1 = __nccwpck_require__(860);
const https_1 = tslib_1.__importDefault(__nccwpck_require__(692));
const http_1 = tslib_1.__importDefault(__nccwpck_require__(611));
const fs_extra_1 = tslib_1.__importDefault(__nccwpck_require__(955));
const p_limit_1 = tslib_1.__importDefault(__nccwpck_require__(370));
const path_1 = tslib_1.__importDefault(__nccwpck_require__(928));
const promises_1 = __nccwpck_require__(786);
const tar = tslib_1.__importStar(__nccwpck_require__(101));
const zlib = tslib_1.__importStar(__nccwpck_require__(106));
const temp_1 = tslib_1.__importDefault(__nccwpck_require__(609));
const os_1 = tslib_1.__importDefault(__nccwpck_require__(857));
const shallowParse_1 = tslib_1.__importDefault(__nccwpck_require__(287));
temp_1.default.track();
/**
* default logger uses global console methods
*/
const defaultLogger = {
info: (msg) => console.log(msg),
warn: (msg) => console.warn(msg),
error: (msg) => console.error(msg)
};
/**
* Default prethrow function does nothing since the regular throw prints to console.log, which is the default logger
*/
const prethrow = (msg) => {
if (msg instanceof Error) {
return msg;
}
const error = new Error(msg);
return error;
};
/**
* Max number of concurrent file operations (read / write))
*/
const limit = (0, p_limit_1.default)(Math.max(4, os_1.default.cpus().length));
/**
* Generates an index entry for the package resource
* @param filename resource filename
* @param content resource content
* @returns FileInPackageIndex object
*/
const extractResourceIndexEntry = (filename, content) => {
const evalAttribute = (att) => (typeof att === 'string' ? att : undefined);
const indexEntry = {
filename,
resourceType: content.resourceType,
id: content.id,
url: evalAttribute(content.url),
name: evalAttribute(content.name),
version: evalAttribute(content.version),
kind: evalAttribute(content.kind),
type: evalAttribute(content.type),
supplements: evalAttribute(content.supplements),
content: evalAttribute(content.content),
baseDefinition: evalAttribute(content.baseDefinition),
derivation: evalAttribute(content.derivation),
date: evalAttribute(content.date)
};
return indexEntry;
};
class FhirPackageInstaller {
logger = defaultLogger;
registryUrl = 'https://packages.fhir.org';
registryToken; // optional token for private registries
fallbackUrlBase = 'https://packages.simplifier.net';
/**
* Path to the FHIR package cache directory.
* This directory is used to store downloaded and extracted FHIR packages.
* If the directory does not exist, it will be created.
*/
cachePath = path_1.default.join(os_1.default.homedir(), '.fhir', 'packages');
skipExamples = false; // skip dependency installation of example packages
allowHttp = false; // allow HTTP URLs for testing
prethrow = prethrow;
constructor(config) {
const { logger, registryUrl, registryToken, cachePath, skipExamples, allowHttp } = config || {};
if (registryUrl) {
this.registryUrl = registryUrl;
}
if (registryToken) {
this.registryToken = registryToken;
}
if (cachePath) {
this.cachePath = cachePath;
}
if (allowHttp) {
this.allowHttp = allowHttp;
}
if (logger) {
this.logger = logger;
this.prethrow = (msg) => {
if (!(msg instanceof Error)) {
msg = new Error(msg);
}
this.logger.error(msg.message);
this.logger.error(JSON.stringify(msg, null, 2));
return msg;
};
}
;
if (skipExamples) {
this.skipExamples = skipExamples;
}
if (!fs_extra_1.default.existsSync(this.cachePath)) {
fs_extra_1.default.mkdirSync(this.cachePath, { recursive: true });
this.logger.info(`Directory '${this.cachePath}' created successfully.`);
}
}
async withRetries(fn, retries = 3, delayMs = 5000) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await fn();
}
catch (err) {
lastError = err;
const isTemporary = err.code === 'EAI_AGAIN' || err.code === 'ENOTFOUND' || err.code === 'ECONNRESET';
if (!isTemporary || attempt === retries) {
throw err;
}
this.logger.warn(`⚠️ Attempt ${attempt} failed (${err.code || err.message}), retrying in ${delayMs}ms...`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
throw lastError;
}
/**
* Takes a PackageIdentifier Object and returns the corresponding directory name of the package
* @param packageObject A PackageObject with both name and version keys
* @returns (string) Directory name in the standard format `name#version`
*/
async toDirName(packageId) {
packageId = typeof packageId === 'string' ? await this.toPackageObject(packageId) : packageId;
return packageId.id + '#' + packageId.version;
}
/**
* Takes a PackageIdentifier Object and returns the path to the package folder in the cache
* @param packageObject A PackageIdentifier Object with both name and version keys
* @returns The full path to the package directory
*/
async getPackageDirPath(packageId) {
try {
return path_1.default.join(this.cachePath, await this.toDirName(packageId));
}
catch (e) {
throw this.prethrow(e);
}
}
/**
* Get the full path to the .fpi.index.json file in the package folder
* @param packageObject A PackageIdentifier Object with both name and version keys
* @returns (string) The path to the package index file
*/
async getPackageIndexPath(packageId) {
return path_1.default.join(await this.getPackageDirPath(packageId), 'package', '.fpi.index.json');
}
/**
* Scans a package folder and generates a new `.fpi.index.json` file
* @param packageObject The package identifier object
* @returns PackageIndex
*/
async generatePackageIndex(packageId) {
const pckIdObj = typeof packageId === 'string' ? await this.toPackageObject(packageId) : packageId;
this.logger.info(`Generating new .fpi.index.json file for package ${pckIdObj.id}@${pckIdObj.version}...`);
const packagePath = await this.getPackageDirPath(pckIdObj);
const indexPath = await this.getPackageIndexPath(pckIdObj);
try {
const fileList = await fs_extra_1.default.readdir(path_1.default.join(packagePath, 'package'));
const files = await Promise.all(fileList.filter(file => file.endsWith('.json') && file !== 'package.json' && !file.endsWith('.index.json')).map(file => limit(async () => {
const content = (0, shallowParse_1.default)(await fs_extra_1.default.readFile(path_1.default.join(packagePath, 'package', file), { encoding: 'utf8' }));
const indexEntry = extractResourceIndexEntry(file, content);
return indexEntry;
})));
const indexJson = {
'index-version': 2,
files
};
await fs_extra_1.default.writeJSON(indexPath, indexJson);
return indexJson;
}
catch (e) {
this.logger.error(e);
throw e;
}
}
/**
* Generates HTTP options including authorization header for registry requests
* @param url The URL being requested
* @returns HTTP options object with headers if needed
*/
getHttpOptions(url) {
const options = {};
// Add authorization header for requests to the configured registry
// or any URL that contains the same hostname (to handle redirects within the same registry)
if (this.registryToken) {
const registryHostname = new URL(this.registryUrl).hostname;
const urlHostname = new URL(url).hostname;
if (url.startsWith(this.registryUrl) || urlHostname === registryHostname) {
options.headers = {
'Authorization': `Bearer ${this.registryToken}`
};
}
}
return options;
}
fetchJson(url, redirectCount = 0) {
const maxRedirects = 5;
return this.withRetries(() => new Promise((resolve, reject) => {
const options = this.getHttpOptions(url);
const isHttps = url.startsWith('https:');
const isHttp = url.startsWith('http:');
// Check if HTTP is allowed for testing
if (isHttp && !this.allowHttp) {
reject(new Error('HTTP URLs not allowed. Use HTTPS or enable allowHttp for testing.'));
return;
}
const client = isHttps ? https_1.default : http_1.default;
client.get(url, options, (res) => {
// Handle redirects (301, 302, 303, 307, 308)
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
if (redirectCount >= maxRedirects) {
reject(new Error(`Too many redirects (${maxRedirects}) when fetching ${url}`));
return;
}
const redirectTarget = res.headers.location;
const displayUrl = redirectTarget.length > 64
? `${redirectTarget.substring(0, 64)}...`
: redirectTarget;
this.logger.info(`Following redirect from ${url} to ${displayUrl}`);
// Recursively follow the redirect
this.fetchJson(res.headers.location, redirectCount + 1)
.then(resolve)
.catch(reject);
return;
}
let data = '';
res.on('data', (chunk) => (data += chunk));
res.on('end', () => {
// Check for HTTP error status codes
if (res.statusCode && res.statusCode >= 400) {
try {
const errorData = JSON.parse(data);
const errorMsg = errorData.error || errorData.message || data;
// Convert authentication/authorization errors to "not found" for consistency
if (res.statusCode === 403 || res.statusCode === 401) {
reject(new Error('Package not found in the registry (authentication failed)'));
}
else {
reject(new Error(`HTTP ${res.statusCode}: ${errorMsg}`));
}
}
catch {
if (res.statusCode === 403 || res.statusCode === 401) {
reject(new Error('Package not found in the registry (authentication failed)'));
}
else {
reject(new Error(`HTTP ${res.statusCode}: ${data || 'Unknown error'}`));
}
}
return;
}
try {
resolve(JSON.parse(data));
}
catch (e) {
reject(new Error(`Failed to parse JSON from ${url}: ${e}`));
}
});
}).on('error', reject);
}));
}
fetchStream(url, redirectCount = 0) {
const maxRedirects = 5;
try {
return this.withRetries(() => new Promise((resolve, reject) => {
const options = this.getHttpOptions(url);
const isHttps = url.startsWith('https:');
const isHttp = url.startsWith('http:');
// Check if HTTP is allowed for testing
if (isHttp && !this.allowHttp) {
reject(new Error('HTTP URLs not allowed. Use HTTPS or enable allowHttp for testing.'));
return;
}
const client = isHttps ? https_1.default : http_1.default;
client.get(url, options, (res) => {
// Handle redirects (301, 302, 303, 307, 308)
if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
if (redirectCount >= maxRedirects) {
reject(new Error(`Too many redirects (${maxRedirects}) when fetching ${url}`));
return;
}
const redirectTarget = res.headers.location;
const displayUrl = redirectTarget.length > 64
? `${redirectTarget.substring(0, 64)}...`
: redirectTarget;
this.logger.info(`Following redirect from ${url} to ${displayUrl}`);
// Recursively follow the redirect
this.fetchStream(res.headers.location, redirectCount + 1)
.then(resolve)
.catch(reject);
return;
}
if (res.statusCode === 200) {
resolve(res);
}
else {
reject(new Error(`Failed to fetch ${url} (status ${res.statusCode})`));
}
}).on('error', reject);
}));
}
catch (e) {
this.logger.error(`Failed to fetch stream from ${url}`);
throw e;
}
}
async getPackageDataFromRegistry(packageName) {