import t from"@arcgis/core/portal/Portal";import r from"@arcgis/core/portal/PortalItem";import{ArgumentError as e}from"../ArgumentError.js";import{isPortalUri as o,PortalUri as i}from"../PortalUri.js";import{config as n}from"../config.js";import{isPortalItem as s}from"./esri.js";import{Uri as a}from"./uri.js";import{generateUuid as l}from"./uuid.js";export function isPortalItemId(t){return/^[a-fA-F0-9]{32}$/.test(t)}export function getPortalItemHtmlUrl(t){const r=toPortalItem(t);if(r.portal?.url&&r.id){const t=new a("home/item.html");return t.queryValues.set("id",r.id),t.toAbsoluteUri(`${r.portal.url}/`).toString()}}export function isPortalItemUrl(t){return"string"==typeof t?o(t)||isPortalItemUrl(new a(t)):!!t&&(u.test(t.path)||!!t.path?.endsWith("/home/item.html")&&t.queryValues.has("id")&&isPortalItemId(t.queryValues.get("id")))}export function isPortalItemLike(t){if(s(t)||t instanceof i)return!0;if(t instanceof a){const r=t.toString();return isPortalItemUrl(r)||o(r)}return"string"==typeof t?isPortalItemId(t)||o(t)||isPortalItemUrl(t):!(!t||null==t.id)&&isPortalItemId(t.id)}export function toPortalItem(n){if(n instanceof r)return n;if(n instanceof i)return n.toPortalItem();if(n instanceof a)return p(n);if("string"==typeof n){if(isPortalItemId(n))return new r({id:n});if(o(n))return new i(n).toPortalItem();if(isPortalItemUrl(n))return p(new a(n));throw new e("input",`Unable to convert "${n}" to a Portal item. Make sure it is a valid Portal item ID or URL.`)}if("object"==typeof n){const e=r.fromJSON(n);return e.id=n.id,e.portal=t.getDefault(),e}throw new e("toPortalItem(): invalid input type.")}export function serializePortalItem(t){if(s(t)){if(t.itemUrl)return m(t.itemUrl);if(t.portal){const r=new a("/sharing/rest/content/items/");return r.queryValues.set("id",t.id),m(r.toAbsoluteUri(t.portal.url))}return t.id}return t instanceof i?t.toString():t instanceof a||"string"==typeof t?m(t):t}function m(t){const r="string"==typeof t?new a(t):t;return r.host.toLowerCase().endsWith(".maps.arcgis.com")&&(r.host="www.arcgis.com"),r.toString()}const u=/\/sharing\/rest\/content\/items\/([a-fA-F0-9]{32}).*/,f=/\/home\/item\.html$/;function p(o){const i=new a;let s;const m=o.path.match(u);if(m)i.path=o.path.replace(u,""),s=m[1];else{if(!(o.path?.endsWith("/home/item.html")&&o.queryValues.has("id")&&isPortalItemId(o.queryValues.get("id"))))throw new e("itemUrl",`Invalid Portal item URL "${o.toString()}".`);i.path=o.path.replace(f,""),s=o.queryValues.get("id")}i.scheme=o.scheme,i.host=o.host,i.port=o.port;const p=i.toString(),c=new r({id:s});if(p===t.getDefault().url)c.portal=t.getDefault();else{let r=[...n.portals.values()].find((t=>t.url===p));r||(r=new t({id:l(),url:p}),n.portals.set(r.id,r)),c.portal=r}return c}