@powerhousedao/reactor-browser 6.2.3-dev.71 → 6.2.3-dev.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{attachment-service-CAf9N-15.d.ts → attachment-service-0L7kHOC-.d.ts} +23 -4
  2. package/dist/attachment-service-0L7kHOC-.d.ts.map +1 -0
  3. package/dist/{dispatch-Dd_WEz35.js → dispatch-COa-7Cnf.js} +134 -4
  4. package/dist/dispatch-COa-7Cnf.js.map +1 -0
  5. package/dist/{document-by-id-DqAyjr9P.js → document-by-id-1mRv91Zu.js} +2 -2
  6. package/dist/{document-by-id-DqAyjr9P.js.map → document-by-id-1mRv91Zu.js.map} +1 -1
  7. package/dist/{document-model-modules-DROQT_yu.js → document-model-modules-BN6ps-J2.js} +2 -2
  8. package/dist/{document-model-modules-DROQT_yu.js.map → document-model-modules-BN6ps-J2.js.map} +1 -1
  9. package/dist/{document-operations-C6khz2If.js → document-operations-BY6lqh4g.js} +65 -9
  10. package/dist/document-operations-BY6lqh4g.js.map +1 -0
  11. package/dist/{global-D-VZTZRz.d.ts → global-DgCDUQH2.d.ts} +32 -6
  12. package/dist/global-DgCDUQH2.d.ts.map +1 -0
  13. package/dist/{index-XfcUiODQ.d.ts → index-Dfr257W2.d.ts} +2 -2
  14. package/dist/{index-XfcUiODQ.d.ts.map → index-Dfr257W2.d.ts.map} +1 -1
  15. package/dist/index.d.ts +54 -20
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +85 -48
  18. package/dist/index.js.map +1 -1
  19. package/dist/navigation-BqphkrOB.js.map +1 -1
  20. package/dist/src/ai/index.js +2 -2
  21. package/dist/src/analytics/index.js +1 -1
  22. package/dist/src/graphql-client/entry.d.ts +2 -2
  23. package/dist/src/graphql-client/entry.js +3 -3
  24. package/dist/src/renown/index.d.ts +1 -1
  25. package/dist/src/rpc/index.d.ts +44 -10
  26. package/dist/src/rpc/index.d.ts.map +1 -1
  27. package/dist/src/rpc/index.js +199 -35
  28. package/dist/src/rpc/index.js.map +1 -1
  29. package/dist/{switchboard-cwUp3FxP.js → switchboard-BxnVm77m.js} +3 -3
  30. package/dist/{switchboard-cwUp3FxP.js.map → switchboard-BxnVm77m.js.map} +1 -1
  31. package/package.json +10 -9
  32. package/dist/attachment-service-CAf9N-15.d.ts.map +0 -1
  33. package/dist/dispatch-Dd_WEz35.js.map +0 -1
  34. package/dist/document-operations-C6khz2If.js.map +0 -1
  35. package/dist/global-D-VZTZRz.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"navigation-BqphkrOB.js","names":[],"sources":["../src/utils/url.ts","../src/hooks/navigation.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (getPHStore()?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the path without a leading base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = getPHStore()?.basePath ?? \"/\";\n if (!path.startsWith(basePath)) return path;\n const rest = path.slice(basePath.length);\n if (basePath.endsWith(\"/\")) return `/${rest}`;\n return rest === \"\" || rest.startsWith(\"/\") ? rest : path;\n}\n\n/** Makes a URL component for a drive.\n * @deprecated Open drives through the store's `navigation`; it builds the path. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/** A drive's URL component: its slug, else its id, prefixed with the slugged\n * name as `<name>-<id>` when the id is opaque (a UUID or derived id). */\nexport function makeDriveSlug(drive: DocumentDriveDocument) {\n const { id, slug: driveSlug } = drive.header;\n if (driveSlug && driveSlug !== id) return driveSlug;\n return isOpaqueId(id) ? namedDriveSlug(drive) : id;\n}\n\nfunction isOpaqueId(id: string) {\n return findUuid(id) !== undefined || isDerivedDocumentId(id);\n}\n\nfunction namedDriveSlug(drive: DocumentDriveDocument) {\n const name = drive.state.global.name || drive.header.name;\n return namedSlug(drive, name, drive.header.id);\n}\n\nconst namedSlugs = new WeakMap<\n object,\n { name: string; id: string; value: string }\n>();\n\n// `<slugged name>-<id>`, cached per drive or node; inputs are rechecked.\nfunction namedSlug(owner: object, name: string, id: string) {\n const cached = namedSlugs.get(owner);\n if (cached?.name === name && cached.id === id) return cached.value;\n const nameSlug = name ? slug(name) : \"\";\n const value = nameSlug ? `${nameSlug}-${id}` : id;\n namedSlugs.set(owner, { name, id, value });\n return value;\n}\n\n/** The drive a URL slug names: its own slug, its id, or `<name>-<id>`. */\nexport function findDriveBySlug(\n drives: readonly DocumentDriveDocument[] | undefined,\n ref: string | undefined,\n): DocumentDriveDocument | undefined {\n if (!drives || !ref) return undefined;\n const exact = drives.find(\n (d) => d.header.slug === ref || d.header.id === ref,\n );\n if (exact) return exact;\n const id = extractDriveIdFromSlug(ref);\n if (id !== undefined) {\n const byId = drives.find((d) => d.header.id === id);\n if (byId) return byId;\n }\n // `<name>-<id>` also for a readable id, as older links wrote it.\n return drives.find(\n (d) =>\n (!d.header.slug || d.header.slug === d.header.id) &&\n ref.endsWith(d.header.id) &&\n namedDriveSlug(d) === ref,\n );\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined) {\n if (!node) return \"\";\n return namedSlug(node, node.name, node.id);\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\n/** @deprecated Route loaders resolve the node; use `extractNodeIdFromSlug`. */\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\n/** @deprecated Route loaders resolve the drive; use `extractDriveIdFromSlug`. */\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/** Creates a URL string with the given pathname, keeping the query string.\n * @deprecated The store's `navigation` keeps global params across navigations. */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type {\n PHNavigateOptions,\n PHNavigation,\n PHNavigationTarget,\n PHSearchUpdate,\n PHSettingsTarget,\n SearchParamsUpdate,\n} from \"@powerhousedao/reactor-browser\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { resolveUrlPathname } from \"../utils/url.js\";\nimport { getPHStore } from \"./ph-store.js\";\n\nconst isServer = typeof window === \"undefined\";\n\n/** Fired on `window` when the fallback navigator rewrites the URL. */\nexport const PH_LOCATION_CHANGE_EVENT = \"ph:locationchange\";\n\n/** Params read at boot or app-wide; they survive every navigation. Others,\n * e.g. a document's own, are dropped when the target changes. */\nexport const GLOBAL_SEARCH_PARAMS = [\n // A remote drive to add on boot.\n \"driveUrl\",\n // The theme override read by the inline theme boot script.\n \"theme\",\n // Embedded mode, which hides Connect's chrome.\n \"embed\",\n // Log level override for the feature-flag provider.\n \"LOG_LEVEL\",\n // The reactor worker runtime flag override.\n \"reactorWorker\",\n] as const;\n\n/** Feature flags are any `FEATURE_*` param, so they are retained by prefix. */\nexport const FEATURE_FLAG_PARAM_PREFIX = \"FEATURE_\";\n\n/** Whether `key` is a param every navigation keeps. */\nexport function isGlobalSearchParam(key: string) {\n return (\n (GLOBAL_SEARCH_PARAMS as readonly string[]).includes(key) ||\n key.startsWith(FEATURE_FLAG_PARAM_PREFIX)\n );\n}\n\nfunction globalSearch(search: string) {\n return Object.fromEntries(\n Object.entries(searchToRecord(search)).filter(([key]) =>\n isGlobalSearchParam(key),\n ),\n );\n}\n\n/** A query string's params; repeated keys keep their last value. */\nexport function searchToRecord(search: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(search));\n}\n\n/** `prev` with `update` applied; an `undefined` value removes the key. */\nexport function applySearchUpdate(\n prev: Record<string, string>,\n update: PHSearchUpdate,\n): Record<string, string> {\n const next = { ...prev };\n for (const [key, value] of Object.entries(update)) {\n if (value === undefined) delete next[key];\n else next[key] = value;\n }\n return next;\n}\n\n/** `params` as a query string, with an empty value as a bare key: `history`, not `history=`. */\nexport function searchParamsToString(params: URLSearchParams) {\n return params.toString().replace(/=(?=&|$)/g, \"\");\n}\n\n/** `?a=1&b=2`, or an empty string for no params. */\nexport function recordToSearch(record: Record<string, string>) {\n const search = searchParamsToString(new URLSearchParams(record));\n return search ? `?${search}` : \"\";\n}\n\n/** The settings page's path; its tabs are below it. */\nexport const SETTINGS_PATH = \"/settings\";\n\nexport function isSettingsTarget(\n target: PHNavigationTarget | undefined,\n): target is PHSettingsTarget {\n return !!target && \"settings\" in target;\n}\n\n/** The pathname a target opens at, base path included. */\nexport function targetPathname(target: PHNavigationTarget | undefined) {\n if (!target) return resolveUrlPathname(\"/\");\n if (isSettingsTarget(target)) {\n const { settings } = target;\n return resolveUrlPathname(\n settings === true ? SETTINGS_PATH : `${SETTINGS_PATH}/${settings}`,\n );\n }\n const { driveSlug, nodeSlug } = target;\n return resolveUrlPathname(\n nodeSlug ? `/d/${driveSlug}/${nodeSlug}` : `/d/${driveSlug}`,\n );\n}\n\n/** History state key: the index of the entry a document was opened from. */\nexport const OPENED_FROM_STATE_KEY = \"phOpenedFrom\";\n\n// The fallback numbers its own entries; a router's history has its own index.\ntype BrowserEntryState = { phIndex?: number; phOpenedFrom?: number };\n\nfunction browserEntryState(): BrowserEntryState {\n const state: unknown = window.history.state;\n return state && typeof state === \"object\" ? (state as BrowserEntryState) : {};\n}\n\n/** The index to go back to from `index`, when it lies before it. */\nexport function openedFromIndex(\n state: object | undefined,\n index: number,\n): number | undefined {\n const from = (state as Record<string, unknown> | undefined)?.[\n OPENED_FROM_STATE_KEY\n ];\n return typeof from === \"number\" && from >= 0 && from < index\n ? from\n : undefined;\n}\n\n// `openedFrom` \"keep\" carries the current entry's, as an in-document write does.\nfunction writeBrowserUrl(\n href: string,\n replace: boolean | undefined,\n openedFrom: number | \"keep\" | undefined,\n) {\n const prev = browserEntryState();\n const index = prev.phIndex ?? 0;\n const from = openedFrom === \"keep\" ? prev.phOpenedFrom : openedFrom;\n // Keeps the entry's state, e.g. a router's history key, on a replace.\n if (replace) {\n window.history.replaceState(\n { ...prev, phIndex: index, phOpenedFrom: from },\n \"\",\n href,\n );\n } else {\n window.history.pushState(\n { phIndex: index + 1, phOpenedFrom: from },\n \"\",\n href,\n );\n }\n window.dispatchEvent(new Event(PH_LOCATION_CHANGE_EVENT));\n}\n\nfunction subscribeToLocation(onChange: () => void) {\n window.addEventListener(\"popstate\", onChange);\n window.addEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n return () => {\n window.removeEventListener(\"popstate\", onChange);\n window.removeEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n };\n}\n\nconst readSearch = () => window.location.search;\nconst readPathname = () => window.location.pathname;\nconst readServerPathname = () => \"\";\nconst readServerSearch = () => \"\";\n\nfunction setBrowserSearch(\n update: (prev: Record<string, string>) => PHSearchUpdate,\n options?: { replace?: boolean },\n) {\n const prev = searchToRecord(window.location.search);\n const next = recordToSearch(applySearchUpdate({}, update(prev)));\n if (next === recordToSearch(prev)) return;\n // Like a router's search update, this drops the hash.\n writeBrowserUrl(\n `${window.location.pathname}${next}`,\n options?.replace,\n \"keep\",\n );\n}\n\nfunction setBrowserSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n setBrowserSearch((prev) => resolveSearchUpdate(prev, update), options);\n}\n\n/** The fallback without a host: `window.location` and `window.history`. Only\n * the global params carry over to another target, as with a router. */\n// Set by sync-selection.ts, which imports this module: importing it here would be a cycle.\nlet syncSelectionAfterOpen = () => {};\n\n/** @internal Selects what the browser fallback opens; sync-selection.ts sets it. */\nexport function setBrowserOpenSync(sync: () => void) {\n syncSelectionAfterOpen = sync;\n}\n\nexport const browserNavigation: PHNavigation = {\n location: () => window.location,\n hrefFor: (target) =>\n `${targetPathname(target)}${recordToSearch(globalSearch(window.location.search))}`,\n useIsCurrent(target) {\n const pathname = useSyncExternalStore(\n subscribeToLocation,\n readPathname,\n readServerPathname,\n );\n return pathname === targetPathname(target);\n },\n open: (target, options) => {\n const prev = globalSearch(window.location.search);\n const search = options?.search\n ? applySearchUpdate(prev, options.search)\n : prev;\n const entry = browserEntryState();\n writeBrowserUrl(\n `${targetPathname(target)}${recordToSearch(search)}`,\n options?.replace,\n options?.replace ? entry.phOpenedFrom : (entry.phIndex ?? 0),\n );\n // No router selects for it, and pushState fires no popstate.\n syncSelectionAfterOpen();\n },\n closeOpened: () => {\n const entry = browserEntryState();\n const index = entry.phIndex ?? 0;\n const from = openedFromIndex(entry, index);\n if (from === undefined) return false;\n window.history.go(from - index);\n return true;\n },\n setSearch: setBrowserSearch,\n useSearchParams() {\n const search = useSyncExternalStore(\n subscribeToLocation,\n readSearch,\n readServerSearch,\n );\n return useMemo(() => searchToRecord(search), [search]);\n },\n useSetSearchParams: () => setBrowserSearchParams,\n};\n\n/** True when the store has a host navigation, not the browser fallback. */\nexport function hasHostNavigation() {\n return !isServer && getPHStore()?.navigation !== undefined;\n}\n\n/** The app store's navigation, else the browser fallback. */\nexport function getPHNavigation(): PHNavigation {\n return getPHStore()?.navigation ?? browserNavigation;\n}\n\n/** The current pathname as the navigation sees it, base path included. */\nexport function getCurrentPathname() {\n return getPHNavigation().location().pathname;\n}\n\n/** Opens `target`; without `search`, a target already open is left alone. */\nexport function openTarget(\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n openTargetWith(getPHNavigation(), target, options);\n}\n\n/** Opens `target` through `navigation`, unless it is open already. */\nexport function openTargetWith(\n navigation: PHNavigation,\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n const pathname = navigation.location().pathname;\n const targetPath = targetPathname(target);\n // On any tab, the settings page is open.\n const open =\n targetPath === pathname ||\n (isSettingsTarget(target) &&\n target.settings === true &&\n pathname.startsWith(`${targetPath}/`));\n if (!options?.search && open) return;\n navigation.open(target, options);\n}\n\n/** Asks the host navigation to warm `target`; a no-op without one. */\nexport function preloadTarget(target: PHNavigationTarget | undefined) {\n if (!hasHostNavigation()) return;\n getPHNavigation().preload?.(target);\n}\n\n/** The href `target` opens at through `navigation`, base path included. */\nexport function getTargetHref(\n target: PHNavigationTarget | undefined,\n navigation: PHNavigation = getPHNavigation(),\n) {\n return navigation.hrefFor?.(target) ?? targetPathname(target);\n}\n\nexport function resolveSearchUpdate(\n prev: Record<string, string>,\n update: SearchParamsUpdate,\n): Record<string, string> {\n return typeof update === \"function\"\n ? applySearchUpdate({}, update(prev))\n : applySearchUpdate(prev, update);\n}\n\n/** Rewrites the current query params through the app store's navigation. */\nexport function setSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n getPHNavigation().setSearch(\n (prev) => resolveSearchUpdate(prev, update),\n options,\n );\n}\n"],"mappings":";;;;;AASA,MAAM,oBAAoB;AAG1B,SAAgB,mBAAmB,MAAc;CAC/C,OAAO,IAAI,IACT,KAAK,QAAQ,QAAQ,EAAE,GACvB,OAAO,SAAS,UAAU,WAAW,CAAC,EAAE,YAAY,IACtD,CAAC,CAAC;AACJ;;AAGA,SAAgB,mBAAmB,MAAc;CAC/C,MAAM,WAAW,WAAW,CAAC,EAAE,YAAY;CAC3C,IAAI,CAAC,KAAK,WAAW,QAAQ,GAAG,OAAO;CACvC,MAAM,OAAO,KAAK,MAAM,SAAS,MAAM;CACvC,IAAI,SAAS,SAAS,GAAG,GAAG,OAAO,IAAI;CACvC,OAAO,SAAS,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO;AACtD;;;AAIA,SAAgB,sBACd,OACA;CACA,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,MAAM,KAAK,MAAM,OAAO,IAAI;AACrC;;;AAIA,SAAgB,cAAc,OAA8B;CAC1D,MAAM,EAAE,IAAI,MAAM,cAAc,MAAM;CACtC,IAAI,aAAa,cAAc,IAAI,OAAO;CAC1C,OAAO,WAAW,EAAE,IAAI,eAAe,KAAK,IAAI;AAClD;AAEA,SAAS,WAAW,IAAY;CAC9B,OAAO,SAAS,EAAE,MAAM,KAAA,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AAC,kBAAkB,GAAG;CAC1B,gBAAgB,CAAC,CAAC,UAAU,MAAM;AACpC;;AAGA,SAAgB,cACd,QACA,aAA2B,gBAAgB,GAC3C;CACA,OAAO,WAAW,UAAU,MAAM,KAAK,eAAe,MAAM;AAC9D;AAEA,SAAgB,oBACd,MACA,QACwB;CACxB,OAAO,OAAO,WAAW,aACrB,kBAAkB,CAAC,GAAG,OAAO,IAAI,CAAC,IAClC,kBAAkB,MAAM,MAAM;AACpC;;AAGA,SAAgB,gBACd,QACA,SACA;CACA,gBAAgB,CAAC,CAAC,WACf,SAAS,oBAAoB,MAAM,MAAM,GAC1C,OACF;AACF"}
1
+ {"version":3,"file":"navigation-BqphkrOB.js","names":[],"sources":["../src/utils/url.ts","../src/hooks/navigation.ts"],"sourcesContent":["import { getPHStore } from \"../hooks/ph-store.js\";\nimport type {\n DocumentDriveDocument,\n Node,\n} from \"@powerhousedao/shared/document-drive\";\nimport { isDerivedDocumentId } from \"@powerhousedao/shared/document-model\";\nimport slug from \"slug\";\n\n// Length of the base64url id a v2-required document gets.\nconst DERIVED_ID_LENGTH = 43;\n\n// Returns url with base path plus provided path\nexport function resolveUrlPathname(path: string) {\n return new URL(\n path.replace(/^\\/+/, \"\"),\n window.location.origin + (getPHStore()?.basePath ?? \"/\"),\n ).pathname;\n}\n\n/** Returns the path without a leading base path */\nexport function getPathWithoutBase(path: string) {\n const basePath = getPHStore()?.basePath ?? \"/\";\n if (!path.startsWith(basePath)) return path;\n const rest = path.slice(basePath.length);\n if (basePath.endsWith(\"/\")) return `/${rest}`;\n return rest === \"\" || rest.startsWith(\"/\") ? rest : path;\n}\n\n/** Makes a URL component for a drive.\n * @deprecated Open drives through the store's `navigation`; it builds the path. */\nexport function makeDriveUrlComponent(\n drive: DocumentDriveDocument | undefined,\n) {\n if (!drive) return \"\";\n return `/d/${slug(drive.header.slug)}`;\n}\n\n/** A drive's URL component: its slug, else its id, prefixed with the slugged\n * name as `<name>-<id>` when the id is opaque (a UUID or derived id). */\nexport function makeDriveSlug(drive: DocumentDriveDocument): string {\n const { id, slug: driveSlug } = drive.header;\n if (driveSlug && driveSlug !== id) return driveSlug;\n return isOpaqueId(id) ? namedDriveSlug(drive) : id;\n}\n\nfunction isOpaqueId(id: string) {\n return findUuid(id) !== undefined || isDerivedDocumentId(id);\n}\n\nfunction namedDriveSlug(drive: DocumentDriveDocument): string {\n const name = drive.state.global.name || drive.header.name;\n return namedSlug(drive, name, drive.header.id);\n}\n\nconst namedSlugs = new WeakMap<\n object,\n { name: string; id: string; value: string }\n>();\n\n// `<slugged name>-<id>`, cached per drive or node; inputs are rechecked.\nfunction namedSlug(owner: object, name: string, id: string): string {\n const cached = namedSlugs.get(owner);\n if (cached?.name === name && cached.id === id) return cached.value;\n const nameSlug = name ? slug(name) : \"\";\n const value = nameSlug ? `${nameSlug}-${id}` : id;\n namedSlugs.set(owner, { name, id, value });\n return value;\n}\n\n/** The drive a URL slug names: its own slug, its id, or `<name>-<id>`. */\nexport function findDriveBySlug(\n drives: readonly DocumentDriveDocument[] | undefined,\n ref: string | undefined,\n): DocumentDriveDocument | undefined {\n if (!drives || !ref) return undefined;\n const exact = drives.find(\n (d) => d.header.slug === ref || d.header.id === ref,\n );\n if (exact) return exact;\n const id = extractDriveIdFromSlug(ref);\n if (id !== undefined) {\n const byId = drives.find((d) => d.header.id === id);\n if (byId) return byId;\n }\n // `<name>-<id>` also for a readable id, as older links wrote it.\n return drives.find(\n (d) =>\n (!d.header.slug || d.header.slug === d.header.id) &&\n ref.endsWith(d.header.id) &&\n namedDriveSlug(d) === ref,\n );\n}\n\n/**\n * Makes a URL component for a node: `<slugged name>-<id>`. The id is kept\n * verbatim, since a v2-required id is case-sensitive base64url.\n */\nexport function makeNodeSlug(node: Node | undefined): string {\n if (!node) return \"\";\n return namedSlug(node, node.name, node.id);\n}\n\n/** Extracts the node slug from a path.\n *\n * The path is expected to be in the format `/d/<drive-slug>/<node-slug>`.\n */\nexport function extractNodeSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/[^/]+\\/([^/]+)$/.exec(currentPath);\n return match?.[1];\n}\n\n/** Finds a UUID in a string, used for extracting node ids from node slugs in the URL. */\nexport function findUuid(input: string | undefined) {\n if (!input) return undefined;\n const uuidRegex =\n /\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\\b/;\n const match = uuidRegex.exec(input);\n return match?.[0];\n}\n\n/** The v2-required document id a slug ends with, if any. */\nexport function findDerivedId(input: string | undefined) {\n if (!input || input.length < DERIVED_ID_LENGTH) return undefined;\n const start = input.length - DERIVED_ID_LENGTH;\n if (start > 0 && input[start - 1] !== \"-\") return undefined;\n const candidate = input.slice(start);\n return isDerivedDocumentId(candidate) ? candidate : undefined;\n}\n\nexport function extractNodeIdFromSlug(nodeSlug: string | undefined) {\n return findUuid(nodeSlug) ?? findDerivedId(nodeSlug);\n}\n\n/** @deprecated Route loaders resolve the node; use `extractNodeIdFromSlug`. */\nexport function extractNodeIdFromPath(path: string) {\n const nodeSlug = extractNodeSlugFromPath(path);\n const nodeId = extractNodeIdFromSlug(nodeSlug);\n return nodeId;\n}\n\n/** Extracts the drive slug from a path.\n * Used for extracting drive ids from drive slugs in the URL.\n * Expects the path to be in the format `/d/<drive-slug>`.\n */\nexport function extractDriveSlugFromPath(path: string) {\n const currentPath = getPathWithoutBase(path);\n const match = /^\\/d\\/([^/]+)/.exec(currentPath);\n return match?.[1] ?? \"\";\n}\n\nexport function extractDriveIdFromSlug(driveSlug: string | undefined) {\n return findUuid(driveSlug) ?? findDerivedId(driveSlug);\n}\n\n/** @deprecated Route loaders resolve the drive; use `extractDriveIdFromSlug`. */\nexport function extractDriveIdFromPath(path: string) {\n const driveSlug = extractDriveSlugFromPath(path);\n const driveId = extractDriveIdFromSlug(driveSlug);\n return driveId;\n}\n\n/** Creates a URL string with the given pathname, keeping the query string.\n * @deprecated The store's `navigation` keeps global params across navigations. */\nexport function createUrlWithPreservedParams(pathname: string): string {\n const search = window.location.search;\n return search ? `${pathname}${search}` : pathname;\n}\n","import type {\n PHNavigateOptions,\n PHNavigation,\n PHNavigationTarget,\n PHSearchUpdate,\n PHSettingsTarget,\n SearchParamsUpdate,\n} from \"@powerhousedao/reactor-browser\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { resolveUrlPathname } from \"../utils/url.js\";\nimport { getPHStore } from \"./ph-store.js\";\n\nconst isServer = typeof window === \"undefined\";\n\n/** Fired on `window` when the fallback navigator rewrites the URL. */\nexport const PH_LOCATION_CHANGE_EVENT = \"ph:locationchange\";\n\n/** Params read at boot or app-wide; they survive every navigation. Others,\n * e.g. a document's own, are dropped when the target changes. */\nexport const GLOBAL_SEARCH_PARAMS = [\n // A remote drive to add on boot.\n \"driveUrl\",\n // The theme override read by the inline theme boot script.\n \"theme\",\n // Embedded mode, which hides Connect's chrome.\n \"embed\",\n // Log level override for the feature-flag provider.\n \"LOG_LEVEL\",\n // The reactor worker runtime flag override.\n \"reactorWorker\",\n] as const;\n\n/** Feature flags are any `FEATURE_*` param, so they are retained by prefix. */\nexport const FEATURE_FLAG_PARAM_PREFIX = \"FEATURE_\";\n\n/** Whether `key` is a param every navigation keeps. */\nexport function isGlobalSearchParam(key: string) {\n return (\n (GLOBAL_SEARCH_PARAMS as readonly string[]).includes(key) ||\n key.startsWith(FEATURE_FLAG_PARAM_PREFIX)\n );\n}\n\nfunction globalSearch(search: string) {\n return Object.fromEntries(\n Object.entries(searchToRecord(search)).filter(([key]) =>\n isGlobalSearchParam(key),\n ),\n );\n}\n\n/** A query string's params; repeated keys keep their last value. */\nexport function searchToRecord(search: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(search));\n}\n\n/** `prev` with `update` applied; an `undefined` value removes the key. */\nexport function applySearchUpdate(\n prev: Record<string, string>,\n update: PHSearchUpdate,\n): Record<string, string> {\n const next = { ...prev };\n for (const [key, value] of Object.entries(update)) {\n if (value === undefined) delete next[key];\n else next[key] = value;\n }\n return next;\n}\n\n/** `params` as a query string, with an empty value as a bare key: `history`, not `history=`. */\nexport function searchParamsToString(params: URLSearchParams) {\n return params.toString().replace(/=(?=&|$)/g, \"\");\n}\n\n/** `?a=1&b=2`, or an empty string for no params. */\nexport function recordToSearch(record: Record<string, string>) {\n const search = searchParamsToString(new URLSearchParams(record));\n return search ? `?${search}` : \"\";\n}\n\n/** The settings page's path; its tabs are below it. */\nexport const SETTINGS_PATH = \"/settings\";\n\nexport function isSettingsTarget(\n target: PHNavigationTarget | undefined,\n): target is PHSettingsTarget {\n return !!target && \"settings\" in target;\n}\n\n/** The pathname a target opens at, base path included. */\nexport function targetPathname(target: PHNavigationTarget | undefined) {\n if (!target) return resolveUrlPathname(\"/\");\n if (isSettingsTarget(target)) {\n const { settings } = target;\n return resolveUrlPathname(\n settings === true ? SETTINGS_PATH : `${SETTINGS_PATH}/${settings}`,\n );\n }\n const { driveSlug, nodeSlug } = target;\n return resolveUrlPathname(\n nodeSlug ? `/d/${driveSlug}/${nodeSlug}` : `/d/${driveSlug}`,\n );\n}\n\n/** History state key: the index of the entry a document was opened from. */\nexport const OPENED_FROM_STATE_KEY = \"phOpenedFrom\";\n\n// The fallback numbers its own entries; a router's history has its own index.\ntype BrowserEntryState = { phIndex?: number; phOpenedFrom?: number };\n\nfunction browserEntryState(): BrowserEntryState {\n const state: unknown = window.history.state;\n return state && typeof state === \"object\" ? (state as BrowserEntryState) : {};\n}\n\n/** The index to go back to from `index`, when it lies before it. */\nexport function openedFromIndex(\n state: object | undefined,\n index: number,\n): number | undefined {\n const from = (state as Record<string, unknown> | undefined)?.[\n OPENED_FROM_STATE_KEY\n ];\n return typeof from === \"number\" && from >= 0 && from < index\n ? from\n : undefined;\n}\n\n// `openedFrom` \"keep\" carries the current entry's, as an in-document write does.\nfunction writeBrowserUrl(\n href: string,\n replace: boolean | undefined,\n openedFrom: number | \"keep\" | undefined,\n) {\n const prev = browserEntryState();\n const index = prev.phIndex ?? 0;\n const from = openedFrom === \"keep\" ? prev.phOpenedFrom : openedFrom;\n // Keeps the entry's state, e.g. a router's history key, on a replace.\n if (replace) {\n window.history.replaceState(\n { ...prev, phIndex: index, phOpenedFrom: from },\n \"\",\n href,\n );\n } else {\n window.history.pushState(\n { phIndex: index + 1, phOpenedFrom: from },\n \"\",\n href,\n );\n }\n window.dispatchEvent(new Event(PH_LOCATION_CHANGE_EVENT));\n}\n\nfunction subscribeToLocation(onChange: () => void) {\n window.addEventListener(\"popstate\", onChange);\n window.addEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n return () => {\n window.removeEventListener(\"popstate\", onChange);\n window.removeEventListener(PH_LOCATION_CHANGE_EVENT, onChange);\n };\n}\n\nconst readSearch = () => window.location.search;\nconst readPathname = () => window.location.pathname;\nconst readServerPathname = () => \"\";\nconst readServerSearch = () => \"\";\n\nfunction setBrowserSearch(\n update: (prev: Record<string, string>) => PHSearchUpdate,\n options?: { replace?: boolean },\n) {\n const prev = searchToRecord(window.location.search);\n const next = recordToSearch(applySearchUpdate({}, update(prev)));\n if (next === recordToSearch(prev)) return;\n // Like a router's search update, this drops the hash.\n writeBrowserUrl(\n `${window.location.pathname}${next}`,\n options?.replace,\n \"keep\",\n );\n}\n\nfunction setBrowserSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n setBrowserSearch((prev) => resolveSearchUpdate(prev, update), options);\n}\n\n/** The fallback without a host: `window.location` and `window.history`. Only\n * the global params carry over to another target, as with a router. */\n// Set by sync-selection.ts, which imports this module: importing it here would be a cycle.\nlet syncSelectionAfterOpen = () => {};\n\n/** @internal Selects what the browser fallback opens; sync-selection.ts sets it. */\nexport function setBrowserOpenSync(sync: () => void) {\n syncSelectionAfterOpen = sync;\n}\n\nexport const browserNavigation: PHNavigation = {\n location: () => window.location,\n hrefFor: (target) =>\n `${targetPathname(target)}${recordToSearch(globalSearch(window.location.search))}`,\n useIsCurrent(target) {\n const pathname = useSyncExternalStore(\n subscribeToLocation,\n readPathname,\n readServerPathname,\n );\n return pathname === targetPathname(target);\n },\n open: (target, options) => {\n const prev = globalSearch(window.location.search);\n const search = options?.search\n ? applySearchUpdate(prev, options.search)\n : prev;\n const entry = browserEntryState();\n writeBrowserUrl(\n `${targetPathname(target)}${recordToSearch(search)}`,\n options?.replace,\n options?.replace ? entry.phOpenedFrom : (entry.phIndex ?? 0),\n );\n // No router selects for it, and pushState fires no popstate.\n syncSelectionAfterOpen();\n },\n closeOpened: () => {\n const entry = browserEntryState();\n const index = entry.phIndex ?? 0;\n const from = openedFromIndex(entry, index);\n if (from === undefined) return false;\n window.history.go(from - index);\n return true;\n },\n setSearch: setBrowserSearch,\n useSearchParams() {\n const search = useSyncExternalStore(\n subscribeToLocation,\n readSearch,\n readServerSearch,\n );\n return useMemo(() => searchToRecord(search), [search]);\n },\n useSetSearchParams: () => setBrowserSearchParams,\n};\n\n/** True when the store has a host navigation, not the browser fallback. */\nexport function hasHostNavigation() {\n return !isServer && getPHStore()?.navigation !== undefined;\n}\n\n/** The app store's navigation, else the browser fallback. */\nexport function getPHNavigation(): PHNavigation {\n return getPHStore()?.navigation ?? browserNavigation;\n}\n\n/** The current pathname as the navigation sees it, base path included. */\nexport function getCurrentPathname() {\n return getPHNavigation().location().pathname;\n}\n\n/** Opens `target`; without `search`, a target already open is left alone. */\nexport function openTarget(\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n openTargetWith(getPHNavigation(), target, options);\n}\n\n/** Opens `target` through `navigation`, unless it is open already. */\nexport function openTargetWith(\n navigation: PHNavigation,\n target: PHNavigationTarget | undefined,\n options?: PHNavigateOptions,\n) {\n const pathname = navigation.location().pathname;\n const targetPath = targetPathname(target);\n // On any tab, the settings page is open.\n const open =\n targetPath === pathname ||\n (isSettingsTarget(target) &&\n target.settings === true &&\n pathname.startsWith(`${targetPath}/`));\n if (!options?.search && open) return;\n navigation.open(target, options);\n}\n\n/** Asks the host navigation to warm `target`; a no-op without one. */\nexport function preloadTarget(target: PHNavigationTarget | undefined) {\n if (!hasHostNavigation()) return;\n getPHNavigation().preload?.(target);\n}\n\n/** The href `target` opens at through `navigation`, base path included. */\nexport function getTargetHref(\n target: PHNavigationTarget | undefined,\n navigation: PHNavigation = getPHNavigation(),\n) {\n return navigation.hrefFor?.(target) ?? targetPathname(target);\n}\n\nexport function resolveSearchUpdate(\n prev: Record<string, string>,\n update: SearchParamsUpdate,\n): Record<string, string> {\n return typeof update === \"function\"\n ? applySearchUpdate({}, update(prev))\n : applySearchUpdate(prev, update);\n}\n\n/** Rewrites the current query params through the app store's navigation. */\nexport function setSearchParams(\n update: SearchParamsUpdate,\n options?: { replace?: boolean },\n) {\n getPHNavigation().setSearch(\n (prev) => resolveSearchUpdate(prev, update),\n options,\n );\n}\n"],"mappings":";;;;;AASA,MAAM,oBAAoB;AAG1B,SAAgB,mBAAmB,MAAc;CAC/C,OAAO,IAAI,IACT,KAAK,QAAQ,QAAQ,EAAE,GACvB,OAAO,SAAS,UAAU,WAAW,CAAC,EAAE,YAAY,IACtD,CAAC,CAAC;AACJ;;AAGA,SAAgB,mBAAmB,MAAc;CAC/C,MAAM,WAAW,WAAW,CAAC,EAAE,YAAY;CAC3C,IAAI,CAAC,KAAK,WAAW,QAAQ,GAAG,OAAO;CACvC,MAAM,OAAO,KAAK,MAAM,SAAS,MAAM;CACvC,IAAI,SAAS,SAAS,GAAG,GAAG,OAAO,IAAI;CACvC,OAAO,SAAS,MAAM,KAAK,WAAW,GAAG,IAAI,OAAO;AACtD;;;AAIA,SAAgB,sBACd,OACA;CACA,IAAI,CAAC,OAAO,OAAO;CACnB,OAAO,MAAM,KAAK,MAAM,OAAO,IAAI;AACrC;;;AAIA,SAAgB,cAAc,OAAsC;CAClE,MAAM,EAAE,IAAI,MAAM,cAAc,MAAM;CACtC,IAAI,aAAa,cAAc,IAAI,OAAO;CAC1C,OAAO,WAAW,EAAE,IAAI,eAAe,KAAK,IAAI;AAClD;AAEA,SAAS,W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O;AACjC;;AAGA,SAAgB,cAAc,QAAwC;CACpE,IAAI,CAAC,kBAAkB,GAAG;CAC1B,gBAAgB,CAAC,CAAC,UAAU,MAAM;AACpC;;AAGA,SAAgB,cACd,QACA,aAA2B,gBAAgB,GAC3C;CACA,OAAO,WAAW,UAAU,MAAM,KAAK,eAAe,MAAM;AAC9D;AAEA,SAAgB,oBACd,MACA,QACwB;CACxB,OAAO,OAAO,WAAW,aACrB,kBAAkB,CAAC,GAAG,OAAO,IAAI,CAAC,IAClC,kBAAkB,MAAM,MAAM;AACpC;;AAGA,SAAgB,gBACd,QACA,SACA;CACA,gBAAgB,CAAC,CAAC,WACf,SAAS,oBAAoB,MAAM,MAAM,GAC1C,OACF;AACF"}
@@ -1,5 +1,5 @@
1
- import { g as useSelectedDriveSafe } from "../../document-model-modules-DROQT_yu.js";
2
- import { a as getBrowserSyncManager, h as useSelectedNode, i as createSwitchboardSchemaTool, l as useSelectedDocumentId, n as SWITCHBOARD_INTROSPECTION_QUERY, o as resolveDriveSwitchboard, r as SWITCHBOARD_SCHEMA_TOOL_NAME, s as summarizeIntrospectionSchema, t as GQL_CHANNEL_SUFFIX } from "../../switchboard-cwUp3FxP.js";
1
+ import { g as useSelectedDriveSafe } from "../../document-model-modules-BN6ps-J2.js";
2
+ import { a as getBrowserSyncManager, h as useSelectedNode, i as createSwitchboardSchemaTool, l as useSelectedDocumentId, n as SWITCHBOARD_INTROSPECTION_QUERY, o as resolveDriveSwitchboard, r as SWITCHBOARD_SCHEMA_TOOL_NAME, s as summarizeIntrospectionSchema, t as GQL_CHANNEL_SUFFIX } from "../../switchboard-BxnVm77m.js";
3
3
  import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  import { isFileNode, isFolderNode } from "@powerhousedao/shared/document-drive";
@@ -1,5 +1,5 @@
1
1
  import { i as getGlobal, n as getAnalyticsStore, t as createAnalyticsStore } from "../../store-DInXcjal.js";
2
- import { t as useDocumentById } from "../../document-by-id-DqAyjr9P.js";
2
+ import { t as useDocumentById } from "../../document-by-id-1mRv91Zu.js";
3
3
  import { useEffect } from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  import { childLogger } from "document-model";
@@ -1,5 +1,5 @@
1
- import { _t as OperationsCacheEntry, dt as IReactorBrowserClient, gt as IOperationCache } from "../../global-D-VZTZRz.js";
2
- import { $ as ReactorOperationFieldsFragmentDoc, A as useDocument, B as isAuthRefusalClose, Ct as GetDocumentQueryResult, Dt as phDocumentFromMutation, Et as phDocumentFromGetDocument, F as useGetDocumentAsync, G as packageFromDocumentModels, H as startDocumentChangesSubscription, I as useGetDocuments, J as signStampedAction, Jt as IDLE_OPERATIONS_ENTRY, K as resolveDocumentModelModule, L as ConnectionParams, M as useDocumentSafe, N as useDocuments, Ot as revisionMapFromRevisionsList, P as useGetDocument, Q as MutateDocumentWithOperationsVariables, R as DocumentChangesEventPayload, St as GetDocumentQueryFields, Tt as isoStringFromDateTime, U as subscriptionsUrlFromGraphqlUrl, V as makeAuthConnectionParams, W as StaticPackageManager, X as MutateDocumentWithOperationsDocument, Xt as isOperationCache, Y as stampAction, Yt as addPromiseState, Z as MutateDocumentWithOperationsResult, Zt as readPromiseState, _t as GraphQLOperationNotSupportedError, a as DocumentOperationsState, at as GraphQLReactorClient, bt as ambientRenownTokenProvider, c as useDocumentModelModuleById, ct as isGraphQLReactorClient, d as UseDispatchResult, dt as SubgraphSdkFactory, et as GraphQLReactorProvider, ft as SubgraphSdkRegistry, gt as BatchJobFailedError, ht as subgraphUrlFromGraphqlUrl, i as DocumentOperationsResult, it as DriveIdCall, j as useDocumentCache, k as setDocumentCache, l as useDocumentModelModules, lt as viewFilterInputFromViewFilter, mt as describeGraphQLDocument, nt as ensurePHEventHandlers, o as UseDocumentOperationsOptions, ot as GraphQLReactorClientOptions, p as useDispatch, pt as TypedGraphQLDocument, q as prepareSignedActions, qt as DocumentCache, r as useAttachmentService, rt as useSwitchboardClient, s as useDocumentOperations, st as findIsServableOverGraphQL, tt as GraphQLReactorProviderProps, u as DispatchFn, ut as GraphQLRequestOptions, vt as GraphQLWrongBackendError, w as useReactorClient, wt as RevisionsListSelection, xt as makeAuthMiddleware, y as setReactorClient, yt as BearerTokenProvider, z as DocumentChangesSubscriptionOptions } from "../../attachment-service-CAf9N-15.js";
1
+ import { dt as IReactorBrowserClient, vt as IOperationCache, yt as OperationsCacheEntry } from "../../global-DgCDUQH2.js";
2
+ import { $ as ReactorOperationFieldsFragmentDoc, $t as readPromiseState, A as useDocument, B as isAuthRefusalClose, Ct as GetDocumentQueryResult, Dt as phDocumentFromMutation, Et as phDocumentFromGetDocument, F as useGetDocumentAsync, G as packageFromDocumentModels, H as startDocumentChangesSubscription, I as useGetDocuments, J as signStampedAction, K as resolveDocumentModelModule, L as ConnectionParams, M as useDocumentSafe, N as useDocuments, Ot as revisionMapFromRevisionsList, P as useGetDocument, Q as MutateDocumentWithOperationsVariables, Qt as isOperationCache, R as DocumentChangesEventPayload, St as GetDocumentQueryFields, Tt as isoStringFromDateTime, U as subscriptionsUrlFromGraphqlUrl, V as makeAuthConnectionParams, W as StaticPackageManager, X as MutateDocumentWithOperationsDocument, Xt as addPromiseState, Y as stampAction, Yt as IDLE_OPERATIONS_ENTRY, Z as MutateDocumentWithOperationsResult, _t as GraphQLOperationNotSupportedError, a as DocumentOperationsState, at as GraphQLReactorClient, bt as ambientRenownTokenProvider, c as useDocumentModelModuleById, ct as isGraphQLReactorClient, d as UseDispatchResult, dt as SubgraphSdkFactory, et as GraphQLReactorProvider, ft as SubgraphSdkRegistry, gt as BatchJobFailedError, ht as subgraphUrlFromGraphqlUrl, i as DocumentOperationsResult, it as DriveIdCall, j as useDocumentCache, k as setDocumentCache, l as useDocumentModelModules, lt as viewFilterInputFromViewFilter, mt as describeGraphQLDocument, nt as ensurePHEventHandlers, o as UseDocumentOperationsOptions, ot as GraphQLReactorClientOptions, p as useDispatch, pt as TypedGraphQLDocument, q as prepareSignedActions, qt as DocumentCache, r as useAttachmentService, rt as useSwitchboardClient, s as useDocumentOperations, st as findIsServableOverGraphQL, tt as GraphQLReactorProviderProps, u as DispatchFn, ut as GraphQLRequestOptions, vt as GraphQLWrongBackendError, w as useReactorClient, wt as RevisionsListSelection, xt as makeAuthMiddleware, y as setReactorClient, yt as BearerTokenProvider, z as DocumentChangesSubscriptionOptions } from "../../attachment-service-0L7kHOC-.js";
3
3
  import { k as SdkFunctionWrapper } from "../../types-0Fh1tNjy.js";
4
4
  export { BatchJobFailedError, BearerTokenProvider, ConnectionParams, type DispatchFn, DocumentCache, DocumentChangesEventPayload, DocumentChangesSubscriptionOptions, type DocumentOperationsResult, type DocumentOperationsState, DriveIdCall, GetDocumentQueryFields, GetDocumentQueryResult, GraphQLOperationNotSupportedError, GraphQLReactorClient, GraphQLReactorClientOptions, GraphQLReactorProvider, GraphQLReactorProviderProps, GraphQLRequestOptions, GraphQLWrongBackendError, IDLE_OPERATIONS_ENTRY, type IOperationCache, type IReactorBrowserClient, MutateDocumentWithOperationsDocument, MutateDocumentWithOperationsResult, MutateDocumentWithOperationsVariables, type OperationsCacheEntry, ReactorOperationFieldsFragmentDoc, RevisionsListSelection, type SdkFunctionWrapper, StaticPackageManager, SubgraphSdkFactory, SubgraphSdkRegistry, TypedGraphQLDocument, type UseDispatchResult, type UseDocumentOperationsOptions, addPromiseState, ambientRenownTokenProvider, describeGraphQLDocument, ensurePHEventHandlers, findIsServableOverGraphQL, isAuthRefusalClose, isGraphQLReactorClient, isOperationCache, isoStringFromDateTime, makeAuthConnectionParams, makeAuthMiddleware, packageFromDocumentModels, phDocumentFromGetDocument, phDocumentFromMutation, prepareSignedActions, readPromiseState, resolveDocumentModelModule, revisionMapFromRevisionsList, setDocumentCache, setReactorClient, signStampedAction, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, useAttachmentService, useDispatch, useDocument, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOperations, useDocumentSafe, useDocuments, useGetDocument, useGetDocumentAsync, useGetDocuments, useReactorClient, useSwitchboardClient, viewFilterInputFromViewFilter };
5
5
  export {};
@@ -1,4 +1,4 @@
1
- import { a as useDocument, c as useDocuments, d as useGetDocuments, f as DocumentCache, g as readPromiseState, h as isOperationCache, i as setDocumentCache, l as useGetDocument, m as addPromiseState, n as useDispatch, o as useDocumentCache, p as IDLE_OPERATIONS_ENTRY, s as useDocumentSafe, u as useGetDocumentAsync } from "../../dispatch-Dd_WEz35.js";
2
- import { H as makeAuthMiddleware, V as ambientRenownTokenProvider, n as useDocumentModelModules, t as useDocumentModelModuleById } from "../../document-model-modules-DROQT_yu.js";
3
- import { $r as signStampedAction, Br as isGraphQLReactorClient, Gr as subscriptionsUrlFromGraphqlUrl, Hr as isAuthRefusalClose, I as useAttachmentService, Jr as subgraphUrlFromGraphqlUrl, Ki as useReactorClient, Kr as SubgraphSdkRegistry, Qr as prepareSignedActions, Rr as GraphQLReactorClient, Ur as makeAuthConnectionParams, Vi as setReactorClient, Vr as viewFilterInputFromViewFilter, Wr as startDocumentChangesSubscription, Xr as packageFromDocumentModels, Yr as StaticPackageManager, Zr as resolveDocumentModelModule, ai as GraphQLWrongBackendError, ci as phDocumentFromMutation, ei as stampAction, i as useSwitchboardClient, ii as GraphQLOperationNotSupportedError, li as revisionMapFromRevisionsList, n as GraphQLReactorProvider, ni as ReactorOperationFieldsFragmentDoc, oi as isoStringFromDateTime, qr as describeGraphQLDocument, r as ensurePHEventHandlers, ri as BatchJobFailedError, si as phDocumentFromGetDocument, t as useDocumentOperations, ti as MutateDocumentWithOperationsDocument, zr as findIsServableOverGraphQL } from "../../document-operations-C6khz2If.js";
1
+ import { _ as isOperationCache, a as useDocument, c as useDocuments, d as useGetDocuments, f as DocumentCache, h as addPromiseState, i as setDocumentCache, l as useGetDocument, m as IDLE_OPERATIONS_ENTRY, n as useDispatch, o as useDocumentCache, s as useDocumentSafe, u as useGetDocumentAsync, v as readPromiseState } from "../../dispatch-COa-7Cnf.js";
2
+ import { H as makeAuthMiddleware, V as ambientRenownTokenProvider, n as useDocumentModelModules, t as useDocumentModelModuleById } from "../../document-model-modules-BN6ps-J2.js";
3
+ import { $r as signStampedAction, Br as isGraphQLReactorClient, Gr as subscriptionsUrlFromGraphqlUrl, Hr as isAuthRefusalClose, I as useAttachmentService, Jr as subgraphUrlFromGraphqlUrl, Ki as useReactorClient, Kr as SubgraphSdkRegistry, Qr as prepareSignedActions, Rr as GraphQLReactorClient, Ur as makeAuthConnectionParams, Vi as setReactorClient, Vr as viewFilterInputFromViewFilter, Wr as startDocumentChangesSubscription, Xr as packageFromDocumentModels, Yr as StaticPackageManager, Zr as resolveDocumentModelModule, ai as GraphQLWrongBackendError, ci as phDocumentFromMutation, ei as stampAction, i as useSwitchboardClient, ii as GraphQLOperationNotSupportedError, li as revisionMapFromRevisionsList, n as GraphQLReactorProvider, ni as ReactorOperationFieldsFragmentDoc, oi as isoStringFromDateTime, qr as describeGraphQLDocument, r as ensurePHEventHandlers, ri as BatchJobFailedError, si as phDocumentFromGetDocument, t as useDocumentOperations, ti as MutateDocumentWithOperationsDocument, zr as findIsServableOverGraphQL } from "../../document-operations-BY6lqh4g.js";
4
4
  export { BatchJobFailedError, DocumentCache, GraphQLOperationNotSupportedError, GraphQLReactorClient, GraphQLReactorProvider, GraphQLWrongBackendError, IDLE_OPERATIONS_ENTRY, MutateDocumentWithOperationsDocument, ReactorOperationFieldsFragmentDoc, StaticPackageManager, SubgraphSdkRegistry, addPromiseState, ambientRenownTokenProvider, describeGraphQLDocument, ensurePHEventHandlers, findIsServableOverGraphQL, isAuthRefusalClose, isGraphQLReactorClient, isOperationCache, isoStringFromDateTime, makeAuthConnectionParams, makeAuthMiddleware, packageFromDocumentModels, phDocumentFromGetDocument, phDocumentFromMutation, prepareSignedActions, readPromiseState, resolveDocumentModelModule, revisionMapFromRevisionsList, setDocumentCache, setReactorClient, signStampedAction, stampAction, startDocumentChangesSubscription, subgraphUrlFromGraphqlUrl, subscriptionsUrlFromGraphqlUrl, useAttachmentService, useDispatch, useDocument, useDocumentCache, useDocumentModelModuleById, useDocumentModelModules, useDocumentOperations, useDocumentSafe, useDocuments, useGetDocument, useGetDocumentAsync, useGetDocuments, useReactorClient, useSwitchboardClient, viewFilterInputFromViewFilter };
@@ -1,3 +1,3 @@
1
- import { A as RENOWN_RETURN_URL_STRIPPED_PARAMS, B as UserIcon, C as CREDENTIAL_SCHEMA_EIP712_TYPE, D as ISSUER_TYPE, E as DOMAIN_TYPE, F as ChevronDownIcon, G as RenownLoginButtonProps, H as RenownUserButtonMenuItem, I as CopyIcon, K as RenownAuthButton, L as DisconnectIcon, M as VERIFIABLE_CREDENTIAL_EIP712_TYPE, N as initConnectCrypto, O as RENOWN_CHAIN_ID, P as initRenownCrypto, Q as useRenown, R as RenownLogo, S as useRenownInitialUser, T as CREDENTIAL_TYPES, U as RenownUserButtonProps, V as RenownUserButton, W as RenownLoginButton, _ as RENOWN_INITIAL_UNKNOWN, a as RenownWalletProviderProps, at as RenownAuthResolution, b as RenownInitialUserProviderProps, c as Renown, ct as useRenownAuthAsync, d as useRenownInit, f as RenownSessionCookieOptions, g as RENOWN_INITIAL_ANONYMOUS, h as useRenownSessionSynced, i as RenownWalletProvider, it as RenownAuthAsync, j as RENOWN_URL, k as RENOWN_NETWORK_ID, l as RenownProps, m as useRenownSessionCookie, n as RenownLoginMethod, nt as openRenown, o as RenownProvider, ot as RenownAuthStatus, p as RenownSessionCookieState, q as RenownAuthButtonProps, r as useRenownLoginMethods, rt as RenownAuth, s as RenownProviderProps, st as useRenownAuth, t as useRenownWalletAdapter, u as RenownInitOptions, v as RenownInitialAuth, w as CREDENTIAL_SUBJECT_TYPE, x as useRenownInitialAuth, y as RenownInitialUserProvider, z as SpinnerIcon } from "../../index-XfcUiODQ.js";
1
+ import { A as RENOWN_RETURN_URL_STRIPPED_PARAMS, B as UserIcon, C as CREDENTIAL_SCHEMA_EIP712_TYPE, D as ISSUER_TYPE, E as DOMAIN_TYPE, F as ChevronDownIcon, G as RenownLoginButtonProps, H as RenownUserButtonMenuItem, I as CopyIcon, K as RenownAuthButton, L as DisconnectIcon, M as VERIFIABLE_CREDENTIAL_EIP712_TYPE, N as initConnectCrypto, O as RENOWN_CHAIN_ID, P as initRenownCrypto, Q as useRenown, R as RenownLogo, S as useRenownInitialUser, T as CREDENTIAL_TYPES, U as RenownUserButtonProps, V as RenownUserButton, W as RenownLoginButton, _ as RENOWN_INITIAL_UNKNOWN, a as RenownWalletProviderProps, at as RenownAuthResolution, b as RenownInitialUserProviderProps, c as Renown, ct as useRenownAuthAsync, d as useRenownInit, f as RenownSessionCookieOptions, g as RENOWN_INITIAL_ANONYMOUS, h as useRenownSessionSynced, i as RenownWalletProvider, it as RenownAuthAsync, j as RENOWN_URL, k as RENOWN_NETWORK_ID, l as RenownProps, m as useRenownSessionCookie, n as RenownLoginMethod, nt as openRenown, o as RenownProvider, ot as RenownAuthStatus, p as RenownSessionCookieState, q as RenownAuthButtonProps, r as useRenownLoginMethods, rt as RenownAuth, s as RenownProviderProps, st as useRenownAuth, t as useRenownWalletAdapter, u as RenownInitOptions, v as RenownInitialAuth, w as CREDENTIAL_SUBJECT_TYPE, x as useRenownInitialAuth, y as RenownInitialUserProvider, z as SpinnerIcon } from "../../index-Dfr257W2.js";
2
2
  export { CREDENTIAL_SCHEMA_EIP712_TYPE, CREDENTIAL_SUBJECT_TYPE, CREDENTIAL_TYPES, ChevronDownIcon, CopyIcon, DOMAIN_TYPE, DisconnectIcon, ISSUER_TYPE, RENOWN_CHAIN_ID, RENOWN_INITIAL_ANONYMOUS, RENOWN_INITIAL_UNKNOWN, RENOWN_NETWORK_ID, RENOWN_RETURN_URL_STRIPPED_PARAMS, RENOWN_URL, Renown, type RenownAuth, type RenownAuthAsync, RenownAuthButton, type RenownAuthButtonProps, type RenownAuthResolution, type RenownAuthStatus, type RenownInitOptions, type RenownInitialAuth, RenownInitialUserProvider, type RenownInitialUserProviderProps, RenownLoginButton, type RenownLoginButtonProps, type RenownLoginMethod, RenownLogo, type RenownProps, RenownProvider, type RenownProviderProps, type RenownSessionCookieOptions, type RenownSessionCookieState, RenownUserButton, type RenownUserButtonMenuItem, type RenownUserButtonProps, RenownWalletProvider, type RenownWalletProviderProps, SpinnerIcon, UserIcon, VERIFIABLE_CREDENTIAL_EIP712_TYPE, initConnectCrypto, initRenownCrypto, openRenown, useRenown, useRenownAuth, useRenownAuthAsync, useRenownInit, useRenownInitialAuth, useRenownInitialUser, useRenownLoginMethods, useRenownSessionCookie, useRenownSessionSynced, useRenownWalletAdapter };
3
3
  export {};
@@ -213,42 +213,76 @@ export declare class SyncManagerProxy implements ISyncManager, ISyncInspector, I
213
213
  }
214
214
  export declare function createSyncManagerProxy(router: MessageRouter$1, busProxy: IEventBus): ISyncManager;
215
215
  //#endregion
216
+ //#region src/rpc/module-graph.d.ts
217
+ /** A bare specifier's URL in the shared table: an exact entry, else the longest trailing-slash prefix, as an import map does. */
218
+ export declare function resolveSharedSpecifier(specifier: string, imports: Record<string, string>): string | undefined;
219
+ type ModuleGraphOptions = {
220
+ sharedImports?: Record<string, string>;
221
+ /** Reads a module's source; defaults to fetch. */
222
+ fetchSource?: (url: string) => Promise<string>;
223
+ /** Makes a rewritten source importable; defaults to a blob URL. */
224
+ createModuleUrl?: (source: string) => string;
225
+ /** Told about dynamic imports with computed specifiers, which stay as they are. */
226
+ warn?: (message: string) => void;
227
+ };
228
+ export declare class ModuleGraph {
229
+ private readonly sharedImports;
230
+ private readonly fetchSource;
231
+ private readonly createModuleUrl;
232
+ private readonly warn;
233
+ private readonly parsed;
234
+ private readonly built;
235
+ constructor(options?: ModuleGraphOptions);
236
+ /** The URL to import in place of `entryUrl`; `entryUrl` itself when nothing needed a rewrite. */
237
+ resolve(entryUrl: string): Promise<string>;
238
+ private collect;
239
+ private parse;
240
+ private readModule;
241
+ private assertAcyclic;
242
+ private assertMapped;
243
+ private needsRewrite;
244
+ private build;
245
+ private rewrite;
246
+ }
247
+ //#endregion
216
248
  //#region src/rpc/worker-package-loader.d.ts
217
249
  type PackageImporter = (url: string) => Promise<Record<string, unknown>>;
218
250
  type WorkerPackageLoaderOptions = {
219
251
  cdnUrl: string;
220
252
  importPackage: PackageImporter;
221
253
  resolvePackages?: (documentType: string) => Promise<string[]>;
222
- /** Absolute-URL import map for shared deps (worker import maps don't
223
- * exist, so the source is rewritten to these URLs and blob-imported). */
254
+ /** Absolute URLs for the shared deps a registry package leaves bare; a worker has no import map. */
224
255
  sharedImports?: Record<string, string>;
225
- /** Import a rewritten source string (blob URL). Only called when a
226
- * rewrite happened; omit to disable shared-deps loading in a worker. */
227
- importSource?: (source: string) => Promise<Record<string, unknown>>;
228
- };
256
+ } & Pick<ModuleGraphOptions, "fetchSource" | "createModuleUrl" | "warn">;
229
257
  type PackageLoadFailure = {
230
258
  name: string;
231
259
  url: string;
232
260
  error: unknown;
233
261
  };
262
+ /** One line for a failed load: the package, its URL and why. */
263
+ export declare function describeLoadFailure(failure: PackageLoadFailure): string;
234
264
  type AnyUpgradeManifest = UpgradeManifest<readonly number[]>;
235
265
  export declare class WorkerPackageLoader implements IDocumentModelLoader {
236
266
  private readonly cdnUrl;
237
267
  private readonly importPackage;
238
268
  private readonly resolvePackages;
239
- private readonly sharedImports?;
240
- private readonly importSource?;
269
+ private readonly moduleGraph;
241
270
  private readonly modulesByKey;
242
271
  private readonly manifestsByType;
243
272
  private readonly keysBySource;
244
273
  private readonly manifestTypesBySource;
245
- private readonly loadedSpecs;
274
+ private readonly loadedUrls;
246
275
  private readonly failures;
247
276
  private readonly pendingLoads;
248
277
  private readonly generationBySource;
249
278
  private generation;
250
279
  constructor(options: WorkerPackageLoaderOptions);
251
280
  loadPackages(specs: string[]): Promise<DocumentModelModule[]>;
281
+ /** Loads registry packages added or updated after boot; returns the types whose modules changed, and the failures. */
282
+ updatePackages(specs: string[]): Promise<{
283
+ types: string[];
284
+ failures: PackageLoadFailure[];
285
+ }>;
252
286
  /** Loads URL-addressed packages (local project packages). Idempotent. */
253
287
  loadSources(sources: WorkerPackageSource$1[]): Promise<void>;
254
288
  /**
@@ -278,6 +312,6 @@ export declare class WorkerPackageLoader implements IDocumentModelLoader {
278
312
  private registerNamespace;
279
313
  }
280
314
  //#endregion
281
- export { type AdoptSyncPeerParams, type ClientMessage, type CorrelationId, type ErrorInfo, type ICorrelatedSubscriptions, type IHostResponder, type IInspectorProxy, type ILiveQueryProxy, type IOpChannel, type IRpcTransport, type IWorkerAdminClient, type InspectorOpTargets, KeyedListeners, Listeners, MessageRouter, type MethodCallMessage, type OpKind, type OwnerMessage, type PackageImporter, type PackageLoadFailure, RPC_PROTOCOL_VERSION, type ReactorHello, ReactorHostServer, type ReactorIdentity, type RemoveSyncPeerParams, type RpcAdoptSyncPeer, RpcCorrelator, type RpcDbOp, type RpcLiveEvent, type RpcLiveSubscribe, type RpcLiveUnsub, type RpcMessage, type RpcPoster, type RpcRemoveSyncPeer, type RpcRequestOptions, SubscriptionStore, type SyncInspectionOpTargets, type SyncStatusChangedBusEvent, type VersionFingerprint, type WorkerInspectorInfo, type WorkerMigrationState, type WorkerPackageLoaderOptions, type WorkerPackageSource, createCorrelatedSubscriptions, createInspectorProxy, createPortTransport, createReactorClientProxy, createWorkerAdminClient, fromErrorInfo, hostResponder, toErrorInfo };
315
+ export { type AdoptSyncPeerParams, type ClientMessage, type CorrelationId, type ErrorInfo, type ICorrelatedSubscriptions, type IHostResponder, type IInspectorProxy, type ILiveQueryProxy, type IOpChannel, type IRpcTransport, type IWorkerAdminClient, type InspectorOpTargets, KeyedListeners, Listeners, MessageRouter, type MethodCallMessage, type ModuleGraphOptions, type OpKind, type OwnerMessage, type PackageImporter, type PackageLoadFailure, RPC_PROTOCOL_VERSION, type ReactorHello, ReactorHostServer, type ReactorIdentity, type RemoveSyncPeerParams, type RpcAdoptSyncPeer, RpcCorrelator, type RpcDbOp, type RpcLiveEvent, type RpcLiveSubscribe, type RpcLiveUnsub, type RpcMessage, type RpcPoster, type RpcRemoveSyncPeer, type RpcRequestOptions, SubscriptionStore, type SyncInspectionOpTargets, type SyncStatusChangedBusEvent, type VersionFingerprint, type WorkerInspectorInfo, type WorkerMigrationState, type WorkerPackageLoaderOptions, type WorkerPackageSource, createCorrelatedSubscriptions, createInspectorProxy, createPortTransport, createReactorClientProxy, createWorkerAdminClient, fromErrorInfo, hostResponder, toErrorInfo };
282
316
  export {};
283
317
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/op-channel.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/bus-event-ids.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/worker-package-loader.ts"],"mappings":";;;;;;KAIY;EACV;EACA;;EAEA;EACA;EACA,QAAQ;;KAGE;EACV;EACA;EACA;;;wBAIc,kBACd,QAAQ,iBACR,QAAQ,qBACR,MAAM,cACL;;wBAmBa,mBACd,QAAQ,iBACR,QAAQ,uBACP;;;KCQS;EACV,SAAS;EACT,SAAS,uBAAuB,QAAQ;EACxC,oBACE,iBACA,UAAU,4BACP;EACL,sBAAsB,oBAAoB;EAC1C,cAAc,MAAM;EACpB,YAAY,gBAAgB,oBAAoB;EAChD,UAAU,gBAAgB,oBAAoB;EAC9C,iBAAiB,gBAAgB,oBAAoB;;EAErD,mBACE,QAAQ,qBACR,MAAM,gBACH;EACL,oBAAoB,QAAQ,yBAAyB;EACrD,eACE,aACA,mBACA,YAAY,8BACT;EAEL;EACA;EACA;EACA;EACA;EACA,4BAA4B;EAC5B,uBAAuB;;EAEvB,YAAY,mBAAmB;;EAE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AgB;;UAKZ;UAaA;UAuBM;UAQN;UAgBM;UAoCA;;UA2BN"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/rpc/adopt-sync-peer.ts","../../../src/rpc/reactor-host.ts","../../../src/rpc/local-sync-peer-handlers.ts","../../../src/rpc/inspector-ops.ts","../../../src/rpc/op-channel.ts","../../../src/rpc/live-query-proxy.ts","../../../src/rpc/relational-db-proxy.ts","../../../src/rpc/event-bus-proxy.ts","../../../src/rpc/forwarded-events.ts","../../../src/rpc/connect-reactor.ts","../../../src/rpc/bus-event-ids.ts","../../../src/rpc/sync-manager-proxy.ts","../../../src/rpc/module-graph.ts","../../../src/rpc/worker-package-loader.ts"],"mappings":";;;;;;KAIY;EACV;EACA;;EAEA;EACA;EACA,QAAQ;;KAGE;EACV;EACA;EACA;;;wBAIc,kBACd,QAAQ,iBACR,QAAQ,qBACR,MAAM,cACL;;wBAmBa,mBACd,QAAQ,iBACR,QAAQ,uBACP;;;KCQS;EACV,SAAS;EACT,SAAS,uBAAuB,QAAQ;EACxC,oBACE,iBACA,UAAU,4BACP;EACL,sBAAsB,oBAAoB;EAC1C,cAAc,MAAM;EACpB,YAAY,gBAAgB,oBAAoB;EAChD,UAAU,gBAAgB,oBAAoB;EAC9C,iBAAiB,gBAAgB,oBAAoB;;EAErD,mBACE,QAAQ,qBACR,MAAM,gBACH;EACL,oBAAoB,QAAQ,yBAAyB;EACrD,eACE,aACA,mBACA,YAAY,8BACT;EAEL;EACA;EACA;EACA;EACA;EACA,4BAA4B;EAC5B,uBAAuB;;EAEvB,YAAY,mBAAmB;;EAE/B,0BAA0B;;;wBA0BZ,4BAA4B;qBA2B/B;qBAMA;mBACM;mBACA;mBACA;UACT;UAEA;UACA;mBACS;mBACA;UACT;UACA;UACA;EAER,YAAY,SAAS;EASrB,QAAQ,WAAW;EAkInB,YAAY,MAAM;EAKlB,kBAAkB,mBAAmB;EAOrC,gBAAgB,gBAAgB;EAQhC,gBAAgB,gBAAgB;UAalB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Q;MAqBtC,UAAU;MAIV,oBAAoB;MAIpB,gBAAgB;;UAKZ;UAaA;UAwBA;UAYA;UAqBM;UAqCA;;UAWN"}
@@ -1,7 +1,7 @@
1
1
  import { l as SYNC_REMOTES_CHANGED_EVENT, t as RegistryClient, u as SYNC_STATUS_CHANGED_EVENT } from "../../client-BFnMV-EO.js";
2
2
  import { DriveCollectionId, INSPECTOR_OPS, ReactorEventTypes, SYNC_INSPECTION_OPS, SyncEventTypes, collectionIdFromKey, createPeerAgreement, dispatchTableOp, messagePortTransport, methodOf, opKeyOf, registerLocalPeer, removeLocalPeer } from "@powerhousedao/reactor";
3
3
  import { KeyedListeners, KeyedListeners as KeyedListeners$1, Listeners, Listeners as Listeners$1, MessageRouter, RPC_PROTOCOL_VERSION, RPC_PROTOCOL_VERSION as RPC_PROTOCOL_VERSION$1, ReactorHostServer, ReactorHostServer as ReactorHostServer$1, RpcCorrelator, SubscriptionStore, SubscriptionStore as SubscriptionStore$1, createCorrelatedSubscriptions, createCorrelatedSubscriptions as createCorrelatedSubscriptions$1, createPortTransport, createPortTransport as createPortTransport$1, createReactorClientProxy, createReactorClientProxy as createReactorClientProxy$1, fromErrorInfo, fromErrorInfo as fromErrorInfo$1, hostResponder, hostResponder as hostResponder$1, toErrorInfo } from "@powerhousedao/reactor/rpc";
4
- import { rewritePackageSource } from "@powerhousedao/shared/connect";
4
+ import { init, parse } from "es-module-lexer";
5
5
  //#region src/rpc/op-channel.ts
6
6
  const RPC_DEFAULT_TIMEOUT_MS = 3e4;
7
7
  function toVoid(promise) {
@@ -881,7 +881,174 @@ var ReactorHost = class {
881
881
  }
882
882
  };
883
883
  //#endregion
884
+ //#region src/rpc/module-graph.ts
885
+ /** A bare specifier's URL in the shared table: an exact entry, else the longest trailing-slash prefix, as an import map does. */
886
+ function resolveSharedSpecifier(specifier, imports) {
887
+ if (Object.hasOwn(imports, specifier)) return imports[specifier];
888
+ let best;
889
+ for (const key of Object.keys(imports)) if (key.endsWith("/") && specifier.startsWith(key) && (best === void 0 || key.length > best.length)) best = key;
890
+ return best === void 0 ? void 0 : imports[best] + specifier.slice(best.length);
891
+ }
892
+ function isRelative(specifier) {
893
+ return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
894
+ }
895
+ function isUrl(specifier) {
896
+ return /^[a-z][a-z0-9+.-]*:/i.test(specifier);
897
+ }
898
+ async function fetchModuleSource(url) {
899
+ const response = await fetch(url);
900
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
901
+ return response.text();
902
+ }
903
+ function blobModuleUrl(source) {
904
+ return URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
905
+ }
906
+ var ModuleGraph = class {
907
+ sharedImports;
908
+ fetchSource;
909
+ createModuleUrl;
910
+ warn;
911
+ parsed = /* @__PURE__ */ new Map();
912
+ built = /* @__PURE__ */ new Map();
913
+ constructor(options = {}) {
914
+ this.sharedImports = options.sharedImports ?? {};
915
+ this.fetchSource = options.fetchSource ?? fetchModuleSource;
916
+ this.createModuleUrl = options.createModuleUrl ?? blobModuleUrl;
917
+ this.warn = options.warn ?? ((message) => console.warn(message));
918
+ }
919
+ /** The URL to import in place of `entryUrl`; `entryUrl` itself when nothing needed a rewrite. */
920
+ async resolve(entryUrl) {
921
+ const modules = await this.collect(entryUrl);
922
+ this.assertMapped(entryUrl, modules);
923
+ const rewrite = this.needsRewrite(modules);
924
+ this.assertAcyclic(entryUrl, modules, rewrite);
925
+ return this.build(entryUrl, modules, rewrite);
926
+ }
927
+ async collect(entryUrl) {
928
+ const modules = /* @__PURE__ */ new Map();
929
+ const seen = /* @__PURE__ */ new Set();
930
+ const visit = async (url) => {
931
+ if (seen.has(url)) return;
932
+ seen.add(url);
933
+ const module = await this.parse(url);
934
+ modules.set(url, module);
935
+ await Promise.all(module.deps.map(visit));
936
+ };
937
+ await visit(entryUrl);
938
+ return modules;
939
+ }
940
+ parse(url) {
941
+ let pending = this.parsed.get(url);
942
+ if (!pending) {
943
+ pending = this.readModule(url);
944
+ pending.catch(() => this.parsed.delete(url));
945
+ this.parsed.set(url, pending);
946
+ }
947
+ return pending;
948
+ }
949
+ async readModule(url) {
950
+ const source = await this.fetchSource(url);
951
+ await init;
952
+ const [imports] = parse(source, url);
953
+ const deps = [];
954
+ const bare = [];
955
+ for (const specifier of imports) {
956
+ if (specifier.d === -2) continue;
957
+ const name = specifier.n;
958
+ if (name === void 0) {
959
+ this.warn(`[module-graph] ${url} has a dynamic import with a computed specifier; it is left as is`);
960
+ continue;
961
+ }
962
+ if (isRelative(name)) deps.push(new URL(name, url).href);
963
+ else if (!isUrl(name)) bare.push(name);
964
+ }
965
+ return {
966
+ url,
967
+ source,
968
+ imports,
969
+ deps: [...new Set(deps)],
970
+ bare
971
+ };
972
+ }
973
+ assertAcyclic(entryUrl, modules, rewrite) {
974
+ const state = /* @__PURE__ */ new Map();
975
+ const stack = [];
976
+ const visit = (url) => {
977
+ const seen = state.get(url);
978
+ if (seen === "done") return;
979
+ if (seen === "visiting") {
980
+ const cycle = [...stack.slice(stack.indexOf(url)), url];
981
+ throw new Error(`Can't load ${entryUrl} in the worker: its modules import each other (${cycle.join(" -> ")})`);
982
+ }
983
+ state.set(url, "visiting");
984
+ stack.push(url);
985
+ for (const dep of modules.get(url).deps) if (rewrite.has(dep)) visit(dep);
986
+ stack.pop();
987
+ state.set(url, "done");
988
+ };
989
+ for (const url of [entryUrl, ...rewrite]) if (rewrite.has(url)) visit(url);
990
+ }
991
+ assertMapped(entryUrl, modules) {
992
+ for (const module of modules.values()) for (const name of module.bare) if (resolveSharedSpecifier(name, this.sharedImports) === void 0) throw new Error(`Can't load ${entryUrl} in the worker: ${module.url} imports "${name}", which the host doesn't share with the worker`);
993
+ }
994
+ needsRewrite(modules) {
995
+ const importers = /* @__PURE__ */ new Map();
996
+ for (const module of modules.values()) for (const dep of module.deps) importers.set(dep, [...importers.get(dep) ?? [], module.url]);
997
+ const rewrite = /* @__PURE__ */ new Set();
998
+ const queue = [...modules.values()].filter((module) => module.bare.length > 0).map((module) => module.url);
999
+ while (queue.length > 0) {
1000
+ const url = queue.pop();
1001
+ if (rewrite.has(url)) continue;
1002
+ rewrite.add(url);
1003
+ queue.push(...importers.get(url) ?? []);
1004
+ }
1005
+ return rewrite;
1006
+ }
1007
+ build(url, modules, rewrite) {
1008
+ if (!rewrite.has(url)) return Promise.resolve(url);
1009
+ let pending = this.built.get(url);
1010
+ if (!pending) {
1011
+ pending = this.rewrite(modules.get(url), modules, rewrite);
1012
+ pending.catch(() => this.built.delete(url));
1013
+ this.built.set(url, pending);
1014
+ }
1015
+ return pending;
1016
+ }
1017
+ async rewrite(module, modules, rewrite) {
1018
+ const depUrls = /* @__PURE__ */ new Map();
1019
+ await Promise.all(module.deps.map(async (dep) => {
1020
+ depUrls.set(dep, await this.build(dep, modules, rewrite));
1021
+ }));
1022
+ let out = "";
1023
+ let last = 0;
1024
+ for (const specifier of module.imports) {
1025
+ const name = specifier.n;
1026
+ if (specifier.d === -2 || name === void 0 || isUrl(name)) continue;
1027
+ const target = isRelative(name) ? depUrls.get(new URL(name, module.url).href) : resolveSharedSpecifier(name, this.sharedImports);
1028
+ const replacement = specifier.d > -1 ? JSON.stringify(target) : target;
1029
+ out += module.source.slice(last, specifier.s) + replacement;
1030
+ last = specifier.e;
1031
+ }
1032
+ return this.createModuleUrl(out + module.source.slice(last));
1033
+ }
1034
+ };
1035
+ //#endregion
884
1036
  //#region src/rpc/worker-package-loader.ts
1037
+ /** One line for a failed load: the package, its URL and why. */
1038
+ function describeLoadFailure(failure) {
1039
+ const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
1040
+ return `${failure.name} (${failure.url}): ${reason}`;
1041
+ }
1042
+ function summarize(results) {
1043
+ const types = /* @__PURE__ */ new Set();
1044
+ const failures = [];
1045
+ for (const result of results) if (result.status === "replaced") for (const type of result.types) types.add(type);
1046
+ else if (result.status === "failed") failures.push(result.failure);
1047
+ return {
1048
+ types: [...types],
1049
+ failures
1050
+ };
1051
+ }
885
1052
  const SOURCE_KEY_PREFIX = "src:";
886
1053
  function packageName(key) {
887
1054
  if (key.startsWith(SOURCE_KEY_PREFIX)) return key.slice(4);
@@ -918,13 +1085,12 @@ var WorkerPackageLoader = class {
918
1085
  cdnUrl;
919
1086
  importPackage;
920
1087
  resolvePackages;
921
- sharedImports;
922
- importSource;
1088
+ moduleGraph;
923
1089
  modulesByKey = /* @__PURE__ */ new Map();
924
1090
  manifestsByType = /* @__PURE__ */ new Map();
925
1091
  keysBySource = /* @__PURE__ */ new Map();
926
1092
  manifestTypesBySource = /* @__PURE__ */ new Map();
927
- loadedSpecs = /* @__PURE__ */ new Set();
1093
+ loadedUrls = /* @__PURE__ */ new Map();
928
1094
  failures = [];
929
1095
  pendingLoads = /* @__PURE__ */ new Map();
930
1096
  generationBySource = /* @__PURE__ */ new Map();
@@ -932,8 +1098,12 @@ var WorkerPackageLoader = class {
932
1098
  constructor(options) {
933
1099
  this.cdnUrl = options.cdnUrl.replace(/\/$/, "");
934
1100
  this.importPackage = options.importPackage;
935
- this.sharedImports = options.sharedImports;
936
- this.importSource = options.importSource;
1101
+ this.moduleGraph = new ModuleGraph({
1102
+ sharedImports: options.sharedImports,
1103
+ fetchSource: options.fetchSource,
1104
+ createModuleUrl: options.createModuleUrl,
1105
+ warn: options.warn
1106
+ });
937
1107
  const registryClient = new RegistryClient(options.cdnUrl);
938
1108
  this.resolvePackages = options.resolvePackages ?? ((documentType) => registryClient.getPackagesByDocumentType(documentType));
939
1109
  }
@@ -941,6 +1111,10 @@ var WorkerPackageLoader = class {
941
1111
  await Promise.all([...new Set(specs)].map((spec) => this.loadPackage(spec)));
942
1112
  return this.models;
943
1113
  }
1114
+ /** Loads registry packages added or updated after boot; returns the types whose modules changed, and the failures. */
1115
+ async updatePackages(specs) {
1116
+ return summarize(await Promise.all([...new Set(specs)].map((spec) => this.loadPackage(spec))));
1117
+ }
944
1118
  /** Loads URL-addressed packages (local project packages). Idempotent. */
945
1119
  async loadSources(sources) {
946
1120
  await Promise.all(sources.map((source) => this.loadFromUrl(sourceKey(source), source.url)));
@@ -954,15 +1128,7 @@ var WorkerPackageLoader = class {
954
1128
  * by a newer reload of the same source contributes nothing.
955
1129
  */
956
1130
  async reloadSources(sources) {
957
- const results = await Promise.all(sources.map((source) => this.replaceSource(sourceKey(source), source.url)));
958
- const types = /* @__PURE__ */ new Set();
959
- const failures = [];
960
- for (const result of results) if (result.status === "replaced") for (const type of result.types) types.add(type);
961
- else if (result.status === "failed") failures.push(result.failure);
962
- return {
963
- types: [...types],
964
- failures
965
- };
1131
+ return summarize(await Promise.all(sources.map((source) => this.replaceSource(sourceKey(source), source.url))));
966
1132
  }
967
1133
  async load(documentType) {
968
1134
  const existing = this.latestForType(documentType);
@@ -998,17 +1164,20 @@ var WorkerPackageLoader = class {
998
1164
  const cause = failures.length === 1 ? failures[0].error : new AggregateError(failures.map((failure) => failure.error));
999
1165
  return new Error(`Failed to import package(s) [${packageNames.join(", ")}] for document model: ${documentType}`, { cause });
1000
1166
  }
1001
- async loadPackage(spec) {
1167
+ loadPackage(spec) {
1002
1168
  const name = packageName(spec);
1003
- const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;
1004
- await this.loadFromUrl(spec, url);
1005
- }
1006
- loadFromUrl(key, url) {
1007
- if (this.loadedSpecs.has(key)) return Promise.resolve();
1008
- let pending = this.pendingLoads.get(key);
1169
+ const url = `${this.cdnUrl}/${spec}/browser/document-models/index.js`;
1170
+ const loaded = this.loadedUrls.get(name);
1171
+ if (loaded !== void 0 && (spec === name || loaded === url)) return Promise.resolve({ status: "unchanged" });
1172
+ return this.loadFromUrl(name, url, loaded !== void 0);
1173
+ }
1174
+ loadFromUrl(key, url, replace = false) {
1175
+ if (!replace && this.loadedUrls.has(key)) return Promise.resolve({ status: "unchanged" });
1176
+ const pendingKey = `${key} ${url}`;
1177
+ let pending = this.pendingLoads.get(pendingKey);
1009
1178
  if (!pending) {
1010
- pending = this.replaceSource(key, url).finally(() => this.pendingLoads.delete(key)).then(() => void 0);
1011
- this.pendingLoads.set(key, pending);
1179
+ pending = this.replaceSource(key, url).finally(() => this.pendingLoads.delete(pendingKey));
1180
+ this.pendingLoads.set(pendingKey, pending);
1012
1181
  }
1013
1182
  return pending;
1014
1183
  }
@@ -1017,7 +1186,7 @@ var WorkerPackageLoader = class {
1017
1186
  this.generationBySource.set(key, generation);
1018
1187
  let namespace;
1019
1188
  try {
1020
- namespace = await this.importNamespace(url);
1189
+ namespace = await this.importNamespace(key, url);
1021
1190
  } catch (error) {
1022
1191
  if (this.generationBySource.get(key) !== generation) return { status: "stale" };
1023
1192
  const failure = {
@@ -1040,20 +1209,15 @@ var WorkerPackageLoader = class {
1040
1209
  }
1041
1210
  for (const type of this.manifestTypesBySource.get(key) ?? []) this.manifestsByType.delete(type);
1042
1211
  for (const added of this.registerNamespace(key, namespace)) types.add(added);
1043
- this.loadedSpecs.add(key);
1212
+ this.loadedUrls.set(key, url);
1044
1213
  return {
1045
1214
  status: "replaced",
1046
1215
  types
1047
1216
  };
1048
1217
  }
1049
- async importNamespace(url) {
1050
- const source = this.sharedImports !== void 0 && Object.keys(this.sharedImports).length > 0 ? await (await fetch(url)).text() : void 0;
1051
- const rewritten = source !== void 0 ? rewritePackageSource(source, url, this.sharedImports) : source;
1052
- if (rewritten !== void 0 && rewritten !== source) {
1053
- if (!this.importSource) throw new Error("importSource is required to load a package that imports shared deps");
1054
- return this.importSource(rewritten);
1055
- }
1056
- return this.importPackage(url);
1218
+ async importNamespace(key, url) {
1219
+ if (key.startsWith(SOURCE_KEY_PREFIX)) return this.importPackage(url);
1220
+ return this.importPackage(await this.moduleGraph.resolve(url));
1057
1221
  }
1058
1222
  /** Registers a namespace as the key's whole contribution; returns its module types. */
1059
1223
  registerNamespace(key, namespace) {
@@ -1079,6 +1243,6 @@ function sourceKey(source) {
1079
1243
  return `${SOURCE_KEY_PREFIX}${source.name}`;
1080
1244
  }
1081
1245
  //#endregion
1082
- export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, RETIRED_WORKER_RELOAD_REASON, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, dispatchInspectorOp, dispatchSyncInspectionOp, fromErrorInfo, hostResponder, isFingerprintMismatchReload, isSyncInspectionOp, localSyncPeerHandlers, opChannel, postReactorIdentity, sendAdoptSyncPeer, sendRemoveSyncPeer, toErrorInfo, toVoid };
1246
+ export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, ModuleGraph, RETIRED_WORKER_RELOAD_REASON, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, describeLoadFailure, dispatchInspectorOp, dispatchSyncInspectionOp, fromErrorInfo, hostResponder, isFingerprintMismatchReload, isSyncInspectionOp, localSyncPeerHandlers, opChannel, postReactorIdentity, resolveSharedSpecifier, sendAdoptSyncPeer, sendRemoveSyncPeer, toErrorInfo, toVoid };
1083
1247
 
1084
1248
  //# sourceMappingURL=index.js.map