import { getItem } from "@esri/arcgis-rest-portal";
import { failSafe } from "../../utils/fail-safe";
/**
 * Parse a resourceUrl ref and construct the appropriate URL to the resource,
 * including token if needed.
 * Example
 * `$ref: "resourceUrl://0a9c24aea6b642d39f09359d31bb0baf/layout/izxrxg8g4-image-card-1768506539822.png"`
 * returns: `https://qaext.arcgis.com/sharing/rest/content/items/0a9c24aea6b642d39f09359d31bb0baf/resources/layout/izxrxg8g4-image-card-1768506539822.png`
 * @param ref The resource URL reference. resourceUrl://:id/:prefix/:filename
 * @param context The ArcGIS context.
 * @returns The constructed URL to the resource.
 */
export async function resourceUrlResolver(ref, context) {
    var _a, _b;
    // Parse id, prefix, filename from the ref
    const parts = ref.split("/");
    const id = parts[2];
    const prefix = parts[3];
    const filename = parts[4];
    if (!id) {
        throw new Error("resourceUrl resolver: No id provided");
    }
    // Optionally, fetch entity to check access
    // FUTURE: cache the item data to avoid redundant fetches if multiple resources from the same item are requested
    const failSafeGetItem = failSafe(getItem, {});
    const entity = (await failSafeGetItem(id, context.requestOptions));
    const access = entity.access;
    // Get portalUrl and token from context
    const portalUrl = context.sharingApiUrl;
    const token = (_b = (_a = context.hubRequestOptions) === null || _a === void 0 ? void 0 : _a.authentication) === null || _b === void 0 ? void 0 : _b.token;
    let url = `${portalUrl}/content/items/${id}/resources/${prefix}/${filename}`;
    if (access !== "public" && token) {
        url += url.includes("?") ? `&token=${token}` : `?token=${token}`;
    }
    return url;
}
//# sourceMappingURL=resourceUrlResolver.js.map