{
  "version": 3,
  "sources": ["../../../../../node_modules/whatwg-mimetype/lib/utils.js", "../../../../../node_modules/whatwg-mimetype/lib/mime-type-parameters.js", "../../../../../node_modules/whatwg-mimetype/lib/parser.js", "../../../../../node_modules/whatwg-mimetype/lib/serializer.js", "../../../../../node_modules/whatwg-mimetype/lib/mime-type.js", "../../src/document/components/chrome/shared/UpsellModal/utils/fileLimitUpsellModals.ts", "../../src/web/pages/project/lib/UploadUserAssetsService.ts", "../../src/web/lib/LimitedRunner.ts", "../../src/web/lib/BatchAssetUploader.ts", "../../src/document/models/CanvasTree/traits/forms/formConfig.ts", "../../src/modules/compilerContractVersion.ts", "../../../../../node_modules/es-module-lexer/dist/lexer.js", "../../src/modules/rewriteRelativeImports.ts", "../../../../../node_modules/mrmime/index.mjs", "../../src/document/components/chrome/properties/utils/allowedFileTypes.ts", "../../src/utils/entries.ts", "../../src/utils/getFirstRepeaterItemId.ts", "../../src/code-editor/formatting.ts", "../../src/modules/getCodeComponentModuleTypeSlashNamesInScope.ts", "../../src/modules/ModulesDivergenceReporter.ts", "../../src/modules/ModulesStorage.ts", "../../src/web/lib/batchUploaderUtils.tsx", "../../src/document/components/chrome/contentManagement/utils/validateControlPropReference.ts", "../../src/document/models/CanvasTree/traits/utils/reducePositionType.ts"],
  "sourcesContent": ["\"use strict\";\n\nexports.removeLeadingAndTrailingHTTPWhitespace = string => {\n  return string.replace(/^[ \\t\\n\\r]+/u, \"\").replace(/[ \\t\\n\\r]+$/u, \"\");\n};\n\nexports.removeTrailingHTTPWhitespace = string => {\n  return string.replace(/[ \\t\\n\\r]+$/u, \"\");\n};\n\nexports.isHTTPWhitespaceChar = char => {\n  return char === \" \" || char === \"\\t\" || char === \"\\n\" || char === \"\\r\";\n};\n\nexports.solelyContainsHTTPTokenCodePoints = string => {\n  return /^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u.test(string);\n};\n\nexports.soleyContainsHTTPQuotedStringTokenCodePoints = string => {\n  return /^[\\t\\u0020-\\u007E\\u0080-\\u00FF]*$/u.test(string);\n};\n\nexports.asciiLowercase = string => {\n  return string.replace(/[A-Z]/ug, l => l.toLowerCase());\n};\n\n// This variant only implements it with the extract-value flag set.\nexports.collectAnHTTPQuotedString = (input, position) => {\n  let value = \"\";\n\n  position++;\n\n  while (true) {\n    while (position < input.length && input[position] !== \"\\\"\" && input[position] !== \"\\\\\") {\n      value += input[position];\n      ++position;\n    }\n\n    if (position >= input.length) {\n      break;\n    }\n\n    const quoteOrBackslash = input[position];\n    ++position;\n\n    if (quoteOrBackslash === \"\\\\\") {\n      if (position >= input.length) {\n        value += \"\\\\\";\n        break;\n      }\n\n      value += input[position];\n      ++position;\n    } else {\n      break;\n    }\n  }\n\n  return [value, position];\n};\n", "\"use strict\";\nconst {\n  asciiLowercase,\n  solelyContainsHTTPTokenCodePoints,\n  soleyContainsHTTPQuotedStringTokenCodePoints\n} = require(\"./utils.js\");\n\nmodule.exports = class MIMETypeParameters {\n  constructor(map) {\n    this._map = map;\n  }\n\n  get size() {\n    return this._map.size;\n  }\n\n  get(name) {\n    name = asciiLowercase(String(name));\n    return this._map.get(name);\n  }\n\n  has(name) {\n    name = asciiLowercase(String(name));\n    return this._map.has(name);\n  }\n\n  set(name, value) {\n    name = asciiLowercase(String(name));\n    value = String(value);\n\n    if (!solelyContainsHTTPTokenCodePoints(name)) {\n      throw new Error(`Invalid MIME type parameter name \"${name}\": only HTTP token code points are valid.`);\n    }\n    if (!soleyContainsHTTPQuotedStringTokenCodePoints(value)) {\n      throw new Error(`Invalid MIME type parameter value \"${value}\": only HTTP quoted-string token code points are ` +\n                      `valid.`);\n    }\n\n    return this._map.set(name, value);\n  }\n\n  clear() {\n    this._map.clear();\n  }\n\n  delete(name) {\n    name = asciiLowercase(String(name));\n    return this._map.delete(name);\n  }\n\n  forEach(callbackFn, thisArg) {\n    this._map.forEach(callbackFn, thisArg);\n  }\n\n  keys() {\n    return this._map.keys();\n  }\n\n  values() {\n    return this._map.values();\n  }\n\n  entries() {\n    return this._map.entries();\n  }\n\n  [Symbol.iterator]() {\n    return this._map[Symbol.iterator]();\n  }\n};\n", "\"use strict\";\nconst {\n  removeLeadingAndTrailingHTTPWhitespace,\n  removeTrailingHTTPWhitespace,\n  isHTTPWhitespaceChar,\n  solelyContainsHTTPTokenCodePoints,\n  soleyContainsHTTPQuotedStringTokenCodePoints,\n  asciiLowercase,\n  collectAnHTTPQuotedString\n} = require(\"./utils.js\");\n\nmodule.exports = input => {\n  input = removeLeadingAndTrailingHTTPWhitespace(input);\n\n  let position = 0;\n  let type = \"\";\n  while (position < input.length && input[position] !== \"/\") {\n    type += input[position];\n    ++position;\n  }\n\n  if (type.length === 0 || !solelyContainsHTTPTokenCodePoints(type)) {\n    return null;\n  }\n\n  if (position >= input.length) {\n    return null;\n  }\n\n  // Skips past \"/\"\n  ++position;\n\n  let subtype = \"\";\n  while (position < input.length && input[position] !== \";\") {\n    subtype += input[position];\n    ++position;\n  }\n\n  subtype = removeTrailingHTTPWhitespace(subtype);\n\n  if (subtype.length === 0 || !solelyContainsHTTPTokenCodePoints(subtype)) {\n    return null;\n  }\n\n  const mimeType = {\n    type: asciiLowercase(type),\n    subtype: asciiLowercase(subtype),\n    parameters: new Map()\n  };\n\n  while (position < input.length) {\n    // Skip past \";\"\n    ++position;\n\n    while (isHTTPWhitespaceChar(input[position])) {\n      ++position;\n    }\n\n    let parameterName = \"\";\n    while (position < input.length && input[position] !== \";\" && input[position] !== \"=\") {\n      parameterName += input[position];\n      ++position;\n    }\n    parameterName = asciiLowercase(parameterName);\n\n    if (position < input.length) {\n      if (input[position] === \";\") {\n        continue;\n      }\n\n      // Skip past \"=\"\n      ++position;\n    }\n\n    let parameterValue = null;\n    if (input[position] === \"\\\"\") {\n      [parameterValue, position] = collectAnHTTPQuotedString(input, position);\n\n      while (position < input.length && input[position] !== \";\") {\n        ++position;\n      }\n    } else {\n      parameterValue = \"\";\n      while (position < input.length && input[position] !== \";\") {\n        parameterValue += input[position];\n        ++position;\n      }\n\n      parameterValue = removeTrailingHTTPWhitespace(parameterValue);\n\n      if (parameterValue === \"\") {\n        continue;\n      }\n    }\n\n    if (parameterName.length > 0 &&\n        solelyContainsHTTPTokenCodePoints(parameterName) &&\n        soleyContainsHTTPQuotedStringTokenCodePoints(parameterValue) &&\n        !mimeType.parameters.has(parameterName)) {\n      mimeType.parameters.set(parameterName, parameterValue);\n    }\n  }\n\n  return mimeType;\n};\n", "\"use strict\";\nconst { solelyContainsHTTPTokenCodePoints } = require(\"./utils.js\");\n\nmodule.exports = mimeType => {\n  let serialization = `${mimeType.type}/${mimeType.subtype}`;\n\n  if (mimeType.parameters.size === 0) {\n    return serialization;\n  }\n\n  for (let [name, value] of mimeType.parameters) {\n    serialization += \";\";\n    serialization += name;\n    serialization += \"=\";\n\n    if (!solelyContainsHTTPTokenCodePoints(value) || value.length === 0) {\n      value = value.replace(/([\"\\\\])/ug, \"\\\\$1\");\n      value = `\"${value}\"`;\n    }\n\n    serialization += value;\n  }\n\n  return serialization;\n};\n", "\"use strict\";\nconst MIMETypeParameters = require(\"./mime-type-parameters.js\");\nconst parse = require(\"./parser.js\");\nconst serialize = require(\"./serializer.js\");\nconst {\n  asciiLowercase,\n  solelyContainsHTTPTokenCodePoints\n} = require(\"./utils.js\");\n\nmodule.exports = class MIMEType {\n  constructor(string) {\n    string = String(string);\n    const result = parse(string);\n    if (result === null) {\n      throw new Error(`Could not parse MIME type string \"${string}\"`);\n    }\n\n    this._type = result.type;\n    this._subtype = result.subtype;\n    this._parameters = new MIMETypeParameters(result.parameters);\n  }\n\n  static parse(string) {\n    try {\n      return new this(string);\n    } catch (e) {\n      return null;\n    }\n  }\n\n  get essence() {\n    return `${this.type}/${this.subtype}`;\n  }\n\n  get type() {\n    return this._type;\n  }\n\n  set type(value) {\n    value = asciiLowercase(String(value));\n\n    if (value.length === 0) {\n      throw new Error(\"Invalid type: must be a non-empty string\");\n    }\n    if (!solelyContainsHTTPTokenCodePoints(value)) {\n      throw new Error(`Invalid type ${value}: must contain only HTTP token code points`);\n    }\n\n    this._type = value;\n  }\n\n  get subtype() {\n    return this._subtype;\n  }\n\n  set subtype(value) {\n    value = asciiLowercase(String(value));\n\n    if (value.length === 0) {\n      throw new Error(\"Invalid subtype: must be a non-empty string\");\n    }\n    if (!solelyContainsHTTPTokenCodePoints(value)) {\n      throw new Error(`Invalid subtype ${value}: must contain only HTTP token code points`);\n    }\n\n    this._subtype = value;\n  }\n\n  get parameters() {\n    return this._parameters;\n  }\n\n  toString() {\n    // The serialize function works on both \"MIME type records\" (i.e. the results of parse) and on this class, since\n    // this class's interface is identical.\n    return serialize(this);\n  }\n\n  isJavaScript({ prohibitParameters = false } = {}) {\n    switch (this._type) {\n      case \"text\": {\n        switch (this._subtype) {\n          case \"ecmascript\":\n          case \"javascript\":\n          case \"javascript1.0\":\n          case \"javascript1.1\":\n          case \"javascript1.2\":\n          case \"javascript1.3\":\n          case \"javascript1.4\":\n          case \"javascript1.5\":\n          case \"jscript\":\n          case \"livescript\":\n          case \"x-ecmascript\":\n          case \"x-javascript\": {\n            return !prohibitParameters || this._parameters.size === 0;\n          }\n          default: {\n            return false;\n          }\n        }\n      }\n      case \"application\": {\n        switch (this._subtype) {\n          case \"ecmascript\":\n          case \"javascript\":\n          case \"x-ecmascript\":\n          case \"x-javascript\": {\n            return !prohibitParameters || this._parameters.size === 0;\n          }\n          default: {\n            return false;\n          }\n        }\n      }\n      default: {\n        return false;\n      }\n    }\n  }\n  isXML() {\n    return (this._subtype === \"xml\" && (this._type === \"text\" || this._type === \"application\")) ||\n           this._subtype.endsWith(\"+xml\");\n  }\n  isHTML() {\n    return this._subtype === \"html\" && this._type === \"text\";\n  }\n};\n", "import { getHighestTierSiteUpsell } from \"@framerjs/app-shared\"\nimport { UpsellType } from \"@framerjs/events\"\nimport { assert } from \"@framerjs/shared\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport { UpsellFeature } from \"document/components/chrome/siteSettings/Plans/Stripe/utils/upsell.ts\"\nimport { ModalType } from \"document/utils/ModalType.ts\"\nimport { MEGABYTE } from \"web/lib/upload.ts\"\n\nexport function showFileTooLargeUpsellModal(engine: BaseEngine, size: number) {\n\tif (engine.stores.projectStore.projectLicenseType === getHighestTierSiteUpsell()) {\n\t\treturn engine.stores.modalStore.set({\n\t\t\ttype: ModalType.UpsellEnterprise,\n\t\t\tsource: \"upsell\",\n\t\t\tdescription:\n\t\t\t\t\"Sign up for an Enterprise plan to increase your file upload limit to 150MB and unlock other powerful features that help scale your site.\",\n\t\t\tupsell: UpsellType.fileLimitEnterpriseUpsell,\n\t\t\tupsellFeatures: [\n\t\t\t\t\"Advanced Permissions\",\n\t\t\t\t\"Custom Limits\",\n\t\t\t\t\"Custom Hosting\",\n\t\t\t\t\"Custom Proxy Support\",\n\t\t\t\t\"Enterprise Security\",\n\t\t\t\t\"Dedicated Support\",\n\t\t\t],\n\t\t})\n\t}\n\n\tconst fileUploadLimitInMB = engine.stores.projectStore.resourceLimits?.fileUploadLimitInMB\n\tassert(typeof fileUploadLimitInMB === \"number\", \"fileUploadLimitInMB is not a number\")\n\tconst limitInMB = fileUploadLimitInMB.toLocaleString() + \"MB\"\n\tconst sizeInMB =\n\t\t(size / MEGABYTE).toLocaleString(undefined, {\n\t\t\tminimumFractionDigits: 0,\n\t\t\tmaximumFractionDigits: 1,\n\t\t}) + \"MB\"\n\treturn engine.stores.modalStore.set({\n\t\tsource: \"upsell\",\n\t\ttype: ModalType.UpsellFeature,\n\t\tupsellFeature: UpsellFeature.fileUploadLimitInMB,\n\t\ttitle: \"File Upload Limit\",\n\t\tdescription: `Your current plan limits file uploads to ${limitInMB}, and you\u2019re trying to upload a file that\u2019s ${sizeInMB}. Upgrade your site to increase the limit and upload your file.`,\n\t})\n}\n", "import type { Asset } from \"@framerjs/assets\"\nimport { createAbsoluteAssetURLFromAsset, getAssetFilename } from \"@framerjs/assets\"\nimport { assert, getLogger } from \"@framerjs/shared\"\nimport { noop } from \"@framerjs/shared/src/noop.ts\"\nimport type { ImageSize } from \"web/lib/images/image.ts\"\nimport * as supportedImages from \"web/lib/images/supportedFormats.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { measureVideo } from \"web/lib/videos/measureVideo.ts\"\nimport type {\n\tAssetBatchUploadService,\n\tAssetUploadResult,\n\tFileUploadResult,\n\tImageUploadResult,\n\tVideoUploadResult,\n\tUploadOptions,\n} from \"./UploadService.ts\"\nimport { createService } from \"./createService.ts\"\nimport { svgHasTooLargeRasterImages } from \"./svg.ts\"\nimport type { API } from \"./useAPI.ts\"\n\nconst log = getLogger(\"UploadUserAssetsService\")\n\nfunction imageAssetToImageSize(asset: Asset): ImageSize {\n\tconst naturalWidth = asset.properties?.image?.width\n\tconst naturalHeight = asset.properties?.image?.height\n\n\tassert(naturalWidth !== undefined && naturalHeight !== undefined, \"Image asset missing width/height\")\n\n\treturn { naturalWidth, naturalHeight }\n}\n\n/**\n * User-scoped asset uploads for agent chat attachments (see `API.uploadUserAsset`),\n * which then register a project ownership row for the open project.\n * `uploadFile` and `uploadAssetByURL` exist for `AssetBatchUploadService` but throw.\n */\nclass UploadUserAssetsService implements AssetBatchUploadService {\n\tconstructor(private readonly api: API) {}\n\n\tasync uploadImage(\n\t\tfile: File,\n\t\t{ silent = false, maxFileSize, onExceedsCustomMaxSize }: UploadOptions = {},\n\t): Promise<ImageUploadResult | undefined> {\n\t\ttry {\n\t\t\tconst showToast: typeof toast = silent ? noop : value => toast(value)\n\n\t\t\tif (!supportedImages.mimeTypes.includes(file.type)) {\n\t\t\t\tshowToast({\n\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\ticon: \"error\",\n\t\t\t\t\tduration: Infinity,\n\t\t\t\t\tprimaryText: \"Unsupported image type.\",\n\t\t\t\t\tsecondaryText: \"Try png or jpg.\",\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (file.type === \"image/svg+xml\") {\n\t\t\t\tconst svgText = await file.text()\n\t\t\t\tif (svgHasTooLargeRasterImages(svgText)) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst asset = await this.api.uploadUserAsset(file, {\n\t\t\t\tmaxFileSize,\n\t\t\t\tonExceedsCustomMaxSize,\n\t\t\t\tonToast: showToast,\n\t\t\t})\n\n\t\t\tif (!asset) return\n\n\t\t\treturn {\n\t\t\t\ttype: \"image\",\n\t\t\t\tasset,\n\t\t\t\tfilename: getAssetFilename(asset),\n\t\t\t\toriginalFilename: asset.name,\n\t\t\t\turl: createAbsoluteAssetURLFromAsset(asset),\n\t\t\t\timageSize: imageAssetToImageSize(asset),\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (silent) {\n\t\t\t\tthrow err\n\t\t\t} else {\n\t\t\t\ttoast({\n\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\ticon: \"error\",\n\t\t\t\t\tduration: Infinity,\n\t\t\t\t\tprimaryText: \"Couldn\u2019t add image.\",\n\t\t\t\t\tsecondaryText: \"It may be too large.\",\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t})\n\t\t\t\tlog.reportError(err, {\n\t\t\t\t\tfileName: file.name,\n\t\t\t\t\tfileSize: file.size,\n\t\t\t\t\tfileType: file.type,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tasync uploadVideo(\n\t\tfile: File,\n\t\t{ silent = false, maxFileSize, onExceedsCustomMaxSize }: UploadOptions = {},\n\t): Promise<VideoUploadResult | undefined> {\n\t\ttry {\n\t\t\tconst showToast: typeof toast = silent ? noop : value => toast(value)\n\n\t\t\tconst [videoDimensions, asset] = await Promise.all([\n\t\t\t\twithTimeout(measureVideo(file), 10_000, \"Measuring the video took more than 10 seconds\"),\n\t\t\t\tthis.api.uploadUserAsset(file, { maxFileSize, onExceedsCustomMaxSize, onToast: showToast }),\n\t\t\t])\n\n\t\t\tif (!asset) return\n\n\t\t\treturn {\n\t\t\t\ttype: \"video\",\n\t\t\t\tasset,\n\t\t\t\tfilename: getAssetFilename(asset),\n\t\t\t\toriginalFilename: asset.name,\n\t\t\t\turl: createAbsoluteAssetURLFromAsset(asset),\n\t\t\t\tdimensions: videoDimensions,\n\t\t\t}\n\t\t} catch (err: unknown) {\n\t\t\tif (silent) {\n\t\t\t\tthrow err\n\t\t\t} else {\n\t\t\t\ttoast({\n\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\ticon: \"error\",\n\t\t\t\t\tduration: Infinity,\n\t\t\t\t\tprimaryText: \"Couldn't add video.\",\n\t\t\t\t\tsecondaryText: \"Please retry.\",\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t})\n\t\t\t\tlog.reportError(err, {\n\t\t\t\t\tfileName: file.name,\n\t\t\t\t\tfileSize: file.size,\n\t\t\t\t\tfileType: file.type,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\tasync uploadFile(_file: File, _options: UploadOptions = {}): Promise<FileUploadResult | undefined> {\n\t\tthrow new Error(\"UploadUserAssetsService.uploadFile is not supported; use uploadImage.\")\n\t}\n\n\tasync uploadAssetByURL(_url: string, _options: UploadOptions = {}): Promise<AssetUploadResult> {\n\t\tthrow new Error(\"UploadUserAssetsService.uploadAssetByURL is not supported; use uploadImage.\")\n\t}\n}\n\nconst { service: uploadUserAssetsService, resolve: resolveUploadUserAssetsService } =\n\tcreateService<UploadUserAssetsService>()\nexport { uploadUserAssetsService }\n\nexport function initUploadUserAssetsService(api: API): void {\n\tresolveUploadUserAssetsService(new UploadUserAssetsService(api))\n}\n\nfunction withTimeout<T>(promise: PromiseLike<T>, ms: number, error = \"timed out\"): PromiseLike<T> {\n\treturn new Promise((resolve, reject) => {\n\t\tsetTimeout(() => {\n\t\t\treject(Error(error))\n\t\t}, ms)\n\t\tpromise.then(resolve, reject)\n\t})\n}\n", "export class LimitedRunner {\n\t#active = 0\n\t#waiters: (() => void)[] = []\n\n\tconstructor(private readonly limit: number) {}\n\n\t/**\n\t * Run a task, waiting if the limit is reached.\n\t * signal is an optional AbortSignal that can be used to abort the task.\n\t */\n\tasync run<T>(task: () => PromiseLike<T>, signal?: AbortSignal): Promise<T> {\n\t\tif (this.#active === this.limit) {\n\t\t\tlet startPromise = new Promise<void>(resolve => {\n\t\t\t\tthis.#waiters.push(resolve)\n\t\t\t})\n\n\t\t\tif (signal) {\n\t\t\t\tstartPromise = Promise.race([startPromise, onAbortReject(signal)])\n\t\t\t}\n\n\t\t\tawait startPromise\n\t\t}\n\t\tthrowIfAborted(signal)\n\t\tthis.#active++\n\t\ttry {\n\t\t\tconst result = await task()\n\t\t\treturn result\n\t\t} finally {\n\t\t\tthis.#active--\n\t\t\tconst resolve = this.#waiters.shift()\n\t\t\tresolve?.()\n\t\t}\n\t}\n}\n\nconst signalPromiseCache = new WeakMap<AbortSignal, Promise<never>>()\n/**\n * Returns a promise that rejects when the signal is aborted.\n * The promise is cached so that multiple calls to this function with the same signal return the same promise.\n */\nfunction onAbortReject(signal: AbortSignal): Promise<never> {\n\tlet promise = signalPromiseCache.get(signal)\n\tif (!promise) {\n\t\tthrowIfAborted(signal)\n\t\tpromise = new Promise<never>((_resolve, reject) => {\n\t\t\tsignal.addEventListener(\n\t\t\t\t\"abort\",\n\t\t\t\t() => {\n\t\t\t\t\treject(signal.reason)\n\t\t\t\t},\n\t\t\t\t{ once: true },\n\t\t\t)\n\t\t})\n\t\tsignalPromiseCache.set(signal, promise)\n\t}\n\treturn promise\n}\n\nfunction throwIfAborted(signal?: AbortSignal) {\n\tif (signal?.aborted) {\n\t\tthrow signal.reason\n\t}\n}\n", "import { unhandledError } from \"@framerjs/shared\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport { showFileTooLargeUpsellModal } from \"document/components/chrome/shared/UpsellModal/utils/fileLimitUpsellModals.ts\"\nimport { isDefined, isPromiseFulfilled } from \"utils/typeChecks.ts\"\nimport { fileFromURL } from \"web/lib/fileFromURL.ts\"\nimport type { AssetBatchUploadService, AssetUploadResult } from \"web/pages/project/lib/UploadService.ts\"\nimport { uploadService } from \"web/pages/project/lib/UploadService.ts\"\nimport { uploadUserAssetsService } from \"web/pages/project/lib/UploadUserAssetsService.ts\"\nimport { LimitedRunner } from \"./LimitedRunner.ts\"\n\ntype BatchAssetUploaderOwnerType = \"project\" | \"user\"\n\n/**\n * Function that returns a promise.\n *\n * For postponing work by capturing it in a (async) function closure.\n */\nexport type Task<T> = () => Promise<T>\n\ninterface Upload {\n\t/** Task to delay the start of an upload */\n\ttask: Task<AssetUploadResult>\n\t/**\n\t * A running/completed upload, will be set when the task executes,\n\t * `undefined` when not yet started\n\t */\n\tresultPromise?: Promise<AssetUploadResult>\n}\n/**\n * Batch uploading of images from remote URLs, with observable progress and\n * concurrency limits. Combines equal URLs, so all callbacks will be called, but\n * only one upload happens.\n */\n\nexport class BatchAssetUploader {\n\t// Keys are URL strings or Files\n\tprotected uploads = new Map<string | File, Upload>()\n\n\t// State for this.status\n\tprivate completed = 0\n\tprivate failed = 0\n\n\t// State for this.statusUpdates()\n\tprivate generating = false\n\tprivate resolveStatusUpdate: (() => void) | undefined\n\n\tprivate limiter: LimitedRunner\n\tprivate silent: boolean\n\tprivate readonly assetUploadService: AssetBatchUploadService\n\tprivate readonly assetOwnerType: BatchAssetUploaderOwnerType\n\n\t/**\n\t * @param engine\n\t * @param options Optional options\n\t * @param options.concurrency Maximum number of assets uploaded at the same time. Default 5, set to `Infinity` for no limit\n\t * @param options.silent Hide (image) processing toasts, default `false`\n\t * @param options.assetOwnerType `\"project\"` (default) uses `uploadService` and optimistically inserts uploads into the\n\t *   project asset store. `\"user\"` uses `uploadUserAssetsService` and skips that step so user-scoped keys are not treated\n\t *   as project assets.\n\t */\n\tconstructor(\n\t\tprivate readonly engine: BaseEngine,\n\t\t{\n\t\t\tconcurrency = 5,\n\t\t\tsilent = false,\n\t\t\tassetOwnerType = \"project\",\n\t\t}: {\n\t\t\tconcurrency?: number\n\t\t\tsilent?: boolean\n\t\t\tassetOwnerType?: BatchAssetUploaderOwnerType\n\t\t} = {},\n\t) {\n\t\tthis.limiter = new LimitedRunner(concurrency)\n\t\tthis.silent = silent\n\t\tthis.assetOwnerType = assetOwnerType\n\t\tthis.assetUploadService = assetOwnerType === \"user\" ? uploadUserAssetsService : uploadService\n\t}\n\n\t/**\n\t * Start uploading an asset from a File or URL\n\t *\n\t * @param file `File` or URL of an asset\n\t * @returns Promise of an Asset\n\t */\n\tadd(file: string | File): Promise<AssetUploadResult> {\n\t\t// Create a task and immediately start it\n\t\treturn this.createTask(file, asset => asset)()\n\t}\n\n\t/**\n\t * Schedules an asset upload, making sure the same File/URL gets only uploaded once\n\t *\n\t * @param url URL of an asset\n\t * @param callback Callback called with an asset reference when the image is successfully uploaded\n\t * @returns Postponed task that should be executed to start the upload\n\t */\n\tcreateTask<T>(file: string | File, callback: (result: AssetUploadResult) => T): Task<T> {\n\t\tlet maybeUpload = this.uploads.get(file)\n\t\tif (!maybeUpload) {\n\t\t\tconst task = async (): Promise<AssetUploadResult> => {\n\t\t\t\ttry {\n\t\t\t\t\tif (typeof file === \"string\") {\n\t\t\t\t\t\tif (file.startsWith(\"data:\")) {\n\t\t\t\t\t\t\treturn await this.uploadFile(await fileFromURL(file, \"imported\"))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn await this.assetUploadService.uploadAssetByURL(file, {\n\t\t\t\t\t\t\tsilent: this.silent,\n\t\t\t\t\t\t\trefreshAssetService: false, // We do it ourselves\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\treturn await this.uploadFile(file)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.failed++\n\t\t\t\t\tthrow error\n\t\t\t\t} finally {\n\t\t\t\t\tthis.completed++\n\t\t\t\t\tthis.resolveStatusUpdate?.()\n\t\t\t\t}\n\t\t\t}\n\t\t\tmaybeUpload = { task }\n\t\t\tthis.uploads.set(file, maybeUpload)\n\t\t}\n\n\t\t// Capture in const so TypeScript does not think it can be undefined again below\n\t\tconst upload = maybeUpload\n\n\t\t// Make sure the upload only gets started once and the total is limited\n\t\t// in concurrency\n\t\treturn async () => {\n\t\t\tif (!upload.resultPromise) {\n\t\t\t\tupload.resultPromise = this.limiter.run(upload.task)\n\t\t\t\tthis.resolveStatusUpdate?.()\n\t\t\t}\n\t\t\tconst result = await upload.resultPromise\n\t\t\tif (this.assetOwnerType === \"project\") {\n\t\t\t\t// optimistically update the asset map, the consumer can later refresh the asset map but this will ensure assets\n\t\t\t\t// always appear in the asset map immediately\n\t\t\t\tthis.engine.stores.assetStore.assetService?.addAssets([result.asset])\n\t\t\t}\n\t\t\treturn callback(result)\n\t\t}\n\t}\n\n\t/**\n\t * Helper that will upload a file inspecting its type\n\t */\n\tprivate async uploadFile(file: File) {\n\t\tconst maxFileSize = this.engine.stores.projectStore.resourceLimits?.fileUploadLimitInMB ?? undefined\n\n\t\tconst uploadOptions = {\n\t\t\tsilent: this.silent,\n\t\t\tmaxFileSize,\n\t\t\tonExceedsCustomMaxSize: (size: number) => showFileTooLargeUpsellModal(this.engine, size),\n\t\t\trefreshAssetService: false, // We do it ourselves\n\t\t}\n\t\tlet result: AssetUploadResult | undefined\n\t\tif (file.type.startsWith(\"image/\")) {\n\t\t\tresult = await this.assetUploadService.uploadImage(file, uploadOptions)\n\t\t} else if (file.type.startsWith(\"video/\")) {\n\t\t\tresult = await this.assetUploadService.uploadVideo(file, uploadOptions)\n\t\t} else {\n\t\t\tresult = await uploadService.uploadFile(file, uploadOptions)\n\t\t}\n\t\tif (!result) throw Error(\"Failed to upload file\")\n\t\treturn result\n\t}\n\n\t/**\n\t * Running uploads, includes pending ones\n\t */\n\tprivate get active() {\n\t\treturn [...this.uploads.values()].map(({ resultPromise }) => resultPromise).filter(isDefined)\n\t}\n\n\t/**\n\t * Current status of the uploader.\n\t */\n\tget status() {\n\t\tconst { active, completed, failed } = this\n\t\treturn { started: active.length, completed, failed }\n\t}\n\n\t/**\n\t * [Async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator)\n\t * to observe status updates. Sends the initial status and then status\n\t * updates until completed.\n\t *\n\t * Usage:\n\t * `for await (const status of imageUploader.statusUpdates()) { \u2026 }`\n\t *\n\t * @throws Only one generator can be active, will throw otherwise\n\t */\n\tasync *statusUpdates() {\n\t\tif (this.generating) throw Error(\"`statusUpdates` is in use by another call\")\n\t\tthis.generating = true\n\t\tyield this.status // Initial status\n\t\t// NOTE: Dangerous, bugs in this class could cause an infinite loop\n\t\twhile (this.completed < this.active.length) {\n\t\t\tawait new Promise<void>(resolve => {\n\t\t\t\tthis.resolveStatusUpdate = () => {\n\t\t\t\t\tresolve()\n\t\t\t\t\tthis.resolveStatusUpdate = undefined\n\t\t\t\t}\n\t\t\t})\n\t\t\tyield this.status\n\t\t}\n\t\t// Refresh the assets\n\t\tawait this.engine.stores.assetStore.assetService?.refresh().catch(unhandledError)\n\t\tthis.generating = false\n\t}\n\n\t/**\n\t * @returns Results of all *active* uploads (excludes tasks that have not been started yet)\n\t */\n\tasync results(): Promise<AssetUploadResult[]> {\n\t\t// Wait for all promises to settle, regardless of whether they fail or not\n\t\tconst results = await Promise.allSettled(this.active).then(res =>\n\t\t\tres.filter(isPromiseFulfilled).map(filteredRes => filteredRes.value),\n\t\t)\n\n\t\t// Refresh the assets\n\t\tawait this.engine.stores.assetStore.assetService?.refresh().catch(unhandledError)\n\t\treturn results\n\t}\n}\n", "import type { WindowWithCurrentUser } from \"@framerjs/app-shared\"\nimport { assertNever, emptyArray } from \"@framerjs/shared\"\nimport { Dictionary } from \"app/dictionary.ts\"\nimport { v4 } from \"uuid\"\nimport type { NodeID } from \"../../nodes/NodeID.ts\"\nimport type { SendTo } from \"./WithFormContainer.ts\"\n\nconst currentUser = (window as WindowWithCurrentUser)?.framerUser\n\nexport function createDestination(sendTo: SendTo): FormConfigDestination {\n\tswitch (sendTo) {\n\t\tcase \"verifiedEmail\":\n\t\t\treturn {\n\t\t\t\ttype: \"verifiedEmail\",\n\t\t\t\temails: [{ email: currentUser.email, verified: true }],\n\t\t\t\tname: Dictionary.Framer,\n\t\t\t\tsubject: defaultSubject,\n\t\t\t\tbody: defaultBody,\n\t\t\t\tid: v4(),\n\t\t\t}\n\t\tcase \"webhook\":\n\t\t\treturn { type: \"webhook\", webhookUrl: undefined, secret: \"\", fallbackEmail: currentUser.email, id: v4() }\n\t\tcase \"googlesheet\":\n\t\t\treturn {\n\t\t\t\ttype: \"googlesheet\",\n\t\t\t\tfallbackEmail: currentUser.email,\n\t\t\t\tdocumentId: undefined,\n\t\t\t\tdocumentName: undefined,\n\t\t\t\tid: v4(),\n\t\t\t}\n\t\tdefault:\n\t\t\tassertNever(sendTo)\n\t}\n}\n\n/**\n * Google sheet and webhook destinations may have an optional fallback email address\n * specified in the case that delivery of the form submission fails to be delivered to\n * the primary destination.\n */\ninterface WithFallbackEmail {\n\t/**\n\t * The email address to notify if the primary destination\n\t * fails to deliver the form submission.\n\t * Only applies to webhook and googlesheet destinations.\n\t */\n\tfallbackEmail: string | undefined\n}\n\nexport interface FormConfig {\n\tid: NodeID\n\tprojectId: string\n\tdestinations: readonly FormConfigDestination[]\n\tantispam: FormConfigAntispam\n}\n\ninterface LegacyFormConfigEmailDestination {\n\ttype: \"email\"\n\tid: string\n\temails: string | undefined\n\tsubject: string | undefined\n\tbody: string | undefined\n\tname: string | undefined\n}\n\ninterface VerifiedEmail {\n\temail: string\n\tverified?: boolean\n}\n\nexport interface FormConfigVerifiedEmailDestination {\n\ttype: \"verifiedEmail\"\n\tid: string\n\temails: VerifiedEmail[] | undefined\n\tsubject: string | undefined\n\tbody: string | undefined\n\tname: string | undefined\n}\n\nexport function isFormConfigVerifiedEmailDestination(\n\tdestination: FormConfigDestination,\n): destination is FormConfigVerifiedEmailDestination {\n\treturn destination.type === \"verifiedEmail\"\n}\n\nexport interface FormConfigWebhookDestination extends WithFallbackEmail {\n\ttype: \"webhook\"\n\tid: string\n\twebhookUrl: string | undefined\n\tsecret: string | undefined\n}\n\n/** When the secret is set, it comes from the server as `--encrypted--` */\nexport const encryptedSecret = \"--encrypted--\"\n\nexport function isFormConfigWebhookDestination(\n\tdestination: FormConfigDestination,\n): destination is FormConfigWebhookDestination {\n\treturn destination.type === \"webhook\"\n}\n\nexport interface FormConfigGoogleSheetDestination extends WithFallbackEmail {\n\ttype: \"googlesheet\"\n\tid: string\n\tdocumentName: string | undefined\n\tdocumentId: string | undefined\n}\n\nexport function isFormConfigGoogleSheetDestination(\n\tdestination: FormConfigDestination,\n): destination is FormConfigGoogleSheetDestination {\n\treturn destination.type === \"googlesheet\"\n}\n\nexport type FormConfigDestination =\n\t| FormConfigVerifiedEmailDestination\n\t| FormConfigWebhookDestination\n\t| FormConfigGoogleSheetDestination\n\nexport type ServerFormConfigDestination =\n\t| LegacyFormConfigEmailDestination\n\t| FormConfigVerifiedEmailDestination\n\t| FormConfigWebhookDestination\n\t| FormConfigGoogleSheetDestination\n\nexport enum SecretStatus {\n\tEmpty,\n\tEncrypting,\n\tEncrypted,\n}\n\nexport type SpamProtectionProvider = \"spam_protection\"\nexport type CaptchaProvider = \"recaptcha_v3\"\nexport type AntispamProvider = SpamProtectionProvider | CaptchaProvider\n\nexport type AntispamFiltering = \"block\" | \"pass\"\nexport type SpamProtectionMode = \"disabled\" | \"basic\" | \"advanced\"\n\nexport interface FormConfigAntispamError {\n\treadonly reason: string\n\treadonly data?: string\n}\n\ninterface FormConfigAntispamConfigBase {\n\tprovider: AntispamProvider\n\tfiltering: AntispamFiltering\n}\n\nexport interface FormConfigSpamProtectionAntispamConfig extends FormConfigAntispamConfigBase {\n\tprovider: SpamProtectionProvider\n\tmode: SpamProtectionMode\n}\n\nexport interface FormConfigRecaptchaV3AntispamConfig extends FormConfigAntispamConfigBase {\n\tprovider: CaptchaProvider\n\tsiteKey: string\n\tsecretKey: string\n\tthreshold: number\n\tfiltering: AntispamFiltering\n}\n\nexport interface FormConfigAntispam {\n\tconfigs: readonly FormConfigAntispamConfig[]\n}\n\nexport interface FormConfigAntispamResponse extends FormConfigAntispam {\n\terrors?: readonly FormConfigAntispamError[]\n}\n\nconst antispamProviderOrder = [\"spam_protection\", \"recaptcha_v3\"] as const satisfies AntispamProvider[]\n\ntype FormConfigCaptchaAntispamConfig = FormConfigRecaptchaV3AntispamConfig\n\nexport type FormConfigAntispamConfig = FormConfigSpamProtectionAntispamConfig | FormConfigCaptchaAntispamConfig\n\nexport function isCaptchaAntispam(antispam: FormConfigAntispamConfig): antispam is FormConfigCaptchaAntispamConfig {\n\treturn antispam.provider === \"recaptcha_v3\"\n}\n\nexport function createAntispamConfig(provider: AntispamProvider): FormConfigAntispamConfig {\n\tswitch (provider) {\n\t\tcase \"spam_protection\":\n\t\t\treturn {\n\t\t\t\tprovider: \"spam_protection\",\n\t\t\t\tmode: \"basic\",\n\t\t\t\tfiltering: \"pass\",\n\t\t\t}\n\t\tcase \"recaptcha_v3\":\n\t\t\treturn {\n\t\t\t\tprovider: \"recaptcha_v3\",\n\t\t\t\tsiteKey: \"\",\n\t\t\t\tsecretKey: \"\",\n\t\t\t\tthreshold: 0.5,\n\t\t\t\tfiltering: \"pass\",\n\t\t\t}\n\t\tdefault:\n\t\t\tassertNever(provider)\n\t}\n}\n\nexport function createAntispam(\n\tconfigs: readonly FormConfigAntispamConfig[] = emptyArray<FormConfigAntispamConfig>(),\n): FormConfigAntispam {\n\treturn { configs }\n}\n\n/**\n * If form antispam is enabled, ensures it's present\n * If form antispam is disabled, no providers are returned\n *\n */\nexport function getAvailableAntispamProviders({\n\tformAntispamEnabled,\n\trecaptchaEnabled,\n}: {\n\tformAntispamEnabled: boolean\n\trecaptchaEnabled: boolean\n}): readonly AntispamProvider[] {\n\tif (!formAntispamEnabled) return []\n\n\treturn recaptchaEnabled ? antispamProviderOrder : [\"spam_protection\"]\n}\n\n/**\n * Normalize the antispam configs to the available providers.\n * If a provider is not available, it is removed.\n * If a provider is not present, it is added.\n * If a provider is present, it is kept.\n */\nexport function normalizeAntispamConfigs(\n\tantispamConfigs: readonly FormConfigAntispamConfig[],\n\tavailableProviders: readonly AntispamProvider[],\n): readonly FormConfigAntispamConfig[] {\n\tif (availableProviders.length === 0) return []\n\n\tconst availableProvidersSet = new Set<AntispamProvider>(availableProviders)\n\tconst configsByProvider = new Map<AntispamProvider, FormConfigAntispamConfig>()\n\n\tfor (const config of antispamConfigs) {\n\t\tif (!availableProvidersSet.has(config.provider)) continue\n\t\tif (configsByProvider.has(config.provider)) continue\n\t\tconfigsByProvider.set(config.provider, config)\n\t}\n\n\tif (availableProvidersSet.has(\"spam_protection\") && !configsByProvider.has(\"spam_protection\")) {\n\t\tconfigsByProvider.set(\"spam_protection\", createAntispamConfig(\"spam_protection\"))\n\t}\n\n\treturn antispamProviderOrder.flatMap(provider => {\n\t\tif (!availableProvidersSet.has(provider)) return []\n\t\tconst config = configsByProvider.get(provider)\n\t\treturn config ? [config] : []\n\t})\n}\n\nexport function normalizeAntispamConfigsForSpamProtectionAdvanced(\n\tantispamConfigs: readonly FormConfigAntispamConfig[],\n\tavailableProviders: readonly AntispamProvider[],\n\tcanUseSpamProtectionAdvanced: boolean,\n): readonly FormConfigAntispamConfig[] {\n\tconst normalizedConfigs = normalizeAntispamConfigs(antispamConfigs, availableProviders)\n\tif (canUseSpamProtectionAdvanced) return normalizedConfigs\n\n\treturn normalizedConfigs.map(config =>\n\t\tnormalizeSpamProtectionModeForSpamProtectionAdvanced(config, canUseSpamProtectionAdvanced),\n\t)\n}\n\nfunction normalizeSpamProtectionModeForSpamProtectionAdvanced(\n\tconfig: FormConfigAntispamConfig,\n\tcanUseSpamProtectionAdvanced: boolean,\n): FormConfigAntispamConfig {\n\tif (canUseSpamProtectionAdvanced) return config\n\tif (config.provider !== \"spam_protection\" || config.mode !== \"advanced\") return config\n\treturn { ...config, mode: \"basic\" }\n}\n\nconst destinationTypeKey: keyof Pick<FormConfigDestination, \"type\"> = \"type\"\nconst antispamProviderKey: keyof Pick<FormConfigAntispamConfig, \"provider\"> = \"provider\"\nconst formConfigVerifiedEmailDestinationKeys: Record<keyof FormConfigVerifiedEmailDestination, true> = {\n\ttype: true,\n\tid: true,\n\temails: true,\n\tsubject: true,\n\tbody: true,\n\tname: true,\n}\n\nexport function isCompatibleVerifiedEmailDestinationUpdate(\n\tupdate: Partial<FormConfigDestination>,\n): update is Partial<FormConfigVerifiedEmailDestination> {\n\tfor (const key in update) {\n\t\tif (key === destinationTypeKey && update[key] !== \"verifiedEmail\") return false\n\t\tif (!(key in formConfigVerifiedEmailDestinationKeys)) return false\n\t}\n\treturn true\n}\n\nconst formConfigWebhookDestinationKeys: Record<keyof FormConfigWebhookDestination, true> = {\n\ttype: true,\n\tid: true,\n\twebhookUrl: true,\n\tfallbackEmail: true,\n\tsecret: true,\n}\n\nexport function isCompatibleWebhookDestinationUpdate(\n\tupdate: Partial<FormConfigDestination>,\n): update is Partial<FormConfigWebhookDestination> {\n\tfor (const key in update) {\n\t\tif (key === destinationTypeKey && update[key] !== \"webhook\") return false\n\t\tif (!(key in formConfigWebhookDestinationKeys)) return false\n\t}\n\treturn true\n}\n\nconst formConfigGoogleSheetDestinationKeys: Record<keyof FormConfigGoogleSheetDestination, true> = {\n\ttype: true,\n\tid: true,\n\tdocumentName: true,\n\tdocumentId: true,\n\tfallbackEmail: true,\n}\n\nexport function isCompatibleGoogleSheetDestinationUpdate(\n\tupdate: Partial<FormConfigDestination>,\n): update is Partial<FormConfigGoogleSheetDestination> {\n\tfor (const key in update) {\n\t\tif (key === destinationTypeKey && update[key] !== \"googlesheet\") return false\n\t\tif (!(key in formConfigGoogleSheetDestinationKeys)) return false\n\t}\n\treturn true\n}\n\nconst formConfigSpamProtectionAntispamKeys: Record<keyof FormConfigSpamProtectionAntispamConfig, true> = {\n\tprovider: true,\n\tfiltering: true,\n\tmode: true,\n}\n\nexport function isCompatibleSpamProtectionUpdate(\n\tupdate: Partial<FormConfigAntispamConfig>,\n): update is Partial<FormConfigSpamProtectionAntispamConfig> {\n\tfor (const key in update) {\n\t\tif (key === antispamProviderKey && update[key] !== \"spam_protection\") return false\n\t\tif (!(key in formConfigSpamProtectionAntispamKeys)) return false\n\t}\n\treturn true\n}\n\nconst formConfigRecaptchaV3AntispamKeys: Record<keyof FormConfigRecaptchaV3AntispamConfig, true> = {\n\tprovider: true,\n\tfiltering: true,\n\tsiteKey: true,\n\tsecretKey: true,\n\tthreshold: true,\n}\n\nexport function isCompatibleRecaptchaV3Update(\n\tupdate: Partial<FormConfigAntispamConfig>,\n): update is Partial<FormConfigRecaptchaV3AntispamConfig> {\n\tfor (const key in update) {\n\t\tif (key === antispamProviderKey && update[key] !== \"recaptcha_v3\") return false\n\t\tif (!(key in formConfigRecaptchaV3AntispamKeys)) return false\n\t}\n\treturn true\n}\n\nexport const defaultSubject = \"New Submission\"\nexport const defaultBody = \"You\u2019ve just received a new submission.\"\n", "// IMPORTANT! This module should not use any dependencies because it's reused between vekter and modules-cli (Deno)\n// (Note: tools/modules-cli doesn\u2019t exist anymore, so this comment is probably outdated)\n\n/**\n * Bump this version when there's a need to change the expectations in the Framer\n * runtime (such as the meaning of an annotation, or a default behavior). Because\n * Framer needs to keep supporting code compiled in the past it's important that\n * we don't change the behavior of old code. That's why we will compile this version\n * number into each component so that we know what the expectations were for that\n * particular compiled component at the time it was compiled.\n *\n * If the version annotation does not exist on a component, we assume it is 0.\n *\n * Version history:\n *\n *   0 Initial version.\n *   1 Change default for missing @framerSupportedLayout{Width,Height} to \"any\"\n *\n */\nexport const COMPILER_CONTRACT_VERSION = 1\n", "/* es-module-lexer 1.5.4 */\nexport var ImportType;!function(A){A[A.Static=1]=\"Static\",A[A.Dynamic=2]=\"Dynamic\",A[A.ImportMeta=3]=\"ImportMeta\",A[A.StaticSourcePhase=4]=\"StaticSourcePhase\",A[A.DynamicSourcePhase=5]=\"DynamicSourcePhase\"}(ImportType||(ImportType={}));const A=1===new Uint8Array(new Uint16Array([1]).buffer)[0];export function parse(E,g=\"@\"){if(!C)return init.then((()=>parse(E)));const I=E.length+1,w=(C.__heap_base.value||C.__heap_base)+4*I-C.memory.buffer.byteLength;w>0&&C.memory.grow(Math.ceil(w/65536));const K=C.sa(I-1);if((A?B:Q)(E,new Uint16Array(C.memory.buffer,K,I)),!C.parse())throw Object.assign(new Error(`Parse error ${g}:${E.slice(0,C.e()).split(\"\\n\").length}:${C.e()-E.lastIndexOf(\"\\n\",C.e()-1)}`),{idx:C.e()});const D=[],o=[];for(;C.ri();){const A=C.is(),Q=C.ie(),B=C.it(),g=C.ai(),I=C.id(),w=C.ss(),K=C.se();let o;C.ip()&&(o=k(E.slice(-1===I?A-1:A,-1===I?Q+1:Q))),D.push({n:o,t:B,s:A,e:Q,ss:w,se:K,d:I,a:g})}for(;C.re();){const A=C.es(),Q=C.ee(),B=C.els(),g=C.ele(),I=E.slice(A,Q),w=I[0],K=B<0?void 0:E.slice(B,g),D=K?K[0]:\"\";o.push({s:A,e:Q,ls:B,le:g,n:'\"'===w||\"'\"===w?k(I):I,ln:'\"'===D||\"'\"===D?k(K):K})}function k(A){try{return(0,eval)(A)}catch(A){}}return[D,o,!!C.f(),!!C.ms()]}function Q(A,Q){const B=A.length;let C=0;for(;C<B;){const B=A.charCodeAt(C);Q[C++]=(255&B)<<8|B>>>8}}function B(A,Q){const B=A.length;let C=0;for(;C<B;)Q[C]=A.charCodeAt(C++)}let C;export const init=WebAssembly.compile((E=\"AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKm0EwaAEBf0EAIAA2AoA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kAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=\",\"undefined\"!=typeof Buffer?Buffer.from(E,\"base64\"):Uint8Array.from(atob(E),(A=>A.charCodeAt(0))))).then(WebAssembly.instantiate).then((({exports:A})=>{C=A}));var E;", "import { type ImportSpecifier, init as initLexer, parse } from \"es-module-lexer\"\nimport type { ModuleSpecifier, RelativeFilePath, TypeSlashName } from \"../modules/types.ts\"\nimport type { Result } from \"../utils/result.ts\"\nimport { err, ok } from \"../utils/result.ts\"\n\nconst ARGUMENT_IS_RELATIVE_MODULE_SPECIFIER_REGEXP = /^\\s*(['\"](\\..*)['\"])\\s*$/mu\n\ninterface FailedReplacement {\n\tpartiallyProcessedCode: string\n\tunresolvedRelativeImports: Set<string>\n\tparsedImports: readonly ImportSpecifier[]\n}\n\nexport type ReplacementMap = Record<RelativeFilePath, ModuleSpecifier | undefined>\n\nexport class RewriteRelativeImportsError extends Error {\n\tconstructor(public readonly persistedMissingRelativeImports: Set<TypeSlashName>) {\n\t\tsuper()\n\t\tthis.name = \"RewriteRelativeImportsError\"\n\t}\n}\n\nexport function isRewriteRelativeImportsError(error: unknown): error is RewriteRelativeImportsError {\n\treturn error instanceof RewriteRelativeImportsError\n}\n\n/**\n * Returns either an \"ok\" Result wrapping the `code` with all relative imports replaced\n * with the values from `replacementMap` or an \"error\" Result with partially processed code\n * and a `Set` of all relative imports that weren't found in `replacementMap`.\n *\n * @param code\n * @param replacementMap\n */\nexport async function rewriteRelativeImports(\n\tcode: string,\n\treplacementMap: ReplacementMap,\n): Promise<Result<string, FailedReplacement>> {\n\tawait initLexer\n\tconst [imports] = parse(code)\n\n\tlet transformedCode = code\n\tconst unresolvedRelativeImports = new Set<RelativeFilePath>()\n\tconst reversedImports = [...imports].reverse()\n\tfor (const { s: specStart, e: specEnd, d } of reversedImports) {\n\t\t// d = -2 = import.meta.url = we can skip this\n\t\tif (d === -2) continue\n\n\t\t// static import statement\n\t\tif (d === -1) {\n\t\t\tconst moduleSpecifier = code.substring(specStart, specEnd)\n\t\t\tif (!moduleSpecifier.startsWith(\".\")) continue\n\n\t\t\tlet replacementSpecifier = replacementMap[moduleSpecifier]\n\n\t\t\tif (replacementSpecifier === undefined) {\n\t\t\t\tunresolvedRelativeImports.add(moduleSpecifier)\n\t\t\t\treplacementSpecifier = unresolvedRelativeSpecifier(moduleSpecifier)\n\t\t\t}\n\n\t\t\ttransformedCode = spliceString(transformedCode, replacementSpecifier, specStart, specEnd)\n\t\t\tcontinue\n\t\t}\n\n\t\t// dynamic import\n\t\t// in case of dynamic import the substring below returns everything between import()'s parenthesis.\n\t\tconst importArgumentUnsanitized = code.substring(specStart, specEnd)\n\t\tconst importArgument = importArgumentUnsanitized\n\t\t\t// strip comments, see https://stackoverflow.com/a/15123777\n\t\t\t.replace(/\\/\\*[\\s\\S]*?\\*\\/|([^\\\\:]|^)\\/\\/.*$/gm, \"$1\")\n\t\t\t.trim()\n\n\t\tconst match = importArgument.match(ARGUMENT_IS_RELATIVE_MODULE_SPECIFIER_REGEXP)\n\t\tif (!match) continue\n\n\t\tconst moduleSpecifierWithQuotes = match[1]\n\t\tconst moduleSpecifier = match[2]\n\t\tif (moduleSpecifierWithQuotes === undefined || moduleSpecifier === undefined) continue\n\n\t\tlet replacementSpecifier = replacementMap[moduleSpecifier]\n\n\t\tif (replacementSpecifier === undefined) {\n\t\t\tunresolvedRelativeImports.add(moduleSpecifier)\n\t\t\treplacementSpecifier = unresolvedRelativeSpecifier(moduleSpecifier)\n\t\t}\n\n\t\t// This will replace all the occurrences in the argument string,\n\t\t// so might affect comments if they contain that string but we are ok with that\n\t\tconst replacementImportArgument = importArgumentUnsanitized.replace(\n\t\t\tnew RegExp(escapeRegExp(moduleSpecifierWithQuotes), \"g\"),\n\t\t\tJSON.stringify(replacementSpecifier),\n\t\t)\n\t\ttransformedCode = spliceString(transformedCode, replacementImportArgument, specStart, specEnd)\n\t}\n\n\tif (unresolvedRelativeImports.size > 0) {\n\t\treturn err({ partiallyProcessedCode: transformedCode, unresolvedRelativeImports, parsedImports: imports })\n\t}\n\n\treturn ok(transformedCode)\n}\n\nfunction spliceString(source: string, withString: string, start: number, end: number): string {\n\treturn source.slice(0, start) + withString + source.slice(end)\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping\nexport function escapeRegExp(str: string) {\n\treturn str.replace(/[.*+\\-?^${}()|[\\]\\\\]/gu, \"\\\\$&\") // $& means the whole matched string\n}\n\n/**\n * Creates a \"bare\" moduleSpecifier from the unresolved relative `moduleSpecifier`,\n * so that the browser doesn't try to \"resolve\" that path relatively to\n * the absolute importing module URL, and thus print better console error messages.\n */\nfunction unresolvedRelativeSpecifier(moduleSpecifier: RelativeFilePath): string {\n\treturn `!missing/${moduleSpecifier}`\n}\n", "const mimes = {\n  \"3g2\": \"video/3gpp2\",\n  \"3gp\": \"video/3gpp\",\n  \"3gpp\": \"video/3gpp\",\n  \"3mf\": \"model/3mf\",\n  \"aac\": \"audio/aac\",\n  \"ac\": \"application/pkix-attr-cert\",\n  \"adp\": \"audio/adpcm\",\n  \"adts\": \"audio/aac\",\n  \"ai\": \"application/postscript\",\n  \"aml\": \"application/automationml-aml+xml\",\n  \"amlx\": \"application/automationml-amlx+zip\",\n  \"amr\": \"audio/amr\",\n  \"apng\": \"image/apng\",\n  \"appcache\": \"text/cache-manifest\",\n  \"appinstaller\": \"application/appinstaller\",\n  \"appx\": \"application/appx\",\n  \"appxbundle\": \"application/appxbundle\",\n  \"asc\": \"application/pgp-keys\",\n  \"atom\": \"application/atom+xml\",\n  \"atomcat\": \"application/atomcat+xml\",\n  \"atomdeleted\": \"application/atomdeleted+xml\",\n  \"atomsvc\": \"application/atomsvc+xml\",\n  \"au\": \"audio/basic\",\n  \"avci\": \"image/avci\",\n  \"avcs\": \"image/avcs\",\n  \"avif\": \"image/avif\",\n  \"aw\": \"application/applixware\",\n  \"bdoc\": \"application/bdoc\",\n  \"bin\": \"application/octet-stream\",\n  \"bmp\": \"image/bmp\",\n  \"bpk\": \"application/octet-stream\",\n  \"btf\": \"image/prs.btif\",\n  \"btif\": \"image/prs.btif\",\n  \"buffer\": \"application/octet-stream\",\n  \"ccxml\": \"application/ccxml+xml\",\n  \"cdfx\": \"application/cdfx+xml\",\n  \"cdmia\": \"application/cdmi-capability\",\n  \"cdmic\": \"application/cdmi-container\",\n  \"cdmid\": \"application/cdmi-domain\",\n  \"cdmio\": \"application/cdmi-object\",\n  \"cdmiq\": \"application/cdmi-queue\",\n  \"cer\": \"application/pkix-cert\",\n  \"cgm\": \"image/cgm\",\n  \"cjs\": \"application/node\",\n  \"class\": \"application/java-vm\",\n  \"coffee\": \"text/coffeescript\",\n  \"conf\": \"text/plain\",\n  \"cpl\": \"application/cpl+xml\",\n  \"cpt\": \"application/mac-compactpro\",\n  \"crl\": \"application/pkix-crl\",\n  \"css\": \"text/css\",\n  \"csv\": \"text/csv\",\n  \"cu\": \"application/cu-seeme\",\n  \"cwl\": \"application/cwl\",\n  \"cww\": \"application/prs.cww\",\n  \"davmount\": \"application/davmount+xml\",\n  \"dbk\": \"application/docbook+xml\",\n  \"deb\": \"application/octet-stream\",\n  \"def\": \"text/plain\",\n  \"deploy\": \"application/octet-stream\",\n  \"dib\": \"image/bmp\",\n  \"disposition-notification\": \"message/disposition-notification\",\n  \"dist\": \"application/octet-stream\",\n  \"distz\": \"application/octet-stream\",\n  \"dll\": \"application/octet-stream\",\n  \"dmg\": \"application/octet-stream\",\n  \"dms\": \"application/octet-stream\",\n  \"doc\": \"application/msword\",\n  \"dot\": \"application/msword\",\n  \"dpx\": \"image/dpx\",\n  \"drle\": \"image/dicom-rle\",\n  \"dsc\": \"text/prs.lines.tag\",\n  \"dssc\": \"application/dssc+der\",\n  \"dtd\": \"application/xml-dtd\",\n  \"dump\": \"application/octet-stream\",\n  \"dwd\": \"application/atsc-dwd+xml\",\n  \"ear\": \"application/java-archive\",\n  \"ecma\": \"application/ecmascript\",\n  \"elc\": \"application/octet-stream\",\n  \"emf\": \"image/emf\",\n  \"eml\": \"message/rfc822\",\n  \"emma\": \"application/emma+xml\",\n  \"emotionml\": \"application/emotionml+xml\",\n  \"eps\": \"application/postscript\",\n  \"epub\": \"application/epub+zip\",\n  \"exe\": \"application/octet-stream\",\n  \"exi\": \"application/exi\",\n  \"exp\": \"application/express\",\n  \"exr\": \"image/aces\",\n  \"ez\": \"application/andrew-inset\",\n  \"fdf\": \"application/fdf\",\n  \"fdt\": \"application/fdt+xml\",\n  \"fits\": \"image/fits\",\n  \"g3\": \"image/g3fax\",\n  \"gbr\": \"application/rpki-ghostbusters\",\n  \"geojson\": \"application/geo+json\",\n  \"gif\": \"image/gif\",\n  \"glb\": \"model/gltf-binary\",\n  \"gltf\": \"model/gltf+json\",\n  \"gml\": \"application/gml+xml\",\n  \"gpx\": \"application/gpx+xml\",\n  \"gram\": \"application/srgs\",\n  \"grxml\": \"application/srgs+xml\",\n  \"gxf\": \"application/gxf\",\n  \"gz\": \"application/gzip\",\n  \"h261\": \"video/h261\",\n  \"h263\": \"video/h263\",\n  \"h264\": \"video/h264\",\n  \"heic\": \"image/heic\",\n  \"heics\": \"image/heic-sequence\",\n  \"heif\": \"image/heif\",\n  \"heifs\": \"image/heif-sequence\",\n  \"hej2\": \"image/hej2k\",\n  \"held\": \"application/atsc-held+xml\",\n  \"hjson\": \"application/hjson\",\n  \"hlp\": \"application/winhlp\",\n  \"hqx\": \"application/mac-binhex40\",\n  \"hsj2\": \"image/hsj2\",\n  \"htm\": \"text/html\",\n  \"html\": \"text/html\",\n  \"ics\": \"text/calendar\",\n  \"ief\": \"image/ief\",\n  \"ifb\": \"text/calendar\",\n  \"iges\": \"model/iges\",\n  \"igs\": \"model/iges\",\n  \"img\": \"application/octet-stream\",\n  \"in\": \"text/plain\",\n  \"ini\": \"text/plain\",\n  \"ink\": \"application/inkml+xml\",\n  \"inkml\": \"application/inkml+xml\",\n  \"ipfix\": \"application/ipfix\",\n  \"iso\": \"application/octet-stream\",\n  \"its\": \"application/its+xml\",\n  \"jade\": \"text/jade\",\n  \"jar\": \"application/java-archive\",\n  \"jhc\": \"image/jphc\",\n  \"jls\": \"image/jls\",\n  \"jp2\": \"image/jp2\",\n  \"jpe\": \"image/jpeg\",\n  \"jpeg\": \"image/jpeg\",\n  \"jpf\": \"image/jpx\",\n  \"jpg\": \"image/jpeg\",\n  \"jpg2\": \"image/jp2\",\n  \"jpgm\": \"image/jpm\",\n  \"jpgv\": \"video/jpeg\",\n  \"jph\": \"image/jph\",\n  \"jpm\": \"image/jpm\",\n  \"jpx\": \"image/jpx\",\n  \"js\": \"text/javascript\",\n  \"json\": \"application/json\",\n  \"json5\": \"application/json5\",\n  \"jsonld\": \"application/ld+json\",\n  \"jsonml\": \"application/jsonml+json\",\n  \"jsx\": \"text/jsx\",\n  \"jt\": \"model/jt\",\n  \"jxl\": \"image/jxl\",\n  \"jxr\": \"image/jxr\",\n  \"jxra\": \"image/jxra\",\n  \"jxrs\": \"image/jxrs\",\n  \"jxs\": \"image/jxs\",\n  \"jxsc\": \"image/jxsc\",\n  \"jxsi\": \"image/jxsi\",\n  \"jxss\": \"image/jxss\",\n  \"kar\": \"audio/midi\",\n  \"ktx\": \"image/ktx\",\n  \"ktx2\": \"image/ktx2\",\n  \"less\": \"text/less\",\n  \"lgr\": \"application/lgr+xml\",\n  \"list\": \"text/plain\",\n  \"litcoffee\": \"text/coffeescript\",\n  \"log\": \"text/plain\",\n  \"lostxml\": \"application/lost+xml\",\n  \"lrf\": \"application/octet-stream\",\n  \"m1v\": \"video/mpeg\",\n  \"m21\": \"application/mp21\",\n  \"m2a\": \"audio/mpeg\",\n  \"m2t\": \"video/mp2t\",\n  \"m2ts\": \"video/mp2t\",\n  \"m2v\": \"video/mpeg\",\n  \"m3a\": \"audio/mpeg\",\n  \"m4a\": \"audio/mp4\",\n  \"m4p\": \"application/mp4\",\n  \"m4s\": \"video/iso.segment\",\n  \"ma\": \"application/mathematica\",\n  \"mads\": \"application/mads+xml\",\n  \"maei\": \"application/mmt-aei+xml\",\n  \"man\": \"text/troff\",\n  \"manifest\": \"text/cache-manifest\",\n  \"map\": \"application/json\",\n  \"mar\": \"application/octet-stream\",\n  \"markdown\": \"text/markdown\",\n  \"mathml\": \"application/mathml+xml\",\n  \"mb\": \"application/mathematica\",\n  \"mbox\": \"application/mbox\",\n  \"md\": \"text/markdown\",\n  \"mdx\": \"text/mdx\",\n  \"me\": \"text/troff\",\n  \"mesh\": \"model/mesh\",\n  \"meta4\": \"application/metalink4+xml\",\n  \"metalink\": \"application/metalink+xml\",\n  \"mets\": \"application/mets+xml\",\n  \"mft\": \"application/rpki-manifest\",\n  \"mid\": \"audio/midi\",\n  \"midi\": \"audio/midi\",\n  \"mime\": \"message/rfc822\",\n  \"mj2\": \"video/mj2\",\n  \"mjp2\": \"video/mj2\",\n  \"mjs\": \"text/javascript\",\n  \"mml\": \"text/mathml\",\n  \"mods\": \"application/mods+xml\",\n  \"mov\": \"video/quicktime\",\n  \"mp2\": \"audio/mpeg\",\n  \"mp21\": \"application/mp21\",\n  \"mp2a\": \"audio/mpeg\",\n  \"mp3\": \"audio/mpeg\",\n  \"mp4\": \"video/mp4\",\n  \"mp4a\": \"audio/mp4\",\n  \"mp4s\": \"application/mp4\",\n  \"mp4v\": \"video/mp4\",\n  \"mpd\": \"application/dash+xml\",\n  \"mpe\": \"video/mpeg\",\n  \"mpeg\": \"video/mpeg\",\n  \"mpf\": \"application/media-policy-dataset+xml\",\n  \"mpg\": \"video/mpeg\",\n  \"mpg4\": \"video/mp4\",\n  \"mpga\": \"audio/mpeg\",\n  \"mpp\": \"application/dash-patch+xml\",\n  \"mrc\": \"application/marc\",\n  \"mrcx\": \"application/marcxml+xml\",\n  \"ms\": \"text/troff\",\n  \"mscml\": \"application/mediaservercontrol+xml\",\n  \"msh\": \"model/mesh\",\n  \"msi\": \"application/octet-stream\",\n  \"msix\": \"application/msix\",\n  \"msixbundle\": \"application/msixbundle\",\n  \"msm\": \"application/octet-stream\",\n  \"msp\": \"application/octet-stream\",\n  \"mtl\": \"model/mtl\",\n  \"mts\": \"video/mp2t\",\n  \"musd\": \"application/mmt-usd+xml\",\n  \"mxf\": \"application/mxf\",\n  \"mxmf\": \"audio/mobile-xmf\",\n  \"mxml\": \"application/xv+xml\",\n  \"n3\": \"text/n3\",\n  \"nb\": \"application/mathematica\",\n  \"nq\": \"application/n-quads\",\n  \"nt\": \"application/n-triples\",\n  \"obj\": \"model/obj\",\n  \"oda\": \"application/oda\",\n  \"oga\": \"audio/ogg\",\n  \"ogg\": \"audio/ogg\",\n  \"ogv\": \"video/ogg\",\n  \"ogx\": \"application/ogg\",\n  \"omdoc\": \"application/omdoc+xml\",\n  \"onepkg\": \"application/onenote\",\n  \"onetmp\": \"application/onenote\",\n  \"onetoc\": \"application/onenote\",\n  \"onetoc2\": \"application/onenote\",\n  \"opf\": \"application/oebps-package+xml\",\n  \"opus\": \"audio/ogg\",\n  \"otf\": \"font/otf\",\n  \"owl\": \"application/rdf+xml\",\n  \"oxps\": \"application/oxps\",\n  \"p10\": \"application/pkcs10\",\n  \"p7c\": \"application/pkcs7-mime\",\n  \"p7m\": \"application/pkcs7-mime\",\n  \"p7s\": \"application/pkcs7-signature\",\n  \"p8\": \"application/pkcs8\",\n  \"pdf\": \"application/pdf\",\n  \"pfr\": \"application/font-tdpfr\",\n  \"pgp\": \"application/pgp-encrypted\",\n  \"pkg\": \"application/octet-stream\",\n  \"pki\": \"application/pkixcmp\",\n  \"pkipath\": \"application/pkix-pkipath\",\n  \"pls\": \"application/pls+xml\",\n  \"png\": \"image/png\",\n  \"prc\": \"model/prc\",\n  \"prf\": \"application/pics-rules\",\n  \"provx\": \"application/provenance+xml\",\n  \"ps\": \"application/postscript\",\n  \"pskcxml\": \"application/pskc+xml\",\n  \"pti\": \"image/prs.pti\",\n  \"qt\": \"video/quicktime\",\n  \"raml\": \"application/raml+yaml\",\n  \"rapd\": \"application/route-apd+xml\",\n  \"rdf\": \"application/rdf+xml\",\n  \"relo\": \"application/p2p-overlay+xml\",\n  \"rif\": \"application/reginfo+xml\",\n  \"rl\": \"application/resource-lists+xml\",\n  \"rld\": \"application/resource-lists-diff+xml\",\n  \"rmi\": \"audio/midi\",\n  \"rnc\": \"application/relax-ng-compact-syntax\",\n  \"rng\": \"application/xml\",\n  \"roa\": \"application/rpki-roa\",\n  \"roff\": \"text/troff\",\n  \"rq\": \"application/sparql-query\",\n  \"rs\": \"application/rls-services+xml\",\n  \"rsat\": \"application/atsc-rsat+xml\",\n  \"rsd\": \"application/rsd+xml\",\n  \"rsheet\": \"application/urc-ressheet+xml\",\n  \"rss\": \"application/rss+xml\",\n  \"rtf\": \"text/rtf\",\n  \"rtx\": \"text/richtext\",\n  \"rusd\": \"application/route-usd+xml\",\n  \"s3m\": \"audio/s3m\",\n  \"sbml\": \"application/sbml+xml\",\n  \"scq\": \"application/scvp-cv-request\",\n  \"scs\": \"application/scvp-cv-response\",\n  \"sdp\": \"application/sdp\",\n  \"senmlx\": \"application/senml+xml\",\n  \"sensmlx\": \"application/sensml+xml\",\n  \"ser\": \"application/java-serialized-object\",\n  \"setpay\": \"application/set-payment-initiation\",\n  \"setreg\": \"application/set-registration-initiation\",\n  \"sgi\": \"image/sgi\",\n  \"sgm\": \"text/sgml\",\n  \"sgml\": \"text/sgml\",\n  \"shex\": \"text/shex\",\n  \"shf\": \"application/shf+xml\",\n  \"shtml\": \"text/html\",\n  \"sieve\": \"application/sieve\",\n  \"sig\": \"application/pgp-signature\",\n  \"sil\": \"audio/silk\",\n  \"silo\": \"model/mesh\",\n  \"siv\": \"application/sieve\",\n  \"slim\": \"text/slim\",\n  \"slm\": \"text/slim\",\n  \"sls\": \"application/route-s-tsid+xml\",\n  \"smi\": \"application/smil+xml\",\n  \"smil\": \"application/smil+xml\",\n  \"snd\": \"audio/basic\",\n  \"so\": \"application/octet-stream\",\n  \"spdx\": \"text/spdx\",\n  \"spp\": \"application/scvp-vp-response\",\n  \"spq\": \"application/scvp-vp-request\",\n  \"spx\": \"audio/ogg\",\n  \"sql\": \"application/sql\",\n  \"sru\": \"application/sru+xml\",\n  \"srx\": \"application/sparql-results+xml\",\n  \"ssdl\": \"application/ssdl+xml\",\n  \"ssml\": \"application/ssml+xml\",\n  \"stk\": \"application/hyperstudio\",\n  \"stl\": \"model/stl\",\n  \"stpx\": \"model/step+xml\",\n  \"stpxz\": \"model/step-xml+zip\",\n  \"stpz\": \"model/step+zip\",\n  \"styl\": \"text/stylus\",\n  \"stylus\": \"text/stylus\",\n  \"svg\": \"image/svg+xml\",\n  \"svgz\": \"image/svg+xml\",\n  \"swidtag\": \"application/swid+xml\",\n  \"t\": \"text/troff\",\n  \"t38\": \"image/t38\",\n  \"td\": \"application/urc-targetdesc+xml\",\n  \"tei\": \"application/tei+xml\",\n  \"teicorpus\": \"application/tei+xml\",\n  \"text\": \"text/plain\",\n  \"tfi\": \"application/thraud+xml\",\n  \"tfx\": \"image/tiff-fx\",\n  \"tif\": \"image/tiff\",\n  \"tiff\": \"image/tiff\",\n  \"toml\": \"application/toml\",\n  \"tr\": \"text/troff\",\n  \"trig\": \"application/trig\",\n  \"ts\": \"video/mp2t\",\n  \"tsd\": \"application/timestamped-data\",\n  \"tsv\": \"text/tab-separated-values\",\n  \"ttc\": \"font/collection\",\n  \"ttf\": \"font/ttf\",\n  \"ttl\": \"text/turtle\",\n  \"ttml\": \"application/ttml+xml\",\n  \"txt\": \"text/plain\",\n  \"u3d\": \"model/u3d\",\n  \"u8dsn\": \"message/global-delivery-status\",\n  \"u8hdr\": \"message/global-headers\",\n  \"u8mdn\": \"message/global-disposition-notification\",\n  \"u8msg\": \"message/global\",\n  \"ubj\": \"application/ubjson\",\n  \"uri\": \"text/uri-list\",\n  \"uris\": \"text/uri-list\",\n  \"urls\": \"text/uri-list\",\n  \"vcard\": \"text/vcard\",\n  \"vrml\": \"model/vrml\",\n  \"vtt\": \"text/vtt\",\n  \"vxml\": \"application/voicexml+xml\",\n  \"war\": \"application/java-archive\",\n  \"wasm\": \"application/wasm\",\n  \"wav\": \"audio/wav\",\n  \"weba\": \"audio/webm\",\n  \"webm\": \"video/webm\",\n  \"webmanifest\": \"application/manifest+json\",\n  \"webp\": \"image/webp\",\n  \"wgsl\": \"text/wgsl\",\n  \"wgt\": \"application/widget\",\n  \"wif\": \"application/watcherinfo+xml\",\n  \"wmf\": \"image/wmf\",\n  \"woff\": \"font/woff\",\n  \"woff2\": \"font/woff2\",\n  \"wrl\": \"model/vrml\",\n  \"wsdl\": \"application/wsdl+xml\",\n  \"wspolicy\": \"application/wspolicy+xml\",\n  \"x3d\": \"model/x3d+xml\",\n  \"x3db\": \"model/x3d+fastinfoset\",\n  \"x3dbz\": \"model/x3d+binary\",\n  \"x3dv\": \"model/x3d-vrml\",\n  \"x3dvz\": \"model/x3d+vrml\",\n  \"x3dz\": \"model/x3d+xml\",\n  \"xaml\": \"application/xaml+xml\",\n  \"xav\": \"application/xcap-att+xml\",\n  \"xca\": \"application/xcap-caps+xml\",\n  \"xcs\": \"application/calendar+xml\",\n  \"xdf\": \"application/xcap-diff+xml\",\n  \"xdssc\": \"application/dssc+xml\",\n  \"xel\": \"application/xcap-el+xml\",\n  \"xenc\": \"application/xenc+xml\",\n  \"xer\": \"application/patch-ops-error+xml\",\n  \"xfdf\": \"application/xfdf\",\n  \"xht\": \"application/xhtml+xml\",\n  \"xhtml\": \"application/xhtml+xml\",\n  \"xhvml\": \"application/xv+xml\",\n  \"xlf\": \"application/xliff+xml\",\n  \"xm\": \"audio/xm\",\n  \"xml\": \"text/xml\",\n  \"xns\": \"application/xcap-ns+xml\",\n  \"xop\": \"application/xop+xml\",\n  \"xpl\": \"application/xproc+xml\",\n  \"xsd\": \"application/xml\",\n  \"xsf\": \"application/prs.xsf+xml\",\n  \"xsl\": \"application/xml\",\n  \"xslt\": \"application/xml\",\n  \"xspf\": \"application/xspf+xml\",\n  \"xvm\": \"application/xv+xml\",\n  \"xvml\": \"application/xv+xml\",\n  \"yaml\": \"text/yaml\",\n  \"yang\": \"application/yang\",\n  \"yin\": \"application/yin+xml\",\n  \"yml\": \"text/yaml\",\n  \"zip\": \"application/zip\"\n};\n\nfunction lookup(extn) {\n\tlet tmp = ('' + extn).trim().toLowerCase();\n\tlet idx = tmp.lastIndexOf('.');\n\treturn mimes[!~idx ? tmp : tmp.substring(++idx)];\n}\n\nexport { mimes, lookup };\n", "import { assert } from \"@framerjs/shared\"\nimport type { VariableDefinition } from \"document/models/CanvasTree/traits/WithVariables.ts\"\nimport { type AllowedFileTypes, ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { lookup as lookupMediaType } from \"mrmime\"\nimport MIMEType from \"whatwg-mimetype\"\n\nfunction isCompatibleMediaType(mediaType: MIMEType, allowedFileTypes: AllowedFileTypes) {\n\treturn allowedFileTypes.some(allowedFileType => {\n\t\tif (allowedFileType === \"*\") allowedFileType = \"*/*\"\n\n\t\t// Allowed media type\n\t\tlet allowedMimeType = MIMEType.parse(allowedFileType)\n\n\t\tif (!allowedMimeType) {\n\t\t\t// Allowed file extension with or without leading dot\n\t\t\tconst allowedMediaType = lookupMediaType(allowedFileType)\n\t\t\tallowedMimeType = allowedMediaType ? MIMEType.parse(allowedMediaType) : null\n\t\t}\n\n\t\tif (!allowedMimeType) {\n\t\t\t// We don't know this type, so it allows nothing\n\t\t\treturn false\n\t\t}\n\n\t\treturn (\n\t\t\t(allowedMimeType.type === \"*\" || allowedMimeType.type === mediaType.type) &&\n\t\t\t(allowedMimeType.subtype === \"*\" || allowedMimeType.subtype === mediaType.subtype)\n\t\t)\n\t})\n}\n\nexport function isCompatibleFileType(fileTypeOrExtension: string, allowedFileTypes: AllowedFileTypes): boolean {\n\tif (allowedFileTypes.length === 0) return true\n\n\tconst mediaType = lookupMediaType(fileTypeOrExtension) ?? fileTypeOrExtension\n\tconst mimeType = MIMEType.parse(mediaType)\n\tif (mimeType && isCompatibleMediaType(mimeType, allowedFileTypes)) {\n\t\treturn true\n\t}\n\n\t// Might be an unknown custom file extension, only pass if wildcard or that one exactly was allowed\n\treturn allowedFileTypes.some(\n\t\tallowedFileType =>\n\t\t\tallowedFileType === \"*\" ||\n\t\t\tallowedFileType === \"*/*\" ||\n\t\t\tfileTypeOrExtension === allowedFileType ||\n\t\t\tfileTypeOrExtension === `.${allowedFileType}`,\n\t)\n}\n\nexport function isCompatibleFileControl(variable: VariableDefinition, allowedFileTypes: AllowedFileTypes | undefined) {\n\tif (variable.type !== ControlType.File) return false\n\tassert(allowedFileTypes, \"allowedFileTypes should always be defined for ControlType.File\")\n\n\treturn variable.allowedFileTypes.every(({ extension: possibleFileType }) =>\n\t\tisCompatibleFileType(possibleFileType, allowedFileTypes),\n\t)\n}\n", "type ObjectEntry<T extends object> = {\n\t[K in keyof T]-?: [K, T[K]]\n}[keyof T]\n\ntype ObjectEntries<T extends object> = ObjectEntry<T>[]\n\n/**\n * A type-safe version of Object.entries.\n */\nexport function entries<T extends object>(obj: T): ObjectEntries<T> {\n\treturn Object.entries(obj) as ObjectEntries<T>\n}\n\n/**\n * A lazy, type-safe version of Object.entries. Optimization: Uses Object.keys to avoid prototype\n * chain traversal overhead.\n */\nexport function* entriesIterator<T extends object>(obj: T): Generator<ObjectEntry<T>> {\n\t// Object.keys is generally faster than for..in + hasOwnProperty in V8 because it uses the\n\t// engine's hidden class shape.\n\tconst keys = Object.keys(obj) as Array<keyof T>\n\n\tfor (const key of keys) {\n\t\tyield [key, obj[key]]\n\t}\n}\n", "import type { SandboxRepeaterData } from \"document/SandboxRepeaterData.ts\"\nimport type { CanvasNode, NodeID } from \"document/models/CanvasTree/index.ts\"\n\nexport function getFirstRepeaterItemId(\n\tproviderNode: CanvasNode,\n\tsandboxRepeaterData: SandboxRepeaterData,\n): NodeID | undefined {\n\tconst itemIds = sandboxRepeaterData.getItemIds(providerNode.id)\n\tif (!itemIds) return\n\n\treturn itemIds[0]\n}\n", "export const CODE_FORMATTING_TAB_WIDTH = 4\n", "import { isLocalModuleIdentifier, parseModuleIdentifier } from \"@framerjs/shared\"\nimport { hasLayoutTemplate } from \"document/models/CanvasTree/traits/WithLayoutTemplate.ts\"\nimport type { ScopeNode } from \"../document/models/CanvasTree/index.ts\"\nimport { isCodeComponentNode, isWebPageNode } from \"../document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { isReplicaOrReplicaChild } from \"../document/models/CanvasTree/traits/WithTemplate.ts\"\nimport type { TypeSlashName } from \"./types.ts\"\nimport { getTypeSlashName } from \"./utils.ts\"\n\nexport function getCodeComponentModuleTypeSlashNamesInScope(scope: ScopeNode | undefined): Set<TypeSlashName> {\n\tconst identifiers = new Set<TypeSlashName>()\n\n\tif (!scope) return identifiers\n\n\tif (isWebPageNode(scope) && hasLayoutTemplate(scope)) {\n\t\tconst typeSlashName = typeSlashNameForIdentifier(scope.layoutTemplateIdentifier)\n\t\tif (typeSlashName) identifiers.add(typeSlashName)\n\t}\n\n\tfor (const { node, skipChildren } of scope.walkWithSkipChildren()) {\n\t\tif (!isCodeComponentNode(node)) continue\n\t\tif (isReplicaOrReplicaChild(node)) {\n\t\t\t// Primaries contain all nodes.\n\t\t\tskipChildren()\n\t\t\tcontinue\n\t\t}\n\n\t\tconst typeSlashName = typeSlashNameForIdentifier(node.codeComponentIdentifier)\n\t\tif (typeSlashName) identifiers.add(typeSlashName)\n\t}\n\treturn identifiers\n}\n\nexport function typeSlashNameForIdentifier(identifier: string) {\n\tconst parsed = parseModuleIdentifier(identifier)\n\tif (!parsed || !isLocalModuleIdentifier(parsed)) return\n\treturn getTypeSlashName({ type: parsed.type, name: parsed.localIdName })\n}\n", "import type { ModulesAPI } from \"@framerjs/framer-services\"\nimport type { LocalModuleId } from \"@framerjs/shared\"\nimport { asLocalId, getLogger, unhandledError } from \"@framerjs/shared\"\nimport type { LocalModuleNode } from \"document/models/CanvasTree/nodes/LocalModuleNode.ts\"\n\nconst log = getLogger(\"modules-divergence-reporter\")\n\nexport interface DivergenceEntry {\n\tlocalId: LocalModuleId\n\ttreeSaveId: string | null\n\tbackendSaveId: string | null\n}\n\n/**\n * Outcome of a single divergence sample attempt.\n *\n * `notSettled` means the caller could not take a meaningful sample because local state is in\n * flight (unpersisted saves, pending tree writes, detached/view-only mode, etc). The reporter\n * treats this as a transient reason to back off and retry.\n *\n * `sampled` means the sample was taken and returns the current set of divergences (possibly\n * empty) between the in-memory tree and the backend list.\n */\nexport type SampleOutcome = { kind: \"notSettled\" } | { kind: \"sampled\"; divergences: readonly DivergenceEntry[] }\n\nexport interface ModulesDivergenceReporterParams {\n\t/** Performs one settle-gated divergence sample under the storage lock. */\n\tsample: () => Promise<SampleOutcome>\n\t/** Schedules a task to run when the engine is idle. */\n\trunWhenIdle: (task: () => void) => void\n\t/** Aborting this signal halts the loop and clears pending timers. */\n\tabortSignal?: AbortSignal\n\n\t/**\n\t * Number of consecutive samples a specific divergence entry must appear in before it is\n\t * logged. Defaults to 2 (observe, wait one `fastIntervalMs`, re-observe).\n\t */\n\tconsecutiveThreshold?: number\n\t/**\n\t * Delay sequence (in ms) applied when `sample` returns `notSettled`. The index is the current\n\t * settle-retry attempt; if the attempt index exceeds the array, the reporter gives up on\n\t * settling for this round and waits `slowIntervalMs` before the next round.\n\t */\n\tsettleBackoffMs?: readonly number[]\n\t/**\n\t * Default cadence between samples when nothing interesting is happening (no divergences, or\n\t * every currently-observed divergence has already been logged this session). Defaults to\n\t * 10 minutes.\n\t */\n\tslowIntervalMs?: number\n\t/**\n\t * Cadence between samples while we are actively monitoring a suspected divergence whose\n\t * counter has not yet reached `consecutiveThreshold`. Used to quickly confirm persistence or\n\t * reset transient divergences. Defaults to 10 seconds.\n\t */\n\tfastIntervalMs?: number\n}\n\nconst DEFAULT_CONSECUTIVE_THRESHOLD = 2\nconst DEFAULT_SETTLE_BACKOFF_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 32_000]\nconst DEFAULT_SLOW_INTERVAL_MS = 10 * 60_000\nconst DEFAULT_FAST_INTERVAL_MS = 10_000\n\ntype DivergenceKey = string\n\ninterface CounterState {\n\tentry: DivergenceEntry\n\tcount: number\n}\n\nfunction divergenceKey(entry: DivergenceEntry): DivergenceKey {\n\treturn `${entry.localId}|${entry.treeSaveId ?? \"\"}|${entry.backendSaveId ?? \"\"}`\n}\n\n/**\n * Continuously samples tree \u2194 backend divergence via the provided `sample` callback, and logs\n * a divergence entry only after it has persisted across `consecutiveThreshold`\n * consecutive samples. Entries that appear transiently (e.g. during remote event propagation)\n * never reach the threshold and are silently dropped.\n *\n * Each logged divergence shape is remembered for the life of the reporter and suppressed on\n * subsequent samples, so a persistent divergence is logged at most once per session.\n *\n * The reporter owns all scheduling state (timers, per-entry counters, session-logged set) and\n * has no knowledge of the storage internals \u2014 just the `sample` function.\n */\nexport class ModulesDivergenceReporter {\n\tprivate readonly sample: ModulesDivergenceReporterParams[\"sample\"]\n\tprivate readonly runWhenIdle: ModulesDivergenceReporterParams[\"runWhenIdle\"]\n\tprivate readonly abortSignal?: AbortSignal\n\n\tprivate readonly consecutiveThreshold: number\n\tprivate readonly settleBackoffMs: readonly number[]\n\tprivate readonly slowIntervalMs: number\n\tprivate readonly fastIntervalMs: number\n\n\tprivate pendingTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate settleAttempt = 0\n\tprivate started = false\n\n\t/** Active counters for currently-tracked divergence shapes that have not yet been logged. */\n\tprivate readonly counters = new Map<DivergenceKey, CounterState>()\n\t/** Divergence shapes already logged in this session. Ignored on future samples. */\n\tprivate readonly sessionLoggedKeys = new Set<DivergenceKey>()\n\n\tconstructor(params: ModulesDivergenceReporterParams) {\n\t\tthis.sample = params.sample\n\t\tthis.runWhenIdle = params.runWhenIdle\n\t\tthis.abortSignal = params.abortSignal\n\n\t\tthis.consecutiveThreshold = params.consecutiveThreshold ?? DEFAULT_CONSECUTIVE_THRESHOLD\n\t\tthis.settleBackoffMs = params.settleBackoffMs ?? DEFAULT_SETTLE_BACKOFF_MS\n\t\tthis.slowIntervalMs = params.slowIntervalMs ?? DEFAULT_SLOW_INTERVAL_MS\n\t\tthis.fastIntervalMs = params.fastIntervalMs ?? DEFAULT_FAST_INTERVAL_MS\n\n\t\tthis.abortSignal?.addEventListener(\"abort\", () => {\n\t\t\tif (this.pendingTimer !== null) {\n\t\t\t\tclearTimeout(this.pendingTimer)\n\t\t\t\tthis.pendingTimer = null\n\t\t\t}\n\t\t})\n\t}\n\n\tstart(): void {\n\t\tif (this.started) return\n\t\tthis.started = true\n\t\tlog.debug(\"started\", {\n\t\t\tthreshold: this.consecutiveThreshold,\n\t\t\tslowIntervalMs: this.slowIntervalMs,\n\t\t\tfastIntervalMs: this.fastIntervalMs,\n\t\t})\n\t\tthis.scheduleNext(0)\n\t}\n\n\tsampleNow(): void {\n\t\tthis.scheduleNext(0)\n\t}\n\n\tprivate scheduleNext(delayMs: number): void {\n\t\tif (this.abortSignal?.aborted) return\n\t\tif (this.pendingTimer !== null) {\n\t\t\tclearTimeout(this.pendingTimer)\n\t\t}\n\t\tthis.pendingTimer = setTimeout(() => {\n\t\t\tthis.pendingTimer = null\n\t\t\tif (this.abortSignal?.aborted) return\n\t\t\tthis.runWhenIdle(() => {\n\t\t\t\tif (this.abortSignal?.aborted) return\n\t\t\t\tthis.runSample().catch(unhandledError)\n\t\t\t})\n\t\t}, delayMs)\n\t}\n\n\tprivate async runSample(): Promise<void> {\n\t\tlet outcome: SampleOutcome | undefined\n\t\ttry {\n\t\t\toutcome = await this.sample()\n\t\t} catch (error) {\n\t\t\tif (this.abortSignal?.aborted) return\n\t\t\tlog.debug(\"failed to sample modules divergence\", { error })\n\t\t\tthis.handleNotSettled()\n\t\t\treturn\n\t\t}\n\n\t\tif (this.abortSignal?.aborted) return\n\n\t\tswitch (outcome.kind) {\n\t\t\tcase \"notSettled\":\n\t\t\t\tthis.handleNotSettled()\n\t\t\t\treturn\n\t\t\tcase \"sampled\":\n\t\t\t\tthis.settleAttempt = 0\n\t\t\t\tthis.handleSampled(outcome.divergences)\n\t\t\t\treturn\n\t\t}\n\t}\n\n\tprivate handleNotSettled(): void {\n\t\tconst delay = this.settleBackoffMs[this.settleAttempt]\n\t\tif (delay === undefined) {\n\t\t\t// Exhausted settle attempts for this round \u2014 wait a full slow interval before trying\n\t\t\t// again, so we don't hammer a busy project.\n\t\t\tlog.debug(\"sample notSettled, backoff exhausted, waiting slow interval\", {\n\t\t\t\tnextDelayMs: this.slowIntervalMs,\n\t\t\t})\n\t\t\tthis.settleAttempt = 0\n\t\t\tthis.scheduleNext(this.slowIntervalMs)\n\t\t\treturn\n\t\t}\n\t\tlog.debug(\"sample notSettled, retrying with backoff\", {\n\t\t\tattempt: this.settleAttempt,\n\t\t\tnextDelayMs: delay,\n\t\t})\n\t\tthis.settleAttempt += 1\n\t\tthis.scheduleNext(delay)\n\t}\n\n\tprivate handleSampled(divergences: readonly DivergenceEntry[]): void {\n\t\tconst seen = new Set<DivergenceKey>()\n\t\tconst sampledDivergences: DivergenceEntry[] = []\n\t\tconst alreadySeenDivergences: DivergenceEntry[] = []\n\t\tfor (const entry of divergences) {\n\t\t\tconst key = divergenceKey(entry)\n\t\t\tif (this.sessionLoggedKeys.has(key)) {\n\t\t\t\talreadySeenDivergences.push(entry)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsampledDivergences.push(entry)\n\t\t\tseen.add(key)\n\t\t\tconst existing = this.counters.get(key)\n\t\t\tif (existing) {\n\t\t\t\texisting.count += 1\n\t\t\t} else {\n\t\t\t\tthis.counters.set(key, { entry, count: 1 })\n\t\t\t}\n\t\t}\n\n\t\tfor (const key of this.counters.keys()) {\n\t\t\tif (!seen.has(key)) this.counters.delete(key)\n\t\t}\n\n\t\tconst settledDivergences: DivergenceEntry[] = []\n\t\tfor (const [key, state] of this.counters.entries()) {\n\t\t\tif (state.count >= this.consecutiveThreshold) {\n\t\t\t\tthis.sessionLoggedKeys.add(key)\n\t\t\t\tthis.counters.delete(key)\n\t\t\t\tsettledDivergences.push(state.entry)\n\t\t\t}\n\t\t}\n\n\t\tconst nextDelayMs = this.counters.size > 0 ? this.fastIntervalMs : this.slowIntervalMs\n\t\tthis.scheduleNext(nextDelayMs)\n\n\t\tlog.debug(\"sampled\", {\n\t\t\tsampledDivergences,\n\t\t\tsettledDivergences,\n\t\t\talreadySeenDivergences,\n\t\t\tnextDelayMs,\n\t\t})\n\t}\n}\n\nexport function computeModulesTreeBackendDivergence(\n\tlocalModuleNodes: readonly LocalModuleNode[],\n\tbackendModules: readonly ModulesAPI.ModuleWithSave[],\n): DivergenceEntry[] {\n\tconst treeSaveIdByLocalId = new Map<LocalModuleId, string>()\n\tconst treeModuleIdByLocalId = new Map<LocalModuleId, string>()\n\tfor (const node of localModuleNodes) {\n\t\tconst localId = asLocalId(node.id)\n\t\ttreeSaveIdByLocalId.set(localId, node.save.saveId)\n\t\ttreeModuleIdByLocalId.set(localId, node.save.moduleId)\n\t}\n\n\tconst backendSaveIdByLocalId = new Map<LocalModuleId, string>()\n\tconst backendModuleIdByLocalId = new Map<LocalModuleId, string>()\n\tfor (const mod of backendModules) {\n\t\tconst localId = asLocalId(mod.localId)\n\t\tbackendSaveIdByLocalId.set(localId, mod.saveId)\n\t\tbackendModuleIdByLocalId.set(localId, mod.id)\n\t}\n\n\tconst divergences: DivergenceEntry[] = []\n\n\tfor (const [localId, backendSaveId] of backendSaveIdByLocalId) {\n\t\tconst treeSaveId = treeSaveIdByLocalId.get(localId)\n\t\tif (treeSaveId === undefined) {\n\t\t\tdivergences.push({ localId, treeSaveId: null, backendSaveId })\n\t\t} else if (treeSaveId !== backendSaveId) {\n\t\t\tconst treeModuleId = treeModuleIdByLocalId.get(localId)\n\t\t\tconst backendModuleId = backendModuleIdByLocalId.get(localId)\n\t\t\t// During project duplication, backend modules can be duplicated before the tree is\n\t\t\t// updated to point at their new module ids. That transient mismatch is expected.\n\t\t\tif (treeModuleId !== undefined && backendModuleId !== undefined && treeModuleId !== backendModuleId) continue\n\t\t\tdivergences.push({ localId, treeSaveId, backendSaveId })\n\t\t}\n\t}\n\n\tfor (const [localId, treeSaveId] of treeSaveIdByLocalId) {\n\t\tif (!backendSaveIdByLocalId.has(localId)) {\n\t\t\tdivergences.push({ localId, treeSaveId, backendSaveId: null })\n\t\t}\n\t}\n\n\treturn divergences\n}\n", "import { ErrorCodes } from \"@framerjs/app-shared\"\nimport type { Draft, Immutable, Patch } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport { castDraft, produce, produceWithPatches } from \"@framerjs/app-shared/src/lib/immer.ts\"\nimport type { EntityDefinition } from \"@framerjs/framer-runtime\"\nimport type {\n\tExportSpecifier,\n\tModuleAnnotations,\n\tParsedAnnotations,\n\tParsedModuleAnnotations,\n} from \"@framerjs/framer-runtime/crossorigin\"\nimport { AnnotationKey } from \"@framerjs/framer-runtime/crossorigin\"\nimport { locks } from \"@framerjs/framer-runtime/utils/locks\"\nimport type { ModulesAPI, UnsafeJSON } from \"@framerjs/framer-services\"\nimport { ServiceError } from \"@framerjs/framer-services\"\nimport type { ExternalModuleExportIdentifier, GlobalModuleId, LocalModuleId } from \"@framerjs/shared\"\nimport {\n\tDEPENDENCIES_FILE_ID,\n\tDEPENDENCIES_MODULE_NAME,\n\tDEPENDENCIES_MODULE_TYPE,\n\tDEPENDENCIES_MODULE_TYPE_SLASH_NAME,\n\tIMPORT_MAP_FILE_ID,\n\tModuleType,\n\tResolvablePromise,\n\tasGlobalId,\n\tasLocalId,\n\tassert,\n\tassertNever,\n\texternalModuleIdentifier,\n\tgetLogger,\n\tgetServiceMap,\n\tisLocalModuleIdentifier,\n\tisModuleExportIdentifier,\n\tlocalModuleIdForStableName,\n\tlocalModuleImportMapSpecifier,\n\tparseModuleIdentifier,\n\tstableTypeAndNameFromLocalId,\n\tunhandledError,\n} from \"@framerjs/shared\"\nimport {\n\thasLocalModuleImportMapPrefix,\n\thasMissingModuleImportSpecifierPrefix,\n} from \"@framerjs/shared/src/moduleIdentifiers.ts\"\nimport type { KitClipboardData } from \"app/ai/sections/getKitSectionNodeData.ts\"\nimport type { VectorSetDictionary } from \"app/ai/sections/types.ts\"\nimport type { WireframerKitJSON } from \"app/ai/utils/wireframerKit.ts\"\nimport { experiments } from \"app/experiments.ts\"\nimport { getUniqueName } from \"code-editor/utils.ts\"\nimport type { CodeGenerationTelemetrySession } from \"code-generation/TelemetrySession.ts\"\nimport { getCompatibleCmsVersion, hasCmsDependency } from \"code-generation/cmsVersion.ts\"\nimport type { KitSection } from \"code-generation/utils/KitSectionStructureCollector.ts\"\nimport { parseTrackingIdsAnnotation } from \"code-generation/utils/TrackingIdCollector.ts\"\nimport type { BaseEngineScheduler } from \"document/base-engine/BaseEngine.ts\"\nimport type { CanvasTree, LoadedScopeNode, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport type { ReadonlyChildList } from \"document/models/CanvasTree/nodes/ChildList.ts\"\nimport { ERROR_LIST_NODE_ID, ErrorListNode } from \"document/models/CanvasTree/nodes/ErrorListNode.ts\"\nimport type { ErrorNode } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport { isErrorNodeTypeResolvedByCodeGeneration } from \"document/models/CanvasTree/nodes/ErrorNode.ts\"\nimport type { ModuleSaveData } from \"document/models/CanvasTree/nodes/LocalModuleNode.ts\"\nimport {\n\tLOCAL_MODULES_LIST_ID,\n\tLocalModuleNode,\n\tLocalModulesListNode,\n\tisLocalModuleNode,\n} from \"document/models/CanvasTree/nodes/LocalModuleNode.ts\"\nimport { isWebPageNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport { sourceNodeIdForModule } from \"document/utils/moduleSourceNodeHelpers.ts\"\nimport { isEqual } from \"library/index.ts\"\nimport type { DeepMutable, Mutable } from \"utils/Mutable.ts\"\nimport { randomBase62 } from \"utils/base62.ts\"\nimport { getKeys } from \"utils/getKeys.ts\"\nimport { isShallowObjectEqual } from \"utils/isShallowEqual.ts\"\nimport { isArray, isNull, isNumber, isString, isUndefined } from \"utils/typeChecks.ts\"\nimport { performanceClearMarks, performanceMark, performanceMeasure } from \"utils/userTiming.ts\"\nimport { toast } from \"web/lib/toaster.ts\"\nimport { record } from \"web/lib/tracker.ts\"\nimport { CODE_FORMATTING_TAB_WIDTH } from \"../code-editor/formatting.ts\"\nimport { markLoadingPerf } from \"../utils/performanceTracker.ts\"\nimport { LimitedRunner } from \"../web/lib/LimitedRunner.ts\"\nimport type { DependencyGraph } from \"./DependencyGraph.ts\"\nimport {\n\tcollectModuleAndItsDependentsRecursively,\n\tcreateDependencyGraph,\n\tdeleteNode,\n\thasCircularImports,\n\tupsertNode,\n} from \"./DependencyGraph.ts\"\nimport type { SampleOutcome } from \"./ModulesDivergenceReporter.ts\"\nimport { ModulesDivergenceReporter, computeModulesTreeBackendDivergence } from \"./ModulesDivergenceReporter.ts\"\nimport type { BinaryAssets } from \"./binaryAssets.ts\"\nimport type { CodeWithRelativeImports, compileModule } from \"./compiler.ts\"\nimport { COMPILER_CONTRACT_VERSION } from \"./compilerContractVersion.ts\"\nimport type { ModuleFilenames } from \"./filenamesFromModuleName.ts\"\nimport { filenamesFromModuleName } from \"./filenamesFromModuleName.ts\"\nimport { getCodeComponentModuleTypeSlashNamesInScope } from \"./getCodeComponentModuleTypeSlashNamesInScope.ts\"\nimport type { InstallDescriptor, PackageResolution } from \"./importMapManager.ts\"\nimport {\n\tPROVIDED_DEPENDENCIES,\n\tRESOLUTIONS,\n\taddDependencies,\n\tassertIsImportMap,\n\textendDependencies,\n\textendImportMap,\n\tgenerateDependenciesFromImportMap,\n\tgenerateImportMapFromDependencies,\n\tgenerateImportMapFromEntryPoints,\n\tgetImportMapKey,\n\tgetStaticImportMap,\n\tisBlockedDependency,\n\tparsePackageUrl,\n\treinstallDependencies,\n\tremoveBlockedDependencies,\n\tuninstallBlockedDependencies,\n\tunsafeUpgradeDependency,\n} from \"./importMapManager.ts\"\nimport { isModulesInTreeOn } from \"./isModulesInTreeOn.ts\"\nimport type { ReplacementMap } from \"./rewriteRelativeImports.ts\"\nimport {\n\tRewriteRelativeImportsError,\n\tescapeRegExp,\n\tisRewriteRelativeImportsError,\n\trewriteRelativeImports,\n} from \"./rewriteRelativeImports.ts\"\nimport type { SubmoduleFilename } from \"./submodules.ts\"\nimport { getSubmoduleFilename, getSubmoduleImport, parseSubmoduleImport } from \"./submodules.ts\"\nimport type {\n\tDependenciesMap,\n\tImportMap,\n\tModuleName,\n\tRelativeFilePath,\n\tSaveId,\n\tSubmoduleContents,\n\tSubmodules,\n\tTypeSlashName,\n} from \"./types.ts\"\nimport { ModuleMetadata } from \"./types.ts\"\nimport {\n\tcreateRelativePath,\n\tgetTypeSlashName,\n\tisEvaluatedModuleType,\n\tnormalizePath,\n\tparseModuleAnnotations,\n\tsplitTypeSlashName,\n} from \"./utils.ts\"\n\nconst log = getLogger(\"modules-storage\")\n\nexport const kitModuleName = \"kit\"\n\nconst emptySubmoduleContents: SubmoduleContents = Object.freeze({})\nconst emptyBinaryAssets: BinaryAssets = Object.freeze({})\n\n// Works around type restrictions in our services runtime.\ntype FixedModuleWithSave = Omit<ModulesAPI.ModuleWithSave, \"localId\" | \"id\" | \"metadata\"> & {\n\treadonly id: GlobalModuleId\n\treadonly localId: LocalModuleId\n\treadonly metadata: Record<string, unknown>\n}\n\n// `update` in `PersistedModuleCommon`, `TransientModuleSave`, `ModuleEntryCommon` is a timestamp\n// rather than a counter because then you don't need to have a reference to the previous state to\n// get the new `update` at the time of an update, just `performance.now()` to get the new value.\n\ntype PersistedModuleCommon = FixedModuleWithSave & {\n\treadonly moduleURL: string\n\treadonly imports: ModulesAPI.Imports\n\t/** `performance.now()` at the time of the last update. */\n\treadonly update: number\n}\n\n/** DependenciesModule is one of a kind module that requires special handling in most situations. */\nexport interface DependenciesModule extends FixedModuleWithSave {\n\treadonly kind: \"dependencies\"\n\treadonly id: GlobalModuleId\n\treadonly localId: LocalModuleId\n\treadonly type: ModuleType.Config\n\treadonly name: typeof DEPENDENCIES_MODULE_NAME\n\treadonly importMapContent: string\n\treadonly dependenciesMapContent: string\n}\n\n/** Server modules rely on server data. They might not have sourceContent. */\ninterface PersistedServerModule extends PersistedModuleCommon {\n\treadonly kind: \"server\"\n\treadonly sourceContent?: string\n}\n\n/** Local modules have been locally compiled, have source content, module content, and possibly a source map. */\ninterface PersistedLocalModule extends PersistedModuleCommon {\n\treadonly kind: \"local\"\n\treadonly sourceContent: string\n\treadonly moduleContent: CodeWithRelativeImports\n\treadonly sourceMapContent: string | undefined\n\treadonly submoduleContents: SubmoduleContents\n\treadonly binaryAssetContents: BinaryAssets\n\treadonly annotations?: ModuleAnnotations\n}\n\n// These types keep immer happy as it wants writable fields for its drafts.\ntype MakeDraftable<T extends FixedModuleWithSave> = Omit<T, \"exports\" | \"reExportedModules\" | \"imports\"> & {\n\texports: string[]\n\treExportedModules: string[]\n\timports: {\n\t\tabsolute: string[]\n\t\trelative: string[]\n\t\tbare: string[]\n\t}\n\tsubmodules: string[]\n\tbinaryAssets: string[]\n}\n\ntype PersistedServerModuleDraft = MakeDraftable<PersistedServerModule>\ntype PersistedLocalModuleDraft = MakeDraftable<PersistedLocalModule>\n\nexport type PersistedModule = PersistedLocalModule | PersistedServerModule\n\ntype TransientModuleSave = Omit<\n\tModulesAPI.BatchSave,\n\t\"description\" | \"files\" | \"moduleId\" | \"metadata\" | \"patchSaveId\" | \"title\" | \"transferEncoding\" | \"detached\"\n> & {\n\t/**\n\t * The value is undefined if the save is for a newly created module\n\t * for which localId must be determined by the server, e.g. a newly created codeFile module.\n\t */\n\treadonly localId: LocalModuleId | undefined\n\treadonly metadata?: PersistParams[\"metadata\"]\n\treadonly moduleContent: CodeWithRelativeImports\n\treadonly sourceContent: string\n\treadonly sourceMapContent: string | undefined\n\treadonly submoduleContents: SubmoduleContents\n\treadonly binaryAssetContents: BinaryAssets\n\treadonly imports: ModulesAPI.Imports\n\treadonly treeVersion?: number\n\treadonly sourceRevision?: number\n\treadonly saveId: string\n\treadonly annotations?: ModuleAnnotations\n\treadonly svgIcon?: string\n\treadonly kitSectionsStructure?: KitSection[]\n\t/** `performance.now()` at the time of the last update. */\n\treadonly update: number\n}\n\ninterface SnapshotMetadata {\n\treadonly patches: Patch[]\n\treadonly hasLocalChanges: boolean\n\treadonly didRemoteChange: boolean\n\t/** True if the state update is caused by a multiplayer event. */\n\treadonly multiplayerChange: boolean\n}\n\ninterface ModuleEntryCommon {\n\tlocalId: LocalModuleId\n\ttype: string\n\tname: ModuleName\n\trelativeImports: readonly RelativeFilePath[]\n\t/** `performance.now()` at the time of the last update, inherited from transient/persisted modules. */\n\tupdate: number\n\tsourceRevision?: number\n}\n\nexport interface ServerModuleEntry extends ModuleEntryCommon {\n\tkind: \"server\"\n\tsourceContent?: string\n\tmoduleURL: string\n\tfiles: Record<string, string>\n}\n\nexport interface LocalModuleEntry extends ModuleEntryCommon {\n\tkind: \"local\"\n\tsourceContent: string\n\tmoduleContent: string\n\tsourceMapContent: string | undefined\n\tsubmoduleContents: SubmoduleContents\n\tbinaryAssetContents: BinaryAssets | undefined\n\tmoduleURL: string\n\tfiles: Record<string, string>\n\tsvgIcon: string | undefined\n}\n\nexport interface FastRefreshModuleEntry extends ModuleEntryCommon {\n\tkind: \"fast-refresh\"\n\tsourceContent: string\n\tmoduleContent: string\n\tsourceMapContent: string | undefined\n\t// These are currently unsupported for FastRefresh modules\n\tsubmoduleContents: SubmoduleContents\n\tbinaryAssetContents: BinaryAssets | undefined\n}\n\nexport type ModuleEntry = ServerModuleEntry | LocalModuleEntry | FastRefreshModuleEntry\n\n/**\n * The dependencies module is a unique module that requires special handling in most situations.\n */\nexport interface DependenciesModuleEntry {\n\tkind: \"dependencies\"\n\tlocalId: typeof DEPENDENCIES_MODULE_TYPE_SLASH_NAME\n\ttype: ModuleType.Config\n\tname: typeof DEPENDENCIES_MODULE_NAME\n\timportMapContent: string\n\tdependenciesMapContent: string\n}\n\n/** Module entries that are editable in the code editor (Code or Shader). */\ninterface EditableModuleEntry extends ModuleEntryCommon {\n\treadonly kind: \"local\" | \"server\"\n\ttype: ModuleType.Code | ModuleType.Shader\n\treadonly sourceContent: string\n}\n\n/** Checks if a module entry is editable in the code editor (Code or Shader). */\nexport function isEditableModuleEntry(\n\tmodule: (ModuleEntryCommon & { sourceContent?: string }) | null | undefined,\n): module is EditableModuleEntry {\n\tif (!module) return false\n\tif (module.type === ModuleType.Code || module.type === ModuleType.Shader) {\n\t\tassert(isString(module.sourceContent), `${module.type} module entry is missing source content`)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunction isDependenciesModuleData(data: { type: string; name: string }): boolean {\n\treturn data.name === DEPENDENCIES_MODULE_NAME && data.type === DEPENDENCIES_MODULE_TYPE\n}\n\nfunction isDependenciesModuleNode(node: LocalModuleNode): boolean {\n\treturn node.id === DEPENDENCIES_MODULE_TYPE_SLASH_NAME\n}\n\nfunction equalIdAndSave(module: { id: string; saveId: string } | undefined, save: ModuleSaveData): boolean {\n\treturn !!module && module.saveId === save.saveId && module.id === save.moduleId\n}\n\ntype ModulesMap = Map<TypeSlashName, ModuleEntry>\n\nexport interface ModulesStorageStateSnapshot {\n\tdependenciesModule: DependenciesModuleEntry | undefined\n\tmodules: Immutable<ModulesMap>\n\tdeletedLocalIdsByTypeSlashNames: Record<TypeSlashName, LocalModuleId>\n\tdepsGraph: DependencyGraph\n\tmetadata: SnapshotMetadata\n\tinitialized: boolean\n}\n\nexport type ModulesStorageListener = (snapshot: ModulesStorageStateSnapshot) => void\n\ntype UnsubscribeFn = () => void\n\nexport type PersistParams = Omit<\n\tDeepMutable<ModulesAPI.BatchSave>,\n\t| \"files\"\n\t| \"metadata\"\n\t| \"moduleId\"\n\t| \"saveId\"\n\t| \"transferEncoding\"\n\t| \"exports\"\n\t| \"reExportedModules\"\n\t| \"imports\"\n\t| \"detached\"\n> & {\n\t/** Any additional files to upload besides the source. */\n\tfiles?: ModulesAPI.FileUpload[]\n\t/** Values to add or update on the module's metadata. */\n\tmetadata?: { [K in ModuleMetadata]?: unknown }\n\ttreeVersion?: number\n\terrors?: ErrorNode[]\n\tkitSectionsStructure?: KitSection[]\n}\n\ntype CreateParams = PersistParams & {\n\t/** The module source code to save. */\n\tsource: string\n\tsourceRevision?: number\n\tsvgIcon?: string\n}\n\nclass CircularDependencyError extends Error {\n\tconstructor() {\n\t\tsuper(\"A circular dependency was detected.\")\n\t\tthis.name = \"CircularDependencyError\"\n\t}\n}\n\ninterface UpdateSourceOptions {\n\tsource: string\n\t/**\n\t * The name and source of each submodule. All submodules are compiled and\n\t * persisted with the main module.\n\t */\n\tsubmodules?: Submodules\n\t/** A set of binary assets to proxy via blob URLs in local modules. */\n\tbinaryAssets?: BinaryAssets\n\t/** Specify true in cases where the module being updated has an immutable name. */\n\tstableName?: boolean\n\t/** A set of asset keys (with extensions) used in the source code. */\n\tassets?: Set<string>\n\t/** Specify true to reject with a CircularDependencyError if there\u2019s an import cycle. */\n\tpreventCircularImports?: boolean\n\ttelemetrySession?: CodeGenerationTelemetrySession\n\ttreeVersion?: number\n\tsourceRevision?: number\n\tsvgIcon?: string\n\tkitSectionsStructure?: KitSection[]\n}\n\nexport type HandleUpdateSourceOptions = Omit<UpdateSourceOptions, \"source\">\n\nexport interface ModuleUpdateSource {\n\tlocalId: LocalModuleId\n\tsource: string\n\toptions: HandleUpdateSourceOptions\n}\n\nconst LOCKED_RESOURCE_NAME = \"update-modules-storage\"\n\nlet synchronizeMarkCounter = 0\n\nasync function synchronize<R>(callback: () => R | Promise<R>): Promise<R> {\n\tconst start = performance.now()\n\tconst markName = `acquire-modules-storage-lock-${synchronizeMarkCounter++}`\n\tperformanceMark(markName)\n\treturn locks.request(LOCKED_RESOURCE_NAME, () => {\n\t\tconst timeTook = performance.now() - start\n\t\tperformanceMeasure(`\uD83D\uDD13 Acquire ${LOCKED_RESOURCE_NAME} lock`, markName)\n\t\tperformanceClearMarks(markName)\n\t\tlog.debug(\"\uD83D\uDD13 Acquired the\", LOCKED_RESOURCE_NAME, \"lock in\", timeTook.toFixed(2), \"ms\")\n\t\tif (timeTook > 1000) {\n\t\t\tlog.warn(\"\u2757 Long wait: it took\", timeTook.toFixed(0), \"ms to acquire the\", LOCKED_RESOURCE_NAME, \"lock.\")\n\t\t}\n\t\treturn callback()\n\t})\n}\n\nclass ModuleHandleBase<T extends string> {\n\tconstructor(\n\t\tprotected readonly storage: ModulesStorage,\n\t\tpublic readonly localId: LocalModuleId,\n\t\tpublic readonly type: T,\n\t\tprivate debugModuleStoreAndComponentLoaderRevisionsMatch: () => boolean,\n\t) {}\n\n\t/** Whether the underlying module data exists (has a transient save or persisted module). */\n\tisValid(): boolean {\n\t\treturn (\n\t\t\tthis.storage.getTransientSaveByLocalId(this.localId) !== undefined ||\n\t\t\tthis.storage.getPersistedModuleByLocalId(this.localId) !== undefined\n\t\t)\n\t}\n\n\tget id(): GlobalModuleId {\n\t\tconst module = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\tif (module) return module.id\n\t\tconst node = this.storage.getModuleTreeData(this.localId)\n\t\tassert(node, \"Module must exist\")\n\t\treturn asGlobalId(node.moduleId)\n\t}\n\n\tget saveId(): string {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\t\tif (transientSave) return transientSave.saveId\n\t\tconst module = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\tassert(module, \"Module must exist\")\n\t\treturn module.saveId\n\t}\n\n\tget transientSVGIcon(): string | undefined {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\t\tif (transientSave) return transientSave.svgIcon\n\t\treturn undefined\n\t}\n\n\tget lastPublish(): ModulesAPI.PublishInfo | null {\n\t\tconst persistedModule = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\treturn persistedModule?.lastPublish ?? null\n\t}\n\n\texternalModuleIdentifier(exportSpecifier: ExportSpecifier = \"default\"): ExternalModuleExportIdentifier {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\t\tif (transientSave) {\n\t\t\tconst names = filenamesFromModuleName(transientSave.name)\n\t\t\treturn externalModuleIdentifier(this.id, transientSave.saveId, names.module, exportSpecifier)\n\t\t}\n\n\t\tconst module = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\tassert(module?.files.module, \"ModulesStorage: Expected module typed file in persisted module.\")\n\t\treturn externalModuleIdentifier(this.id, module.saveId, module.files.module, exportSpecifier)\n\t}\n\n\tdelete() {\n\t\treturn this.storage.delete(this.localId)\n\t}\n\n\tpublish(namespace: string, name: string, version: string): Promise<ModulesAPI.Publish> {\n\t\treturn this.storage.publish(this.localId, { namespace, name, version })\n\t}\n\n\tsourceRevision(): number | undefined {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\t\tif (transientSave) return transientSave.sourceRevision\n\t\tconst persistedModule = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\tif (!persistedModule) return undefined\n\t\treturn sourceRevisionForPersistedModule(persistedModule)\n\t}\n\n\t/**\n\t * Get the annotations of a module that are statically extracted from\n\t * compilation, avoiding issues that may be caused by the componentLoader.\n\t *\n\t * To validate the timings of the updates, temporarily, if the latest\n\t * evaluated sandbox revision and ModulesStore revisions are the same,\n\t * differences between the annotations will be logged to Sentry.\n\t *\n\t * If no annotations are returned, you may need to manually fallback to the\n\t * entity.annotations value, optionally waiting for the latest evaluation.\n\t *\n\t * ```typescript\n\t * const entity = componentLoader.componentForIdentifier(node.instanceIdentifier)\n\t * const annotations = engine.modulesStore.forType(type).getByStableName(node.id).annotations(entity)\n\t * ```\n\t */\n\tannotations(debugEntity: EntityDefinition | null): ParsedModuleAnnotations | undefined\n\tannotations(debugEntity: EntityDefinition | null, exportSpecifier: ExportSpecifier): ParsedAnnotations | undefined\n\tannotations(\n\t\tdebugEntity: EntityDefinition | null,\n\t\texportSpecifier?: ExportSpecifier,\n\t): ParsedModuleAnnotations | ParsedAnnotations | undefined {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\n\t\tconst annotations = transientSave?.annotations\n\t\t\t? parseModuleAnnotations(transientSave.annotations)\n\t\t\t: this.storage.getModuleTreeData(this.localId)?.annotations\n\n\t\t// Temporarily, when valid to compare, report to Sentry if annotations\n\t\t// don't match the component loader.\n\t\tif (debugEntity && this.debugModuleStoreAndComponentLoaderRevisionsMatch()) {\n\t\t\tdebugEntityAnnotationsMatch(annotations, debugEntity)\n\t\t}\n\n\t\treturn exportSpecifier ? annotations?.[exportSpecifier] : annotations\n\t}\n}\n\nexport type PersistOptions = Omit<PersistParams, \"type\" | \"name\">\nclass ModuleByStableNameHandle<T extends string> extends ModuleHandleBase<T> {\n\tconstructor(\n\t\tstorage: ModulesStorage,\n\t\tlocalId: LocalModuleId,\n\t\ttype: T,\n\t\tdebugModuleStoreAndComponentLoaderRevisionsMatch: () => boolean,\n\t\tprivate readonly name: string,\n\t) {\n\t\tsuper(storage, localId, type, debugModuleStoreAndComponentLoaderRevisionsMatch)\n\t}\n\n\tcurrentSourceEquals(source: string, options: HandleUpdateSourceOptions): boolean {\n\t\tconst persistedModule = this.storage.getPersistedModuleByLocalId(this.localId)\n\t\tif (!persistedModule) return false\n\t\t// TODO: Implement hash comparison for compiled submodule content.\n\t\t// Currently, if either the persisted module or the new source contains\n\t\t// submodules, we cannot accurately compare the compiled source content.\n\t\t// As a workaround, we return false if submodules are present in either case.\n\t\tif (persistedModule.submodules.length || options.submodules?.size) {\n\t\t\treturn false\n\t\t}\n\t\treturn persistedModule.sourceContent === source\n\t}\n\n\tupdateSource(source: string, options: HandleUpdateSourceOptions = {}): Promise<boolean> {\n\t\treturn this.storage.updateSources([{ localId: this.localId, source, options: { ...options, stableName: true } }])\n\t}\n\n\tpersist(params: PersistOptions): Promise<void> {\n\t\treturn this.storage.upsert(this.localId, { ...params, type: this.type, name: this.name })\n\t}\n\n\t/**\n\t * A WebPageNode can store information about which kit sections were used when generating the\n\t * page with wireframer. This information is collected during code-generation, and stored\n\t * in-memory until the transient module is persisted, at which point it is written to the tree.\n\t *\n\t * This method returns whichever value is more recent.\n\t */\n\tgetKitSectionsStructure(): KitSection[] | undefined {\n\t\tconst transientSave = this.storage.getTransientSaveByLocalId(this.localId)\n\t\tif (transientSave) return transientSave.kitSectionsStructure\n\n\t\treturn this.storage.getKitSectionsStructure(this.name)\n\t}\n}\n\nfunction debugEntityAnnotationsMatch(staticAnnotations: ParsedModuleAnnotations | undefined, entity: EntityDefinition) {\n\t// If we don't have any static annotations, assume that we haven't recorded\n\t// them yet, and don't try to compare them.\n\tif (!staticAnnotations) return\n\n\tconst identifier = parseModuleIdentifier(entity.identifier)\n\tassert(isLocalModuleIdentifier(identifier) && isModuleExportIdentifier(identifier), \"Entity must have an identifier.\")\n\n\tif (\n\t\tentity.annotations &&\n\t\tidentifier.exportSpecifier in staticAnnotations &&\n\t\t!isEqual(\n\t\t\tstaticAnnotations[identifier.exportSpecifier],\n\t\t\tparseModuleAnnotations({ default: entity.annotations }).default,\n\t\t\ttrue,\n\t\t)\n\t) {\n\t\t// Log if both annotations have an entry for the entity export\n\t\t// identifier, but the values are different.\n\t\tlog.reportError(\"Static annotations are not synchronized with runtime annotations.\", {\n\t\t\tidentifier: entity.identifier,\n\t\t})\n\t}\n}\n\nfunction sourceRevisionForPersistedModule(persistedModule: PersistedModule): number | undefined {\n\tconst metadataRevision = persistedModule?.metadata[ModuleMetadata.SourceRevision]\n\treturn isNumber(metadataRevision) ? metadataRevision : undefined\n}\n\nclass ModuleByLocalIdHandle<T extends ModuleType> extends ModuleHandleBase<T> {\n\tupdateSource(source: string, options?: HandleUpdateSourceOptions): Promise<boolean> {\n\t\treturn this.storage.updateSources([{ localId: this.localId, source, options: options ?? {} }])\n\t}\n\n\tpersist(params: PersistOptions): Promise<void> {\n\t\treturn this.storage.update(this.localId, params)\n\t}\n\n\trename(newName: string): Promise<void> {\n\t\treturn this.storage.rename(this.localId, newName)\n\t}\n}\n\nexport type ModuleHandle<T extends ModuleType> = ModuleByLocalIdHandle<T> | ModuleByStableNameHandle<T>\n\nexport class TypedModulesStorage<T extends ModuleType> {\n\tconstructor(\n\t\tprivate readonly storage: ModulesStorage,\n\t\tpublic readonly type: T,\n\t\tprivate readonly moduleStoreAndComponentLoaderRevisionsMatch: () => boolean = () => true,\n\t) {}\n\n\tpublic async create(params: Omit<CreateParams, \"type\">): Promise<LocalModuleId> {\n\t\treturn this.storage.create({ ...params, type: this.type })\n\t}\n\n\tpublic getByStableName(name: string): ModuleByStableNameHandle<T> {\n\t\treturn new ModuleByStableNameHandle(\n\t\t\tthis.storage,\n\t\t\tlocalModuleIdForStableName(this.type, name),\n\t\t\tthis.type,\n\t\t\tthis.moduleStoreAndComponentLoaderRevisionsMatch,\n\t\t\tname,\n\t\t)\n\t}\n\n\tpublic getByLocalId(id: LocalModuleId): ModuleByLocalIdHandle<T> {\n\t\treturn new ModuleByLocalIdHandle(this.storage, id, this.type, this.moduleStoreAndComponentLoaderRevisionsMatch)\n\t}\n\n\tpublic getUniqueName(desiredName: string): string {\n\t\treturn this.storage.getUniqueNameForType(this.type, desiredName)\n\t}\n}\n\ntype PersistedModules = ReadonlyMap<LocalModuleId, PersistedServerModule | PersistedLocalModule>\n\ntype TransientSaves = ReadonlyMap<LocalModuleId, TransientModuleSave>\n\ninterface CreatedBatch {\n\tprimaryBatch: ModulesAPI.BatchSave[]\n\tdependentBatch: ModulesAPI.BatchSave[]\n\tdependentLocalIdWaves: LocalModuleId[][]\n\tnextPersistedModules: PersistedModules\n}\n\ninterface ModuleTreeData {\n\tid: string\n\tsaveId: string\n\timports?: ModulesAPI.Imports\n\ttitle: string\n\tname: string\n\ttype: string\n\tsourceRevision?: number\n\tannotations?: ModuleAnnotations\n\tmetadata: Record<string, unknown>\n}\n\ninterface TransientSaveResult {\n\tnextPersistedModules: PersistedModules\n\ttransientSave: TransientModuleSave\n\tdata: readonly ModulesAPI.ModuleWithSave[]\n}\n\nexport class ModulesStorage {\n\t/**\n\t * Whether to use the tree's LocalModulesListNode as the source of the modules used by this project.\n\t *\n\t * Used when looking at a historic version of the document, or when {@link isModulesInTreeOn}.\n\t *\n\t * This starts false because the loaded document tree is not available when ModulesStorage is\n\t * constructed. {@link initializeInternal} updates it after `engine.load` has installed the tree.\n\t */\n\tprivate useTreeAsLocalModuleList = false\n\n\t/** Whether saves should be marked as detached when persisting them to the backend. */\n\tprivate detached = false\n\n\tprivate dependenciesModule: DependenciesModule | undefined\n\n\tprivate persistedModules: PersistedModules = new Map()\n\n\t/**\n\t * Sometimes we need to quickly retrieve a persistedModule by its typeSlashName.\n\t * This operation can be called multiple times for the same persistedModules map.\n\t * We keep this weak map as a cache so that the iteration through all the entries of the persistedModules\n\t * happens at most once.\n\t */\n\tprivate persistedLocalIdsByTypeSlashNameCache = new WeakMap<\n\t\tPersistedModules,\n\t\tReadonlyMap<TypeSlashName, LocalModuleId>\n\t>()\n\n\tprivate transientSaves: TransientSaves = new Map()\n\n\tprivate lastSnapshot: Pick<\n\t\tModulesStorageStateSnapshot,\n\t\t\"dependenciesModule\" | \"modules\" | \"depsGraph\" | \"initialized\"\n\t> = {\n\t\tdependenciesModule: undefined,\n\t\tmodules: new Map(),\n\t\tdepsGraph: {},\n\t\tinitialized: false,\n\t}\n\n\tprivate modulesService: ModulesAPI.Interface | undefined = undefined\n\n\t/**\n\t * When we create a transient save, we make any visible dependent server\n\t * modules local (recursively). This ensures that the changes are visible.\n\t * We skip server modules that are not rendered to improve performance.\n\t *\n\t * When those server modules become visible, we need to make them local.\n\t */\n\tprivate lazyServerModulesForTransientSaves = new Map<TypeSlashName, Set<TypeSlashName>>()\n\n\tprivate hasPendingServerModules() {\n\t\treturn this.lazyServerModulesForTransientSaves.size > 0\n\t}\n\n\t/**\n\t * Make one server module that is a dependency of a locally changed module\n\t * local until there are no lazy server modules left to make local. We do\n\t * one at a time instead of a batch so that it is less likely that we slow\n\t * down subsequent scope switches.\n\t */\n\tprivate processOnePendingServerModule(): Promise<boolean> {\n\t\tif (this.lazyServerModulesForTransientSaves.size === 0) return Promise.resolve(false)\n\n\t\t// We must run this task synchronized so we don't do duplicate work as\n\t\t// other tasks like updating another module or switching scopes.\n\t\treturn synchronize(async () => {\n\t\t\tfor (const [, list] of this.lazyServerModulesForTransientSaves) {\n\t\t\t\tfor (const typeSlashName of list) {\n\t\t\t\t\t// @FIXME -- This won't work for code files, whose typeSlashName is not the\n\t\t\t\t\t// localId.\n\t\t\t\t\tconst localId = this.persistedModules.get(typeSlashName as any)?.localId\n\t\t\t\t\tif (!localId) continue\n\t\t\t\t\tconst module = this.persistedModules.get(localId)\n\t\t\t\t\tif (module?.kind !== \"server\") continue\n\n\t\t\t\t\tlog.debug(\"\uD83C\uDF43 Process one server \u2192 local module\", typeSlashName)\n\t\t\t\t\tconst local = await this.createLocalModuleFromModule(module)\n\t\t\t\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\t\t\t\tdraft.set(module.localId, local)\n\t\t\t\t\t})\n\n\t\t\t\t\tthis.setNextInternalState({\n\t\t\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\t\t\tpersistedModules: nextPersistedModules,\n\t\t\t\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\t\t\t\tdidRemoteChange: false,\n\t\t\t\t\t\ttransientSaves: this.transientSaves,\n\t\t\t\t\t})\n\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\t}\n\n\t/**\n\t * When changing scope, make any lazy dependent server modules that weren't\n\t * previously visible when their dependency was updated, local so that we\n\t * can render an accurate version on the canvas. This optimizes the case\n\t * where we changed a smart component with many server dependents so we can\n\t * render the change quickly.\n\t */\n\tasync changeScope(scope: LoadedScopeNode) {\n\t\t// If there are no server modules we need to make local we don't need to\n\t\t// check for code components in the scope.\n\t\tif (!this.hasPendingServerModules()) return\n\n\t\tconst visibleModules = getCodeComponentModuleTypeSlashNamesInScope(scope)\n\n\t\t// If there are no code components in the current scope, we don't need\n\t\t// to make any server modules local.\n\t\tif (!visibleModules || visibleModules.size === 0) return\n\n\t\tawait synchronize(async () => {\n\t\t\tconst visibleDependentModules = new Set<TypeSlashName>()\n\n\t\t\tconst dependencyGraph = this.lastSnapshot.depsGraph\n\n\t\t\tfor (const [typeSlashName, lazyDependentServerModules] of this.lazyServerModulesForTransientSaves) {\n\t\t\t\tcollectModuleAndItsDependentsRecursively(\n\t\t\t\t\tdependencyGraph,\n\t\t\t\t\ttypeSlashName,\n\t\t\t\t\tlazyDependentServerModules,\n\t\t\t\t\tvisibleModules,\n\t\t\t\t\tvisibleDependentModules,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tconst serverModules: Promise<PersistedLocalModuleDraft>[] = []\n\t\t\tfor (const dependentTypeSlashName of visibleDependentModules) {\n\t\t\t\tconst module = this.getModuleWithTypeSlashName(dependentTypeSlashName)\n\t\t\t\tif (module?.kind !== \"server\") continue\n\t\t\t\tserverModules.push(this.createLocalModuleFromModule(module))\n\t\t\t}\n\n\t\t\tlog.debug(\n\t\t\t\t\"\uD83C\uDF43 Prioritizing making visible modules local after changing scope:\",\n\t\t\t\tscope.id,\n\t\t\t\t\"/ Visible:\",\n\t\t\t\tvisibleModules,\n\t\t\t\t\"/ Visible Dependencies:\",\n\t\t\t\tvisibleDependentModules,\n\t\t\t\t\"/ Server modules:\",\n\t\t\t\tserverModules.length,\n\t\t\t)\n\n\t\t\tif (serverModules.length === 0) return\n\n\t\t\tconst createdLocalModules = await Promise.all(serverModules)\n\t\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\t\tfor (const module of createdLocalModules) {\n\t\t\t\t\tdraft.set(module.localId, module)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\tpersistedModules: nextPersistedModules,\n\t\t\t\tdepsGraph: dependencyGraph,\n\t\t\t\tdidRemoteChange: false,\n\t\t\t\ttransientSaves: this.transientSaves,\n\t\t\t})\n\t\t})\n\n\t\tvoid this.makeLazyServerModulesLocalWhenIdle().catch(unhandledError)\n\t}\n\n\tprivate async makeVisibleDependentServerModulesLocal(batch: ModuleUpdateSource[]) {\n\t\tif (!experiments.isOn(\"prioritizedModuleEvaluation\")) {\n\t\t\treturn\n\t\t}\n\n\t\t// The scope may have changed since we started the serialization /\n\t\t// compilation of the module we are updating, and we may now be\n\t\t// rendering a page that includes an instance or includes dependents of\n\t\t// the instance we just updated. In this case we optimize which\n\t\t// dependents are made local to improve canvas performance.\n\n\t\t// capture active scope\n\t\t// get visible dependencies\n\t\tconst scope = this.getActiveScope()\n\t\tconst visibleDependentModules = new Set<TypeSlashName>()\n\t\tconst priority = getCodeComponentModuleTypeSlashNamesInScope(scope)\n\n\t\t// Dependents of the updated module which are not visible in the current\n\t\t// scope and are server modules don't need to be made local immediately,\n\t\t// as there will be no visible benefit. Instead they can be cached in\n\t\t// memory and made local on demand when switching scopes, or when the\n\t\t// updated module is persisted.\n\t\tconst lazyDependentServerModules = new Set<TypeSlashName>()\n\n\t\tfor (const update of batch) {\n\t\t\tconst info = this.typeAndNameFromLocalId(update.localId, update.options.stableName)\n\t\t\tconst typeSlashName = getTypeSlashName(info)\n\n\t\t\tconst nextDepsGraph = this.lastSnapshot.depsGraph\n\t\t\tcollectModuleAndItsDependentsRecursively(\n\t\t\t\tnextDepsGraph,\n\t\t\t\ttypeSlashName,\n\t\t\t\tlazyDependentServerModules,\n\t\t\t\tpriority,\n\t\t\t\tvisibleDependentModules,\n\t\t\t)\n\n\t\t\t// Record the dependent modules that don't need to be made local at this\n\t\t\t// time so they can be made local on demand.\n\t\t\tthis.lazyServerModulesForTransientSaves.set(typeSlashName, lazyDependentServerModules)\n\n\t\t\t// No need to make the changed module local (it already is).\n\t\t\tvisibleDependentModules.delete(typeSlashName)\n\t\t}\n\t\tconst serverModules: Promise<PersistedLocalModuleDraft>[] = []\n\n\t\tfor (const dependentTypeSlashName of visibleDependentModules) {\n\t\t\tconst module = this.getModuleWithTypeSlashName(dependentTypeSlashName)\n\t\t\tif (module?.kind !== \"server\") continue\n\t\t\tserverModules.push(this.createLocalModuleFromModule(module))\n\t\t}\n\n\t\tlog.debug(\n\t\t\t\"\uD83C\uDF43 Prioritizing dependent server modules after updating:\",\n\t\t\tbatch.map(b => b.localId),\n\t\t\t\"/ Visible:\",\n\t\t\tvisibleDependentModules,\n\t\t\t\"/ Lazy:\",\n\t\t\tlazyDependentServerModules,\n\t\t\t\"/ Server modules:\",\n\t\t\tserverModules.length,\n\t\t)\n\n\t\t// Make dependent server modules local so the updated dependency is made\n\t\t// visible in the dependents.\n\t\tlet nextPersistedModules = this.persistedModules\n\t\tif (serverModules.length > 0) {\n\t\t\tconst createdLocalModules = await Promise.all(serverModules)\n\t\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\t\tfor (const module of createdLocalModules) {\n\t\t\t\t\tdraft.set(module.localId, module)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\tthis.persistedModules = nextPersistedModules\n\t}\n\n\tprivate backgroundJob: Promise<void> | null = null\n\tprivate backgroundAbortController: AbortController | null = null\n\n\t/**\n\t * When we update modules, we make all visible dependent server modules\n\t * local so that the change can be rendered on the canvas. When switching\n\t * scopes, we prioritize making the remaining dependencies that become\n\t * visible local. This optimization ensures we do the minimum amount of work\n\t * to render up-to-date modules every time we switch to a new scope.\n\t *\n\t * Making a server module local only when we have switched to a new scope\n\t * creates a small flash. To reduce the likelihood of this happening on\n\t * subsequent navigation, we run a background task when the engine is idle\n\t * that makes any remaining dependents local before they become visible.\n\t */\n\tprivate async makeLazyServerModulesLocalWhenIdle(): Promise<void> {\n\t\tthis.cancelBackgroundJob()\n\t\tthis.backgroundAbortController = new AbortController()\n\t\tconst { signal } = this.backgroundAbortController\n\n\t\tthis.backgroundJob = (async () => {\n\t\t\ttry {\n\t\t\t\twhile (this.hasPendingServerModules()) {\n\t\t\t\t\tif (signal.aborted) break\n\n\t\t\t\t\tconst promise = new ResolvablePromise<boolean>()\n\t\t\t\t\tthis.runWhenIdle(() => {\n\t\t\t\t\t\tif (signal.aborted) {\n\t\t\t\t\t\t\tpromise.resolve(false)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.processOnePendingServerModule().then(promise.resolve, promise.reject)\n\t\t\t\t\t})\n\t\t\t\t\tconst didWork = await promise\n\t\t\t\t\tif (!didWork) break\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tthis.backgroundJob = null\n\t\t\t\tthis.backgroundAbortController = null\n\t\t\t}\n\t\t})()\n\n\t\treturn this.backgroundJob\n\t}\n\n\tprivate cancelBackgroundJob() {\n\t\tif (this.backgroundAbortController) {\n\t\t\tthis.backgroundAbortController.abort()\n\t\t}\n\t}\n\n\tconstructor(\n\t\tprivate readonly getModulesService: () => Promise<ModulesAPI.Interface | undefined>,\n\t\tprivate readonly compile: typeof compileModule,\n\t\tprivate process: BaseEngineScheduler[\"process\"],\n\t\tprivate processWhenReady: BaseEngineScheduler[\"processWhenReady\"],\n\t\tprivate runWhenIdle: BaseEngineScheduler[\"runWhenIdle\"],\n\t\tprivate treeStore: { tree: CanvasTree; remoteTreeVersion: number },\n\t\tprivate readonly getActiveScope: () => LoadedScopeNode | undefined,\n\t\tprivate readonly makeDocumentReadOnly: () => void,\n\t\tprivate readonly abortSignal?: AbortSignal,\n\t) {}\n\n\tpublic initialized = false\n\tprivate initializationStarted = false\n\tprivate readOnlyTree = false\n\n\tprivate preInitListPromise: Promise<ModulesAPI.ListResponse | undefined> | undefined\n\n\t/**\n\t * Eagerly resolves the modules service and fires the list request so the\n\t * data is already in-flight when {@link initialize} is called later.\n\t * Idempotent \u2014 safe to call multiple times.\n\t *\n\t * No-op when modules-in-tree is on, since initialization will source modules from the canvas\n\t * tree via `lookUpModules` and never consume the list response.\n\t */\n\tpublic preInit(): void {\n\t\tif (this.preInitListPromise) return\n\n\t\t// Not checking useTreeAsLocalModuleList, because it's not yet initialized at this point.\n\t\tif (isModulesInTreeOn()) return\n\n\t\tmarkLoadingPerf(\"modulesStorageStart\")\n\t\tthis.preInitListPromise = this.getModulesService()\n\t\t\t.then(service => service?.list({}))\n\t\t\t.catch(err => {\n\t\t\t\tlog.error(err, { context: \"preInit: failed to pre-fetch modules list\" })\n\t\t\t\treturn undefined\n\t\t\t})\n\t}\n\n\tgetTransientSave(localId: LocalModuleId) {\n\t\treturn this.transientSaves.get(localId)\n\t}\n\n\tisReadOnly(): boolean {\n\t\treturn this.readOnlyTree\n\t}\n\n\t/** Can be called when the underlying document is changing in some big way, like history loading\n\t * an older version of the document. Might result in modules not saving to the backend, or not\n\t * being written to the tree. */\n\tresetModuleStateAndPermissions(mode: \"readonly\" | \"readwrite\" | \"readwrite-detached\") {\n\t\tthis.readOnlyTree = mode === \"readonly\"\n\t\tthis.useTreeAsLocalModuleList =\n\t\t\tmode === \"readonly\" ||\n\t\t\tmode === \"readwrite-detached\" ||\n\t\t\t(isModulesInTreeOn() && this.treeStore.tree.has(LOCAL_MODULES_LIST_ID))\n\t\tthis.detached = mode === \"readwrite-detached\"\n\n\t\t// Make sure we listen to the module event stream if needed and initialized enough.\n\t\tif (!this.useTreeAsLocalModuleList && this.modulesService) {\n\t\t\tthis.setupModuleEventStreamIfNeeded()\n\t\t}\n\n\t\t// Clear any tree operations we buffered.\n\t\tthis.treeNodesToUpdate.clear()\n\t\tthis.treeNodesToDelete = []\n\n\t\t// Don't hold on to any transient saves. Modules will synchronize again with the tree or\n\t\t// from the backend.\n\t\tif (this.transientSaves.size > 0) {\n\t\t\tlog.reportErrorOncePerMinute(new Error(\"Discarding transient saves\"), { count: this.transientSaves.size })\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\tpersistedModules: this.persistedModules,\n\t\t\t\ttransientSaves: new Map(),\n\t\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\t\tdidRemoteChange: true,\n\t\t\t})\n\t\t}\n\t}\n\n\tasync waitForModulesToSave(): Promise<void> {\n\t\tconst localIds = Array.from(this.transientSaves.keys())\n\t\tfor (const localId of localIds) {\n\t\t\tif (this.transientSaves.has(localId)) {\n\t\t\t\tawait this.update(localId, {})\n\t\t\t}\n\t\t}\n\n\t\tconst rest = this.transientSaves.size\n\t\tif (rest > 0) {\n\t\t\tlog.warn(\"waitForModulesToSave: transientSaves seems to be growing, ignoring rest:\", rest)\n\t\t}\n\t}\n\n\tprivate resolveInitialization: () => void = () => {\n\t\tthrow new Error(\"initializationPromise has not executed yet\")\n\t}\n\tprivate rejectInitialization: (err: Error) => void = () => {\n\t\tthrow new Error(\"initializationPromise has not executed yet\")\n\t}\n\tprivate readonly initializationPromise: Promise<void> = new Promise((resolve, reject) => {\n\t\tthis.resolveInitialization = resolve\n\t\tthis.rejectInitialization = reject\n\t})\n\n\tpublic async initialize(): Promise<void> {\n\t\tif (this.initializationStarted) return this.initializationPromise\n\n\t\tthis.initializationStarted = true\n\t\tthis.initializeInternal().then(this.resolveInitialization, err => {\n\t\t\tlog.reportError(err, { context: \"Failed to initialize ModulesStorage: \" })\n\t\t\tthis.rejectInitialization(err)\n\t\t})\n\t\treturn this.initializationPromise\n\t}\n\n\tprivate didSetupModuleEventStream = false\n\tprivate setupModuleEventStreamIfNeeded() {\n\t\t// Run this setup only once. Might be called long after intialization, as the document\n\t\t// downgrades from using the tree as source back to using the backend.\n\t\tif (this.didSetupModuleEventStream) return\n\t\tthis.didSetupModuleEventStream = true\n\n\t\tassert(this.modulesService, \"ModulesStorage.useModuleEventStream: expected modules service to be initialized\")\n\t\tthis.modulesService\n\t\t\t.moduleEventsStream()\n\t\t\t.read(async ({ events }) => {\n\t\t\t\tconst saveEvents = events.filter(isSaveEvent)\n\t\t\t\tthis.handleRemoteModuleSaveEvents(saveEvents).catch(log.reportError)\n\n\t\t\t\tconst deleteEvents = events.filter(isDeleteEvent)\n\t\t\t\tthis.handleRemoteModuleDeleteEvents(deleteEvents).catch(log.reportError)\n\t\t\t})\n\t\t\t.catch(err => {\n\t\t\t\tlog.reportError(err, { context: \"Failed to read ModulesAPI event stream: \" })\n\t\t\t})\n\t}\n\n\tprivate transientInfo: Set<string> | null = null\n\n\tprivate async initializeInternal(): Promise<void> {\n\t\tthis.modulesService = await this.getModulesService()\n\t\tif (!this.modulesService) return\n\t\tconst localModuleNodes = LocalModulesListNode.get(this.treeStore.tree)?.children\n\n\t\tif (isModulesInTreeOn()) {\n\t\t\tthis.useTreeAsLocalModuleList = true\n\t\t}\n\n\t\t// This might be a very old project that hasn't yet written any modules to the tree.\n\t\t//\n\t\t// In that case, fall back to using the backend, and the tree will get backfilled when\n\t\t// editing the project via createLocalModulesListNodeIfNeeded. Then, on next refresh, we'll\n\t\t// start using the tree.\n\t\t//\n\t\t// Why not just run the backfill here? Because the project might be read-only. Note that\n\t\t// we'll have to solve that somehow before we can completely switch over to using the tree.\n\t\tconst hasModulesListNode = this.treeStore.tree.has(LOCAL_MODULES_LIST_ID)\n\t\tif (!hasModulesListNode && this.useTreeAsLocalModuleList) {\n\t\t\tlog.reportError(\"Can't useTreeAsLocalModuleList in a project that doesn't have a local modules list node\")\n\t\t\tthis.useTreeAsLocalModuleList = false\n\t\t}\n\n\t\tif (!this.useTreeAsLocalModuleList) {\n\t\t\tthis.setupModuleEventStreamIfNeeded()\n\t\t}\n\n\t\tlet response: ModulesAPI.ListResponse | ModulesAPI.LookupResponse\n\n\t\tconst start = performance.now()\n\t\tif (this.useTreeAsLocalModuleList) {\n\t\t\tlog.info(\"init from tree data\")\n\t\t\tthis.previousLocalModuleNodes = localModuleNodes\n\t\t\tif (!localModuleNodes || localModuleNodes.length === 0) {\n\t\t\t\tresponse = { data: [] }\n\t\t\t} else {\n\t\t\t\tconst queries = localModuleNodes.map(n => ({\n\t\t\t\t\tmoduleId: n.save.moduleId as GlobalModuleId,\n\t\t\t\t\tsaveId: n.save.saveId,\n\t\t\t\t}))\n\t\t\t\tresponse = await this.modulesService.lookUpModules({ queries })\n\t\t\t}\n\t\t} else {\n\t\t\tlog.info(\"init from module list\")\n\t\t\tconst preInitResponse = await this.preInitListPromise\n\t\t\tresponse = preInitResponse ?? (await this.modulesService.list({}))\n\t\t\t// Make sure to not hold on to the pre init promise too long.\n\t\t}\n\t\tthis.preInitListPromise = undefined\n\t\tmarkLoadingPerf(\"modulesStorageInit\")\n\t\tlog.debug(\"listing modules took:\", performance.now() - start, \"millis\")\n\n\t\tconst dependenciesModuleData = response.data.find(isDependenciesModuleData)\n\t\tif (dependenciesModuleData) {\n\t\t\tawait this.updateDependenciesModule(dependenciesModuleData)\n\t\t}\n\n\t\tconst persistedModules = new Map<LocalModuleId, PersistedModule>()\n\n\t\tlet dataLossCount = 0\n\t\tconst info = new Set<string>()\n\t\t// Process all the modules in parallel.\n\t\tawait Promise.all(\n\t\t\tresponse.data.map(async data => {\n\t\t\t\tif (getTypeSlashName(data) === DEPENDENCIES_MODULE_TYPE_SLASH_NAME) return\n\t\t\t\tconst entry = await this.createServerModuleFromData(data)\n\t\t\t\tlog.trace(\"init - create module\", entry.localId, entry.id, entry.saveId, entry.savedAt)\n\t\t\t\tpersistedModules.set(entry.localId, entry)\n\t\t\t\tif (localModuleNodes && checkDataLoss(localModuleNodes, data)) {\n\t\t\t\t\tdataLossCount += 1\n\t\t\t\t}\n\t\t\t\tinfo.add(entry.localId)\n\t\t\t}),\n\t\t)\n\n\t\tconst depsGraph = this.createDependencyGraph(persistedModules)\n\n\t\tthis.initialized = true\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\tmarkLoadingPerf(\"modulesStorageFirstPublish\")\n\n\t\t// Finally process any tree updates that might have happened while initializing.\n\t\tthis.processTreeUpdates({ writeTreeData: true })\n\n\t\tif (dataLossCount > 0) {\n\t\t\tlog.reportError(\"Data loss detected based on modules saves and modules in tree.\", { dataLossCount })\n\t\t}\n\t}\n\n\tprivate divergenceReporter: ModulesDivergenceReporter | undefined\n\n\tpublic startDivergenceReporter(): void {\n\t\tif (this.divergenceReporter) return\n\t\tif (!this.treeStore.tree.has(LOCAL_MODULES_LIST_ID)) return\n\n\t\tthis.divergenceReporter = new ModulesDivergenceReporter({\n\t\t\tsample: () => this.sampleModulesTreeBackendDivergences(),\n\t\t\trunWhenIdle: task => this.runWhenIdle(task),\n\t\t\tabortSignal: this.abortSignal,\n\t\t})\n\t\tthis.divergenceReporter.start()\n\t}\n\n\tpublic sampleDivergencesNow(): void {\n\t\tthis.divergenceReporter?.sampleNow()\n\t}\n\n\tprivate async sampleModulesTreeBackendDivergences(): Promise<SampleOutcome> {\n\t\treturn synchronize(async () => {\n\t\t\tif (\n\t\t\t\t!this.initialized ||\n\t\t\t\t!this.modulesService ||\n\t\t\t\tthis.transientSaves.size > 0 ||\n\t\t\t\tthis.hasPendingTreeData() ||\n\t\t\t\tthis.treeStore.tree.isViewOnly ||\n\t\t\t\tthis.detached\n\t\t\t) {\n\t\t\t\treturn { kind: \"notSettled\" }\n\t\t\t}\n\t\t\tconst localModuleNodes = LocalModulesListNode.getModuleNodes(this.treeStore.tree)\n\t\t\tconst { data } = await this.modulesService.list({})\n\t\t\tconst divergences = computeModulesTreeBackendDivergence(localModuleNodes, data)\n\t\t\treturn { kind: \"sampled\", divergences }\n\t\t})\n\t}\n\n\tprivate createDependencyGraph(persistedModules: PersistedModules): DependencyGraph {\n\t\tconst nextDepsGraphNodes: [TypeSlashName, readonly RelativeFilePath[]][] = []\n\t\tfor (const persistedModule of persistedModules.values()) {\n\t\t\tconst typeSlashName = getTypeSlashName(persistedModule)\n\t\t\tconst relativeImports = persistedModule.imports.relative\n\t\t\tnextDepsGraphNodes.push([typeSlashName, relativeImports])\n\t\t}\n\t\treturn createDependencyGraph(nextDepsGraphNodes)\n\t}\n\n\t// ** tree **\n\n\tpreviousLocalModuleNodes: ReadonlyChildList<LocalModuleNode> | undefined\n\ttreeNodesToUpdate = new Map<\n\t\tNodeID,\n\t\t{\n\t\t\ttreeVersion: number\n\t\t\terrors?: ErrorNode[]\n\t\t\tpersistedModule: ModuleTreeData\n\t\t\tkitSectionsStructure?: KitSection[]\n\t\t}\n\t>()\n\ttreeNodesToDelete: string[] = []\n\n\thasPendingTreeData(): boolean {\n\t\treturn this.treeNodesToUpdate.size > 0 || this.treeNodesToDelete.length > 0\n\t}\n\n\t// Called before the engine produces a new tree.\n\tprocessTreeUpdates({ writeTreeData }: { writeTreeData: boolean }) {\n\t\tif (!this.initialized) return\n\n\t\tthis.syncLocalModules().catch(err => {\n\t\t\tlog.reportError(new Error(\"Failed to sync local modules from tree\", { cause: err }))\n\t\t})\n\n\t\tif (writeTreeData) {\n\t\t\tthis.tryWriteTreeData()\n\t\t}\n\t}\n\n\tprivate async syncLocalModules() {\n\t\tif (!this.useTreeAsLocalModuleList) return\n\n\t\tconst localModuleNodes = LocalModulesListNode.get(this.treeStore.tree)?.children\n\t\tif (!localModuleNodes) return\n\t\tif (this.previousLocalModuleNodes === localModuleNodes) return\n\n\t\tconst queries: { moduleId: string; saveId: string }[] = []\n\t\tconst previousMap: Map<NodeID, LocalModuleNode> = new Map()\n\t\tthis.previousLocalModuleNodes?.forEach(node => {\n\t\t\tpreviousMap.set(node.id, node)\n\t\t})\n\t\tthis.previousLocalModuleNodes = localModuleNodes\n\n\t\tfor (const node of localModuleNodes) {\n\t\t\tconst previous = previousMap.get(node.id)\n\t\t\tpreviousMap.delete(node.id)\n\n\t\t\t// No change in the node.\n\t\t\tif (previous === node) continue\n\t\t\tconst save = node.save\n\n\t\t\t// Changed node data already loaded.\n\t\t\tconst existing = this.persistedModules.get(asLocalId(node.id))\n\t\t\tif (equalIdAndSave(existing, save)) continue\n\n\t\t\t// Change node is the dependency module and already up to date.\n\t\t\tif (isDependenciesModuleNode(node) && equalIdAndSave(this.dependenciesModule, save)) continue\n\n\t\t\t// We have to update the module.\n\t\t\tqueries.push({ moduleId: save.moduleId, saveId: save.saveId })\n\t\t\tlog.debug(\"syncLocalModules to update:\", node.id)\n\t\t}\n\n\t\t// Any leftover previous nodes got deleted with this update.\n\t\tif (previousMap.size > 0) {\n\t\t\tlog.debug(\"syncLocalModules removing:\", previousMap.keys())\n\t\t\tawait this.handleRemoteModuleDeletes(Array.from(previousMap.values()).map(n => asGlobalId(n.save.moduleId)))\n\t\t}\n\n\t\t// Lookup and download and evaluate any new or updated modules.\n\t\tif (queries.length > 0) {\n\t\t\tlog.debug(\"syncLocalModules updating:\", queries)\n\n\t\t\tassert(this.modulesService, \"ModulesStorage.refresh: expected modules service to be initialized\")\n\t\t\tconst start = performance.now()\n\t\t\tconst response = await this.modulesService.lookUpModules({ queries })\n\t\t\tlog.debug(\"lookupModules took:\", performance.now() - start, \"millis\")\n\n\t\t\tawait this.handleRemoteModuleSaves(response.data)\n\t\t}\n\t}\n\n\tprivate canWriteTree(): boolean {\n\t\treturn !this.treeStore.tree.isViewOnly\n\t}\n\n\tprivate tryWriteTreeData() {\n\t\tif (!this.canWriteTree()) return\n\t\tif (!this.hasPendingTreeData()) return\n\n\t\t// We are being called from engine.postProcess, so we should not update the tree right away\n\t\t// via process, but via processWhenReady.\n\t\tthis.processWhenReady(() => {\n\t\t\tif (!this.canWriteTree()) return\n\t\t\tthis.writeTreeData()\n\t\t}, \"nonUserEvent\")\n\t}\n\n\twriteTreeData() {\n\t\tif (!this.hasPendingTreeData()) return\n\n\t\tif (!this.canWriteTree()) {\n\t\t\tthrow new Error(\"Cannot write tree data\")\n\t\t}\n\n\t\tconst tree = this.treeStore.tree\n\t\ttree.lineage.setEditReason(\"localmodules\")\n\n\t\tthis.createLocalModulesListNodeIfNeeded(tree)\n\n\t\t// Process nodes to delete\n\t\tfor (const localId of this.treeNodesToDelete) {\n\t\t\tif (this.persistedModules.get(asLocalId(localId))) continue\n\t\t\tlog.debug(\"tryWriteTreeData, remove:\", localId)\n\t\t\ttree.remove(localId)\n\t\t}\n\t\tthis.treeNodesToDelete = []\n\n\t\t// Process nodes to update\n\n\t\tfor (const [localId, { treeVersion, errors, persistedModule }] of this.treeNodesToUpdate.entries()) {\n\t\t\t// Note, here we used to check if existing.save.treeVersion < treeVersion to move from last\n\t\t\t// writer wins to most up to date writer wins. But duplicates will have high treeVersions.\n\t\t\tif (this.persistedModules.get(asLocalId(localId))?.saveId !== persistedModule.saveId) continue\n\n\t\t\tlog.debug(\"tryWriteTreeData, write:\", localId, treeVersion, persistedModule.id, persistedModule.saveId, errors)\n\t\t\tthis.updateNode(tree, localId, treeVersion, persistedModule, errors)\n\t\t}\n\t\tthis.treeNodesToUpdate.clear()\n\t}\n\n\t/** Same as updateTreeNode, but without a treeVersion, used when patching depedencies. */\n\tprivate updateTreeNodeWithOwnTreeVersion(localId: string, persistedModule: ModuleTreeData): void {\n\t\tthis.process(() => {\n\t\t\tthis.treeStore.tree.lineage.setEditReason(\"localmodules\")\n\n\t\t\tthis.createLocalModulesListNodeIfNeeded(this.treeStore.tree)\n\t\t\tconst node = this.treeStore.tree.get<LocalModuleNode>(localId)\n\t\t\tconst treeVersion = node?.save.treeVersion ?? this.treeStore.remoteTreeVersion\n\t\t\tlog.debug(\n\t\t\t\t\"updateTreeNodeWithCurrentTreeVersion:\",\n\t\t\t\tlocalId,\n\t\t\t\ttreeVersion,\n\t\t\t\tpersistedModule.id,\n\t\t\t\tpersistedModule.saveId,\n\t\t\t)\n\t\t\tthis.updateNode(this.treeStore.tree, localId, treeVersion, persistedModule)\n\t\t}, \"nonUserEvent\")\n\t}\n\n\t/** Returns false if the current update has been superseded by a later update. */\n\tprivate updateTreeNode(\n\t\tlocalId: string,\n\t\ttreeVersion: number,\n\t\tpersistedModule: ModuleTreeData,\n\t\terrors?: ErrorNode[],\n\t\tkitSectionsStructure?: KitSection[],\n\t): boolean {\n\t\t// Note, here we used to check if existing.save.treeVersion < treeVersion to move from last\n\t\t// writer wins to most up to date writer wins. But duplicates will have high treeVersions.\n\n\t\tif (!this.canWriteTree()) {\n\t\t\tlog.debug(\"updateTreeNode - readonly, buffering change\")\n\t\t\tthis.treeNodesToUpdate.set(localId, { treeVersion, persistedModule, errors, kitSectionsStructure })\n\t\t\treturn true\n\t\t}\n\n\t\tthis.process(() => {\n\t\t\tthis.treeStore.tree.lineage.setEditReason(\"localmodules\")\n\t\t\tthis.createLocalModulesListNodeIfNeeded(this.treeStore.tree)\n\t\t\tlog.debug(\"updateTreeNode:\", localId, treeVersion, persistedModule.id, persistedModule.saveId)\n\t\t\tthis.updateNode(this.treeStore.tree, localId, treeVersion, persistedModule, errors, kitSectionsStructure)\n\t\t}, \"nonUserEvent\")\n\t\treturn true\n\t}\n\n\tprivate removeTreeNode(localId: string) {\n\t\tif (!this.canWriteTree()) {\n\t\t\tthis.treeNodesToDelete.push(localId)\n\t\t} else {\n\t\t\tthis.process(() => {\n\t\t\t\tlog.debug(\"removeTreeNode:\", localId)\n\t\t\t\tthis.treeStore.tree.remove(localId)\n\t\t\t})\n\t\t}\n\t}\n\n\t/**\n\t * After persisting a module to the ModulesService, update a LocalModuleNode\n\t * in the tree to record the latest save data. Additionally write any errors\n\t * to the tree that were recorded when serializing the module from a source\n\t * node. This is an atomic update in a single CanvasTree transaction to\n\t * ensure that the diff can't be rebased in a different order in multiplayer\n\t * scenarios.\n\t */\n\tprivate updateNode(\n\t\ttree: CanvasTree,\n\t\tlocalId: string,\n\t\ttreeVersion: number,\n\t\tmodule: ModuleTreeData,\n\t\terrors?: ErrorNode[],\n\t\tkitSectionsStructure?: KitSection[],\n\t) {\n\t\tconst node = tree.get(localId)?.asDraft() ?? new LocalModuleNode({ id: localId })\n\t\tassert(node instanceof LocalModuleNode)\n\t\tconst pluginId = module.metadata[ModuleMetadata.PluginId]\n\t\t// Annotations will be an empty object if the module is a local\n\t\t// compiled module. It will be undefined if we are patching an\n\t\t// external module without compiling. In that case we don't want to\n\t\t// overwrite the annotations.\n\t\tconst annotations = module.annotations ? parseModuleAnnotations(module.annotations) : node.save.annotations\n\t\tconst trackingIds = parseTrackingIdsAnnotation(annotations?.default?.[AnnotationKey.FramerTrackingIds])\n\t\tif (trackingIds) {\n\t\t\tannotations!.default![AnnotationKey.FramerTrackingIds] = trackingIds\n\t\t}\n\t\tconst save: ModuleSaveData = {\n\t\t\ttreeVersion,\n\t\t\tmoduleId: module.id,\n\t\t\tsaveId: module.saveId,\n\t\t\timports: module.imports?.relative,\n\t\t\ttitle: module.title,\n\t\t\tname: module.name,\n\t\t\ttype: module.type,\n\t\t\tsourceRevision: module.sourceRevision,\n\t\t\tannotations,\n\t\t\tpluginId: isString(pluginId) ? pluginId : node.save.pluginId,\n\t\t}\n\t\tnode.set({ save })\n\t\tif (!node.tree()) {\n\t\t\ttree.insertNode(node, LOCAL_MODULES_LIST_ID)\n\t\t}\n\n\t\t// The module name of a module generated from the tree is the source node id.\n\t\tconst sourceNodeId = sourceNodeIdForModule(module)\n\t\tif (!tree.has(sourceNodeId)) return\n\n\t\tthis.updateNodeKitSectionsStructure(tree, sourceNodeId, kitSectionsStructure)\n\n\t\tif (!errors) return\n\t\t// The list node may not exist. There is no need to ensure it if not\n\t\t// since there are no errors to remove in that case.\n\t\tconst maybeErrorListNode = tree.get<ErrorListNode>(ERROR_LIST_NODE_ID)\n\t\tlog.debug(\"Writing serialization errors from artifacts to tree for\", sourceNodeId)\n\n\t\t// Remove any errors that exist for nodes that have been regenerated.\n\t\tmaybeErrorListNode?.children?.forEach(error => {\n\t\t\tconst errorSourceNodeId = error.sourceNodeId ?? error.scopeId\n\t\t\t// Only remove errors for the module type we are persisting/updating.\n\t\t\tconst isModuleTypeError = isUndefined(error.sourceNodeModuleType) || module.type === error.sourceNodeModuleType\n\t\t\tif (\n\t\t\t\t!errorSourceNodeId ||\n\t\t\t\terrorSourceNodeId !== sourceNodeId ||\n\t\t\t\t!isModuleTypeError ||\n\t\t\t\t!isErrorNodeTypeResolvedByCodeGeneration(error.type)\n\t\t\t) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Unconditionally remove code-generation type errors of the module\n\t\t\t// type for the source node.\n\t\t\ttree.remove(error.id)\n\t\t})\n\n\t\t// If we don't need to add errors we don't need to ensure the list node.\n\t\tif (errors.length === 0) return\n\t\tconst listNode = ErrorListNode.ensure(tree)\n\t\terrors.forEach(error => tree.insertNode(error, listNode.id))\n\t}\n\n\t/** Update kit sections structure in web page node after module persistence */\n\tprivate updateNodeKitSectionsStructure(tree: CanvasTree, sourceNodeId: NodeID, kitSectionsStructure?: KitSection[]) {\n\t\tif (!isArray(kitSectionsStructure)) return\n\t\tconst sourceNode = tree.get(sourceNodeId)\n\t\tif (!isWebPageNode(sourceNode)) return\n\n\t\t// Don't update nodes unnecessarily if kitSectionsStructure didn't change, or if it is empty and\n\t\t// undefined before. This avoids regenerating modules unnecessarily if their\n\t\t// moduleSourceRevision hash happens to be outdated.\n\t\t// https://framer-team.slack.com/archives/CR3CYA1D4/p1770415760110039\n\t\tif (isEqual(sourceNode.kitSectionsStructure, kitSectionsStructure)) return\n\t\tif (kitSectionsStructure.length === 0 && isUndefined(sourceNode.kitSectionsStructure)) return\n\n\t\tsourceNode.set({ kitSectionsStructure })\n\t}\n\n\tgetModuleTreeData(localId: string) {\n\t\treturn this.treeStore.tree.getNodeWithTrait(localId, isLocalModuleNode)?.save\n\t}\n\n\tgetKitSectionsStructure(id: NodeID): KitSection[] | undefined {\n\t\tconst node = this.treeStore.tree.getNodeWithTrait(id, isWebPageNode)\n\t\treturn node?.kitSectionsStructure\n\t}\n\n\t/**\n\t * Does nothing if the localModulesListNode already exists. Otherwise will create the list node\n\t * and add all persistedModules.\n\t */\n\tcreateLocalModulesListNodeIfNeeded(tree: CanvasTree) {\n\t\tif (tree.has(LOCAL_MODULES_LIST_ID)) return\n\t\tif (!this.canWriteTree()) return\n\n\t\tlog.debug(\"ensureAllModulesExistInTree:\", this.persistedModules.size)\n\n\t\ttree.insertNode(new LocalModulesListNode())\n\t\tconst treeVersion = this.treeStore.remoteTreeVersion\n\t\tthis.persistedModules.forEach(m => {\n\t\t\tthis.updateNode(tree, m.localId, treeVersion, m)\n\t\t})\n\n\t\tif (this.dependenciesModule) {\n\t\t\tthis.updateNode(tree, DEPENDENCIES_MODULE_TYPE_SLASH_NAME, treeVersion, this.dependenciesModule)\n\t\t}\n\t}\n\n\t// ** end of tree **\n\n\tgetModuleWithTypeSlashName(typeSlashName: string): PersistedModule | undefined {\n\t\tconst localId = this.findPersistedModuleLocalIdByTypeSlashName(this.persistedModules, typeSlashName)\n\t\tif (!localId) return\n\t\treturn this.persistedModules.get(localId)\n\t}\n\n\tprivate async updateDependenciesModule(dependenciesModuleData: ModulesAPI.ModuleWithSave) {\n\t\tassert(\n\t\t\tisDependenciesModuleData(dependenciesModuleData),\n\t\t\t\"updateDependenciesModule called with non dependencies module data\",\n\t\t)\n\n\t\tconst dependenciesFiles: {\n\t\t\timportMapContent: string\n\t\t\tdependenciesMapContent?: string\n\t\t} = await this.getDependenciesFiles(dependenciesModuleData)\n\n\t\tlet dependenciesMapContent = dependenciesFiles?.dependenciesMapContent\n\n\t\t// backfill dependencies.json and persist if it was not available from the backend.\n\t\tif (!dependenciesMapContent) {\n\t\t\tconst importMap = JSON.parse(dependenciesFiles.importMapContent)\n\t\t\tconst dependenciesMap = generateDependenciesFromImportMap(importMap)\n\t\t\tdependenciesMapContent = JSON.stringify(dependenciesMap)\n\n\t\t\t// When we are read only we should not be writing to the backend.\n\t\t\tif (!this.readOnlyTree) {\n\t\t\t\tawait this.updateDependenciesLocked(importMap, dependenciesMap)\n\t\t\t\tlog.info(\"The missing dependencies file has now been created.\")\n\t\t\t} else {\n\t\t\t\tlog.reportError(new Error(\"modules storage is read only\"), {\n\t\t\t\t\tcontext: \"modules storage is read only while calling updateDependenciesModule\",\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tthis.dependenciesModule = {\n\t\t\tkind: \"dependencies\" as const,\n\t\t\t...dependenciesModuleData,\n\t\t\tid: asGlobalId(dependenciesModuleData.id),\n\t\t\tlocalId: asLocalId(dependenciesModuleData.localId),\n\t\t\ttype: ModuleType.Config,\n\t\t\tname: dependenciesModuleData.name as typeof DEPENDENCIES_MODULE_NAME,\n\t\t\timportMapContent: dependenciesFiles.importMapContent,\n\t\t\tdependenciesMapContent,\n\t\t}\n\t}\n\n\tprivate async createServerModuleFromData(data: ModulesAPI.ModuleWithSave): Promise<PersistedServerModule> {\n\t\tconst module: Mutable<PersistedServerModuleDraft> = {\n\t\t\tkind: \"server\",\n\t\t\t...castDraft(data),\n\t\t\tid: asGlobalId(data.id),\n\t\t\tlocalId: asLocalId(data.localId),\n\t\t\tmoduleURL: data.baseURL + (data.type === ModuleType.Kit ? data.files.source : data.files.module),\n\t\t\tupdate: performance.now(),\n\t\t}\n\n\t\t// Always download the source code for code component and shader modules.\n\t\t// We also download the webpage metadata, because as described here:\n\t\t// https://github.com/framer/FramerStudio/blob/566e3f0dbd7f2dd9b9f36336f4ed0702ac96df18/src/app/vekter/src/document/stores/CodeGenerationStore.ts#L462-L469\n\t\t// we update it more often than we need to. By downloading the source,\n\t\t// we can check if it actually changes and only update it if needed.\n\t\tif (\n\t\t\tmodule.type === ModuleType.Code ||\n\t\t\tmodule.type === ModuleType.Shader ||\n\t\t\tmodule.type === ModuleType.WebPageMetadata\n\t\t) {\n\t\t\tmodule.sourceContent = await this.fetchSourceContentFromData(data)\n\t\t}\n\n\t\t// If the module is a smart component or web pge that uses the CMS, we\n\t\t// can infer the compatibility by checking the source code.\n\t\tif (hasCmsDependency(module) && getCompatibleCmsVersion(module) === 0) {\n\t\t\tmodule.sourceContent = await this.fetchSourceContentFromData(data)\n\t\t\tconst version = module.sourceContent.includes(\"useQueryData\") ? 1 : 0\n\t\t\tmodule.metadata = { ...module.metadata, [ModuleMetadata.CompatibleCmsVersion]: version }\n\t\t}\n\n\t\treturn module\n\t}\n\n\tprivate async fetchSourceContentFromData(data: ModulesAPI.ModuleWithSave | PersistedModule): Promise<string> {\n\t\treturn this.downloadQueue.run(async () => {\n\t\t\tconst sourceURL = data.baseURL + data.files.source\n\t\t\tconst response = await fetch(sourceURL)\n\t\t\treturn response.text()\n\t\t})\n\t}\n\n\tasync refresh() {\n\t\tif (!this.initialized) return\n\t\tif (this.useTreeAsLocalModuleList) return\n\t\tlog.debug(\"refresh: acquiring lock\")\n\t\treturn synchronize(() => this.refreshLocked())\n\t}\n\n\tprivate async refreshLocked() {\n\t\tlog.debug(\"refresh: start\")\n\n\t\t// TODO if refresh results in same saveids we can avoid a lot of work.\n\n\t\tassert(this.modulesService, \"ModulesStorage.refresh: expected modules service to be initialized\")\n\t\tconst { data: modulesData } = await this.modulesService.list({})\n\t\tlog.debug(\"refresh: there's\", modulesData.length, \"modules to process\")\n\n\t\tconst persistedModules = new Map<LocalModuleId, PersistedModule>()\n\n\t\tconst info = new Set<string>()\n\t\tawait Promise.all(\n\t\t\tmodulesData.map(async data => {\n\t\t\t\tconst localId = asLocalId(data.localId)\n\n\t\t\t\t// Dependencies module requires special handling.\n\t\t\t\tif (isDependenciesModuleData(data)) {\n\t\t\t\t\tif (this.dependenciesModule?.saveId !== data.saveId) {\n\t\t\t\t\t\tawait this.updateDependenciesModule(data)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t//  If the module didn't change, we can re-use the existing entry.\n\t\t\t\tconst prevModule = this.persistedModules.get(localId)\n\t\t\t\tif (prevModule?.saveId === data.saveId) {\n\t\t\t\t\tpersistedModules.set(localId, prevModule)\n\t\t\t\t} else {\n\t\t\t\t\tconst entry = await this.createServerModuleFromData(data)\n\t\t\t\t\tlog.debug(\"refresh - updating module\", entry.localId, entry.id, entry.saveId, entry.savedAt)\n\t\t\t\t\tpersistedModules.set(localId, entry)\n\t\t\t\t}\n\n\t\t\t\tinfo.add(localId)\n\t\t\t}),\n\t\t)\n\n\t\tconst depsGraph = this.createDependencyGraph(persistedModules)\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: persistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\tlog.debug(\"refresh: finish\")\n\t}\n\n\tpublic whenInitialized(): Promise<void> {\n\t\treturn this.initializationPromise\n\t}\n\n\tpublic async whenIdle(): Promise<void> {\n\t\tawait Promise.all([this.whenInitialized(), synchronize(() => {})])\n\t}\n\n\tpublic isProcessing(): boolean {\n\t\tif (!this.initialized) return true\n\t\tif (this.transientSaves.size > 0) return true\n\t\tif (locks.isLocked(LOCKED_RESOURCE_NAME)) return true\n\t\treturn false\n\t}\n\n\tpublic hasLocalChanges(): boolean {\n\t\treturn this.transientSaves.size > 0\n\t}\n\n\tpublic hasLocalCodeFileChanges(): boolean {\n\t\tif (this.transientSaves.size === 0) return false\n\n\t\tfor (const save of this.transientSaves.values()) {\n\t\t\tif (save.type === ModuleType.Code || save.type === ModuleType.Shader || save.type === ModuleType.Config) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tprivate listeners: Set<ModulesStorageListener> = new Set()\n\tprivate addListener(listener: ModulesStorageListener): void {\n\t\tthis.listeners.add(listener)\n\t}\n\tprivate removeListener(listener: ModulesStorageListener): void {\n\t\tthis.listeners.delete(listener)\n\t}\n\tprivate notifyListeners(snapshot: ModulesStorageStateSnapshot): void {\n\t\tthis.listeners.forEach(listener => {\n\t\t\ttry {\n\t\t\t\tlistener(snapshot)\n\t\t\t} catch (err) {\n\t\t\t\tlog.reportError(err)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * Attaches the listener to the module changes\n\t * and immediately calls the listener with the latest snapshot.\n\t */\n\tpublic subscribe(listener: ModulesStorageListener): UnsubscribeFn {\n\t\tthis.addListener(listener)\n\t\tlistener(\n\t\t\ttakeStateSnapshot(\n\t\t\t\tthis.dependenciesModule,\n\t\t\t\tundefined,\n\t\t\t\tthis.persistedModules,\n\t\t\t\tthis.transientSaves,\n\t\t\t\tthis.lastSnapshot.depsGraph,\n\t\t\t\tnew Map(),\n\t\t\t\tthis.initialized,\n\t\t\t\tfalse,\n\t\t\t\tfalse,\n\t\t\t),\n\t\t)\n\n\t\treturn () => this.removeListener(listener)\n\t}\n\n\tpublic getDependentsOfModule(typeSlashName: TypeSlashName): Set<TypeSlashName> | undefined {\n\t\treturn this.lastSnapshot.depsGraph[typeSlashName]?.dependents\n\t}\n\n\tpublic getUniqueNameForType(type: ModuleType, desiredName: string): string {\n\t\tconst usedNames = new Set<string>()\n\t\tfor (const module of this.persistedModules.values()) {\n\t\t\tif (module.type !== type) continue\n\t\t\tusedNames.add(module.name)\n\t\t}\n\t\treturn getUniqueName(usedNames, desiredName)\n\t}\n\n\t/**\n\t * Optimistically updates the module's source without persisting the change.\n\t */\n\tpublic async updateSources(batch: ModuleUpdateSource[]) {\n\t\treturn synchronize(async () => {\n\t\t\tlet didUpdate = false\n\t\t\tfor (const { localId, source, options } of batch) {\n\t\t\t\tconst startTime = Date.now()\n\t\t\t\ttry {\n\t\t\t\t\tawait this.updateSourceLocked(localId, {\n\t\t\t\t\t\t...options,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t})\n\t\t\t\t\tdidUpdate = true\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// If compilation fails, return false to prevent attempting to\n\t\t\t\t\t// persist the module. If the error is specifically that a circular\n\t\t\t\t\t// dependency was detected -- and it's assumed that the circular\n\t\t\t\t\t// dependency was added locally -- throw toast that explains the\n\t\t\t\t\t// problem. Either way we won't attempt to persist the component\n\t\t\t\t\t// until the next successful compilation.\n\t\t\t\t\tif (error instanceof CircularDependencyError) {\n\t\t\t\t\t\ttoast({\n\t\t\t\t\t\t\ttype: \"add\",\n\t\t\t\t\t\t\tvariant: \"error\",\n\t\t\t\t\t\t\tprimaryText: \"Self-nested components\",\n\t\t\t\t\t\t\tsecondaryText: \"won\u2019t update.\",\n\t\t\t\t\t\t\tkey: \"component-circular-dependency\",\n\t\t\t\t\t\t\ticon: \"error\",\n\t\t\t\t\t\t\tduration: Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tlog.reportError(error)\n\t\t\t\t} finally {\n\t\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\t\tlog.debug(\"\u23F1 update source\", localId, \"in\", duration, \"ms\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait this.makeVisibleDependentServerModulesLocal(batch)\n\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\tpersistedModules: this.persistedModules,\n\t\t\t\ttransientSaves: this.transientSaves,\n\t\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\t\tdidRemoteChange: false,\n\t\t\t})\n\n\t\t\tvoid this.makeLazyServerModulesLocalWhenIdle().catch(unhandledError)\n\t\t\treturn didUpdate\n\t\t})\n\t}\n\n\tpublic async updateDependenciesSource(\n\t\tfileId: typeof IMPORT_MAP_FILE_ID | typeof DEPENDENCIES_FILE_ID,\n\t\tsource: string,\n\t) {\n\t\treturn synchronize(async () => {\n\t\t\tassert(this.dependenciesModule, \"Dependency files must already exist to be updated.\")\n\t\t\tconst importMapContent = fileId === IMPORT_MAP_FILE_ID ? source : this.dependenciesModule.importMapContent\n\t\t\tconst dependenciesContent =\n\t\t\t\tfileId === DEPENDENCIES_FILE_ID ? source : this.dependenciesModule.dependenciesMapContent\n\t\t\treturn this.updateDependenciesLocked(JSON.parse(importMapContent), JSON.parse(dependenciesContent))\n\t\t})\n\t}\n\n\tprivate async compileSubmodules(type: string, submodules: Submodules) {\n\t\tconst result: SubmoduleContents = {}\n\n\t\tawait Promise.all(\n\t\t\t[...submodules].map(async ([name, source]) => {\n\t\t\t\tconst compilation = await this.compile({\n\t\t\t\t\tname,\n\t\t\t\t\tsource,\n\t\t\t\t\ttype,\n\t\t\t\t\tincludeSourceMap: false,\n\t\t\t\t\taddFramerMetadata: false,\n\t\t\t\t})\n\n\t\t\t\t// Submodules don't track their own dependencies and therefore\n\t\t\t\t// we can't update them when a local module changes. To ensure\n\t\t\t\t// that submodules don't import local modules we forbid relative\n\t\t\t\t// imports. One way to use local modules in submodules is to\n\t\t\t\t// import them in the main module and inject them into the\n\t\t\t\t// submodule as a function parameter.\n\t\t\t\tfor (const relativeImport of compilation.imports.relative) {\n\t\t\t\t\tconst submoduleName = parseSubmoduleImport(relativeImport)\n\t\t\t\t\tif (submoduleName && submodules.has(submoduleName)) continue\n\t\t\t\t\tthrow new Error(\"Submodules only support relative imports of other submodules\")\n\t\t\t\t}\n\n\t\t\t\tconst filename = getSubmoduleFilename(name)\n\t\t\t\tresult[filename] = compilation.code\n\t\t\t}),\n\t\t)\n\n\t\treturn result\n\t}\n\n\tprivate typeAndNameFromLocalId(localId: LocalModuleId, stableName: boolean = false): { type: string; name: string } {\n\t\tif (stableName) {\n\t\t\t// For stably named modules, the local id is the type + slash + name.\n\t\t\treturn stableTypeAndNameFromLocalId(localId)\n\t\t}\n\t\t// For non-stably named modules they must first be created to get a local id.\n\t\tfor (const entry of this.lastSnapshot.modules.values()) {\n\t\t\tif (entry?.localId === localId) {\n\t\t\t\treturn entry\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Module entry for local id ${localId} missing in internal snapshot`)\n\t}\n\n\tprivate async updateSourceLocked(\n\t\tlocalId: LocalModuleId,\n\t\t{\n\t\t\tsource,\n\t\t\tsubmodules,\n\t\t\tbinaryAssets = emptyBinaryAssets,\n\t\t\tstableName = false,\n\t\t\tassets,\n\t\t\tpreventCircularImports,\n\t\t\ttelemetrySession,\n\t\t\ttreeVersion,\n\t\t\tsourceRevision,\n\t\t\tsvgIcon,\n\t\t\tkitSectionsStructure,\n\t\t}: UpdateSourceOptions,\n\t): Promise<void> {\n\t\tawait this.whenInitialized()\n\n\t\tconst info = this.typeAndNameFromLocalId(localId, stableName)\n\n\t\tconst typeSlashName = getTypeSlashName(info)\n\n\t\tconst compilation = await this.compile({\n\t\t\tlocalId,\n\t\t\tname: typeSlashName,\n\t\t\tsource,\n\t\t\ttype: info.type,\n\t\t\tincludeSourceMap: shouldIncludeSourceMap(info.type),\n\t\t\ttelemetrySession,\n\t\t})\n\n\t\tlet submoduleContents = emptySubmoduleContents\n\t\tif (submodules) submoduleContents = await this.compileSubmodules(info.type, submodules)\n\n\t\tconst nextDepsGraph = upsertNode(this.lastSnapshot.depsGraph, typeSlashName, compilation.imports.relative)\n\t\tif (preventCircularImports && hasCircularImports(nextDepsGraph, typeSlashName)) {\n\t\t\t// Source contains circular imports. Reject the request to update source.\n\t\t\tthrow new CircularDependencyError()\n\t\t}\n\n\t\tconst annotations = annotationsForModuleType(info.type as ModuleType, compilation.annotations)\n\t\tconst nextTransientSaves = produce(this.transientSaves, draft => {\n\t\t\tconst prevSave = castDraft(draft.get(localId))\n\n\t\t\t// Make intrinsic size available as metadata based on source code annotations.\n\t\t\t// Note that annotations are strings and we want numbers in the metadata.\n\t\t\tlet metadata: PersistParams[\"metadata\"]\n\t\t\tconst intrinsicWidth = annotations?.[AnnotationKey.FramerIntrinsicWidth]\n\t\t\tif (intrinsicWidth) {\n\t\t\t\tmetadata = {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t[ModuleMetadata.IntrinsicWidth]: Number.parseInt(intrinsicWidth, 10),\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst intrinsicHeight = annotations?.[AnnotationKey.FramerIntrinsicHeight]\n\t\t\tif (intrinsicHeight) {\n\t\t\t\tmetadata = {\n\t\t\t\t\t...metadata,\n\t\t\t\t\t[ModuleMetadata.IntrinsicHeight]: Number.parseInt(intrinsicHeight, 10),\n\t\t\t\t}\n\t\t\t}\n\t\t\tmetadata = {\n\t\t\t\t...metadata,\n\t\t\t\t// Make the Framer compiler contract version available as metadata on the module.\n\t\t\t\t[ModuleMetadata.CompilerContractVersion]: COMPILER_CONTRACT_VERSION,\n\t\t\t\t// Record that since this modules source has been updated after\n\t\t\t\t// 08/01/2025, that it's annotations should be statically\n\t\t\t\t// available in the tree.\n\t\t\t\t[ModuleMetadata.TreeAnnotations]: true,\n\t\t\t\t[ModuleMetadata.LocalModuleImportMapEntries]: this.moduleUsesLocalImportMapSpecifiers(typeSlashName),\n\t\t\t}\n\n\t\t\tif (prevSave) {\n\t\t\t\tprevSave.saveId = generateSaveId()\n\t\t\t\tprevSave.moduleContent = compilation.code\n\t\t\t\tprevSave.sourceContent = source\n\t\t\t\tprevSave.sourceMapContent = compilation.sourceMap\n\t\t\t\tprevSave.submoduleContents = submoduleContents\n\t\t\t\tprevSave.binaryAssetContents = binaryAssets\n\t\t\t\tprevSave.imports = compilation.imports\n\t\t\t\tprevSave.exports = compilation.exportedNames\n\t\t\t\tprevSave.reExportedModules = compilation.reExportedModules\n\t\t\t\tprevSave.treeVersion = treeVersion ?? this.treeStore.remoteTreeVersion\n\t\t\t\tprevSave.sourceRevision = sourceRevision ?? prevSave.sourceRevision\n\t\t\t\tprevSave.annotations = compilation.annotations\n\t\t\t\tprevSave.svgIcon = svgIcon ?? prevSave.svgIcon\n\t\t\t\tprevSave.kitSectionsStructure = kitSectionsStructure ?? prevSave.kitSectionsStructure\n\t\t\t\tprevSave.update = performance.now()\n\t\t\t\tif (assets) {\n\t\t\t\t\tprevSave.assets = Array.from(assets)\n\t\t\t\t}\n\t\t\t\tif (metadata) {\n\t\t\t\t\tprevSave.metadata = { ...prevSave.metadata, ...metadata }\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst newTransientSave: Draft<TransientModuleSave> = {\n\t\t\t\t\tlocalId,\n\t\t\t\t\ttype: info.type,\n\t\t\t\t\tname: info.name,\n\t\t\t\t\tsaveId: generateSaveId(),\n\t\t\t\t\tmoduleContent: compilation.code,\n\t\t\t\t\tsourceContent: source,\n\t\t\t\t\tsourceMapContent: compilation.sourceMap,\n\t\t\t\t\tsubmoduleContents,\n\t\t\t\t\tbinaryAssetContents: binaryAssets,\n\t\t\t\t\timports: compilation.imports,\n\t\t\t\t\texports: compilation.exportedNames,\n\t\t\t\t\treExportedModules: compilation.reExportedModules,\n\t\t\t\t\ttreeVersion,\n\t\t\t\t\tsourceRevision,\n\t\t\t\t\tsvgIcon,\n\t\t\t\t\tkitSectionsStructure,\n\t\t\t\t\tannotations: compilation.annotations,\n\t\t\t\t\tupdate: performance.now(),\n\t\t\t\t}\n\t\t\t\tif (assets) {\n\t\t\t\t\tnewTransientSave.assets = Array.from(assets)\n\t\t\t\t}\n\t\t\t\tif (metadata) {\n\t\t\t\t\t// We will merge this metadata with the persisted metadata before sending it to the API.\n\t\t\t\t\tnewTransientSave.metadata = metadata\n\t\t\t\t}\n\t\t\t\tdraft.set(localId, newTransientSave)\n\t\t\t}\n\t\t})\n\n\t\tthis.transientInfo ||= new Set()\n\t\tthis.transientInfo.add(localId)\n\t\tthis.transientSaves = nextTransientSaves\n\t\tthis.lastSnapshot = {\n\t\t\t...this.lastSnapshot,\n\t\t\tdepsGraph: nextDepsGraph,\n\t\t}\n\t}\n\n\tpublic async create(params: CreateParams) {\n\t\treturn synchronize(() => this.createLocked(params))\n\t}\n\n\tprivate async createLocked(params: CreateParams): Promise<LocalModuleId> {\n\t\tawait this.whenInitialized()\n\n\t\t// We use rest props here because it will automatically pipe through any new values that we add.\n\t\tconst { type, name, source, ...rest } = params\n\n\t\tconst typeSlashName = getTypeSlashName({ type, name })\n\t\tconst compilation = await this.compile({\n\t\t\tname: typeSlashName,\n\t\t\tsource,\n\t\t\ttype,\n\t\t\tincludeSourceMap: shouldIncludeSourceMap(type),\n\t\t})\n\n\t\tconst transientSave: TransientModuleSave = {\n\t\t\tlocalId: undefined,\n\t\t\ttype,\n\t\t\tname,\n\t\t\tsaveId: generateSaveId(),\n\t\t\tmoduleContent: compilation.code,\n\t\t\tsourceContent: source,\n\t\t\tsourceMapContent: compilation.sourceMap,\n\t\t\tsubmoduleContents: emptySubmoduleContents,\n\t\t\tbinaryAssetContents: emptyBinaryAssets,\n\t\t\timports: compilation.imports,\n\t\t\texports: compilation.exportedNames,\n\t\t\treExportedModules: compilation.reExportedModules,\n\t\t\ttreeVersion: params.treeVersion || this.treeStore.remoteTreeVersion,\n\t\t\tsourceRevision: params.sourceRevision,\n\t\t\tsvgIcon: params.svgIcon,\n\t\t\tkitSectionsStructure: params.kitSectionsStructure,\n\t\t\tannotations: compilation.annotations,\n\t\t\tupdate: performance.now(),\n\t\t}\n\n\t\tconst save = await this.createBatchSaveForUpdatedModule(\n\t\t\t\"$new\",\n\t\t\ttransientSave,\n\t\t\tthis.persistedModules,\n\t\t\tnew Map(),\n\t\t\tnew Map(),\n\t\t\t{ type, name, ...rest },\n\t\t)\n\n\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\tassert(this.modulesService)\n\n\t\tconst { data } = await this.modulesService.saveBatch({ batch: [save], copyOnWrite: this.detached })\n\n\t\tconst { updatedModuleLocalId, nextPersistedModules } = this.processTransientSaveData({\n\t\t\tnextPersistedModules: this.persistedModules,\n\t\t\ttransientSave,\n\t\t\tdata,\n\t\t})\n\n\t\tconst nextDepsGraph = upsertNode(this.lastSnapshot.depsGraph, typeSlashName, compilation.imports.relative)\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph: nextDepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\treturn updatedModuleLocalId\n\t}\n\n\tpublic async update(localId: LocalModuleId, params: Omit<PersistParams, \"name\" | \"type\">) {\n\t\tconst module = this.persistedModules.get(localId)\n\t\tassert(module, \"Trying to update an unknown module with localId:\", localId)\n\n\t\treturn synchronize(async () => {\n\t\t\tconst startTime = Date.now()\n\n\t\t\ttry {\n\t\t\t\tawait this.whenInitialized()\n\t\t\t\treturn await this.upsertBatchLocked({ [localId]: { ...params, name: module.name, type: module.type } })\n\t\t\t} finally {\n\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\tlog.debug(\"\u23F1 update\", localId, \"in\", duration, \"ms\")\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic async rename(localId: LocalModuleId, newName: string) {\n\t\treturn synchronize(() => this.renameLocked(localId, newName))\n\t}\n\n\tprivate async renameLocked(localId: LocalModuleId, newName: string): Promise<void> {\n\t\tawait this.whenInitialized()\n\t\tlet nextPersistedModules = this.persistedModules\n\t\tlet nextDepsGraph = this.lastSnapshot.depsGraph\n\n\t\tconst moduleToRename = nextPersistedModules.get(localId)\n\t\tassert(moduleToRename, \"Trying to rename an unknown module with localId:\", localId)\n\n\t\tconst treeVersion = this.treeStore.remoteTreeVersion\n\t\tconst typeSlashName = getTypeSlashName(moduleToRename)\n\n\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\tassert(!this.detached, \"renaming modules is not supported in detached mode\")\n\t\tassert(this.modulesService)\n\t\t// persist the nameChange to the backend\n\t\tconst renamedModuleData = await this.modulesService.update({ moduleId: moduleToRename.id, name: newName })\n\t\tassert(renamedModuleData, \"invalid update reply\")\n\n\t\t// For direct dependents we need to update the persisted source code to use the updated name in relative imports.\n\t\t// NOTE: We only need to update compiled code in local state because it also contains relative imports,\n\t\t//       the persisted version of it though uses absolute save URLs that don't change when the module is renamed.\n\t\tconst dependentTypeSlashNames = nextDepsGraph[typeSlashName]?.dependents\n\t\tlet updatedDependentModules: readonly ModulesAPI.ModuleWithSave[] = []\n\t\tconst dependentModuleUpdates: Record<\n\t\t\tLocalModuleId,\n\t\t\tPick<PersistedLocalModuleDraft, \"sourceContent\" | \"moduleContent\" | \"imports\">\n\t\t> = {}\n\n\t\tconst newTypeSlashName = getTypeSlashName(renamedModuleData)\n\t\tif (typeSlashName !== newTypeSlashName) {\n\t\t\t// Update the dependency graph if the typeSlashName of the module changed.\n\t\t\tnextDepsGraph = deleteNode(nextDepsGraph, typeSlashName)\n\t\t\tnextDepsGraph = upsertNode(nextDepsGraph, newTypeSlashName, moduleToRename.imports.relative)\n\t\t}\n\n\t\tif (dependentTypeSlashNames) {\n\t\t\tconst dependentLocalModules: PersistedLocalModule[] = []\n\t\t\tconst dependentServerModules: PersistedServerModule[] = []\n\t\t\tfor (const module of nextPersistedModules.values()) {\n\t\t\t\tconst typeSlashName = getTypeSlashName(module)\n\t\t\t\tif (!dependentTypeSlashNames.has(typeSlashName)) continue\n\n\t\t\t\tif (module.kind === \"local\") {\n\t\t\t\t\tdependentLocalModules.push(module)\n\t\t\t\t} else {\n\t\t\t\t\tdependentServerModules.push(module)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Any server side modules will need to be downloaded and compiled to create local\n\t\t\t// modules. We make sure to persist these. And add them to the list of dependent local\n\t\t\t// modules.\n\t\t\tif (dependentServerModules.length > 0) {\n\t\t\t\tconst createdLocalModules = await Promise.all(\n\t\t\t\t\tdependentServerModules.map(m => this.createLocalModuleFromModule(m)),\n\t\t\t\t)\n\t\t\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\t\t\tfor (const module of createdLocalModules) {\n\t\t\t\t\t\tdraft.set(module.localId, module)\n\t\t\t\t\t\tdependentLocalModules.push(module)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tconst patchSaves: ModulesAPI.BatchSave[] = []\n\t\t\tfor (const dependentModule of dependentLocalModules) {\n\t\t\t\tconst dependentTypeSlashName = getTypeSlashName(dependentModule)\n\t\t\t\tconst toPath = createRelativePath(dependentTypeSlashName, `${moduleToRename.type}/${newName}`)\n\t\t\t\tassert(toPath, \"Failed to create relative path to\", moduleToRename.type, \"/\", newName)\n\n\t\t\t\tconst fromPath = createRelativePath(dependentTypeSlashName, typeSlashName)\n\t\t\t\tassert(fromPath)\n\t\t\t\tconst importIndex = dependentModule.imports.relative.indexOf(fromPath)\n\t\t\t\tif (importIndex === -1) {\n\t\t\t\t\tlog.warn(dependentModule.localId, \"doesn't import\", fromPath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Updated import structure.\n\t\t\t\tconst updatedRelativeImports = [...dependentModule.imports.relative]\n\t\t\t\tupdatedRelativeImports[importIndex] = toPath\n\t\t\t\tconst imports = {\n\t\t\t\t\tabsolute: asWritable(dependentModule.imports.absolute),\n\t\t\t\t\tbare: asWritable(dependentModule.imports.bare),\n\t\t\t\t\trelative: updatedRelativeImports,\n\t\t\t\t}\n\n\t\t\t\t// Replace relative imports in the sources.\n\t\t\t\tconst updatedSource = replaceModuleSpecifier(dependentModule.sourceContent, fromPath, toPath)\n\t\t\t\tconst updatedModuleCode = replaceModuleSpecifier(dependentModule.moduleContent, fromPath, toPath)\n\n\t\t\t\tdependentModuleUpdates[dependentModule.localId] = {\n\t\t\t\t\tsourceContent: updatedSource,\n\t\t\t\t\tmoduleContent: updatedModuleCode as CodeWithRelativeImports,\n\t\t\t\t\timports,\n\t\t\t\t}\n\n\t\t\t\tassert(dependentModule.files.source)\n\t\t\t\tconst patchSave: ModulesAPI.BatchSave = {\n\t\t\t\t\ttype: dependentModule.type,\n\t\t\t\t\tmoduleId: dependentModule.id,\n\t\t\t\t\tname: dependentModule.name,\n\t\t\t\t\tsaveId: generateSaveId(),\n\t\t\t\t\tpatchSaveId: dependentModule.saveId,\n\t\t\t\t\tfiles: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: dependentModule.files.source,\n\t\t\t\t\t\t\ttype: \"source\",\n\t\t\t\t\t\t\tcontent: updatedSource,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\timports,\n\t\t\t\t\tdetached: this.detached,\n\t\t\t\t}\n\t\t\t\tpatchSaves.push(patchSave)\n\t\t\t}\n\n\t\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\t\tconst { data } = await this.modulesService.saveBatch({ batch: patchSaves, copyOnWrite: this.detached })\n\t\t\tupdatedDependentModules = data\n\t\t}\n\n\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\tconst isUpToDate = this.updateTreeNode(localId, treeVersion, renamedModuleData)\n\t\t\tif (!isUpToDate) return\n\n\t\t\t// Update the renamed module in local state. It can be a local or server module.\n\t\t\tif (moduleToRename.kind === \"server\") {\n\t\t\t\tdraft.set(localId, {\n\t\t\t\t\t...renamedModuleData,\n\t\t\t\t\tkind: \"server\",\n\t\t\t\t\tlocalId: asLocalId(renamedModuleData.localId),\n\t\t\t\t\tid: asGlobalId(renamedModuleData.id),\n\t\t\t\t\tmoduleURL: renamedModuleData.baseURL + renamedModuleData.files.module,\n\t\t\t\t\tsourceContent: moduleToRename.sourceContent,\n\t\t\t\t\tupdate: performance.now(),\n\t\t\t\t} satisfies PersistedServerModule as PersistedServerModuleDraft)\n\t\t\t} else {\n\t\t\t\tdraft.set(localId, {\n\t\t\t\t\t...renamedModuleData,\n\t\t\t\t\tkind: \"local\",\n\t\t\t\t\tlocalId: asLocalId(renamedModuleData.localId),\n\t\t\t\t\tid: asGlobalId(renamedModuleData.id),\n\t\t\t\t\tmoduleURL: renamedModuleData.baseURL + renamedModuleData.files.module,\n\t\t\t\t\tsourceContent: moduleToRename.sourceContent,\n\t\t\t\t\tmoduleContent: moduleToRename.moduleContent,\n\t\t\t\t\tsourceMapContent: moduleToRename.sourceMapContent,\n\t\t\t\t\tsubmoduleContents: moduleToRename.submoduleContents,\n\t\t\t\t\tbinaryAssetContents: moduleToRename.binaryAssetContents,\n\t\t\t\t\tupdate: performance.now(),\n\t\t\t\t} satisfies PersistedLocalModule as PersistedLocalModuleDraft)\n\t\t\t}\n\n\t\t\t// Update the dependent modules in local state.\n\t\t\tfor (const newDependentModuleData of updatedDependentModules) {\n\t\t\t\tconst dependentModuleLocalId = asLocalId(newDependentModuleData.localId)\n\t\t\t\tconst dependentModule = draft.get(dependentModuleLocalId)\n\t\t\t\tassert(dependentModule?.kind === \"local\", \"dependent module must be local:\", dependentModuleLocalId)\n\t\t\t\tconst dependentModuleUpdate = dependentModuleUpdates[dependentModuleLocalId]\n\t\t\t\tassert(dependentModuleUpdate, \"dependent module update must exist:\", dependentModuleLocalId)\n\n\t\t\t\tconst isUpToDate = this.updateTreeNode(dependentModuleLocalId, treeVersion, newDependentModuleData)\n\t\t\t\tif (!isUpToDate) continue\n\n\t\t\t\tdraft.set(dependentModuleLocalId, {\n\t\t\t\t\t...newDependentModuleData,\n\t\t\t\t\tkind: \"local\",\n\t\t\t\t\tlocalId: dependentModuleLocalId,\n\t\t\t\t\tid: asGlobalId(newDependentModuleData.id),\n\t\t\t\t\tmoduleURL: newDependentModuleData.baseURL + newDependentModuleData.files.module,\n\t\t\t\t\tmoduleContent: dependentModuleUpdate.moduleContent,\n\t\t\t\t\tsourceContent: dependentModuleUpdate.sourceContent,\n\t\t\t\t\tsourceMapContent: dependentModule.sourceMapContent,\n\t\t\t\t\tsubmoduleContents: dependentModule.submoduleContents,\n\t\t\t\t\tbinaryAssetContents: dependentModule.binaryAssetContents,\n\t\t\t\t\timports: dependentModuleUpdate.imports,\n\t\t\t\t\texports: asWritable(newDependentModuleData.exports),\n\t\t\t\t\treExportedModules: asWritable(newDependentModuleData.reExportedModules),\n\t\t\t\t\tsubmodules: asWritable(newDependentModuleData.submodules),\n\t\t\t\t\tbinaryAssets: asWritable(newDependentModuleData.binaryAssets),\n\t\t\t\t\tsourceRevision: dependentModule.sourceRevision,\n\t\t\t\t\tupdate: dependentModule.update,\n\t\t\t\t})\n\n\t\t\t\tnextDepsGraph = upsertNode(\n\t\t\t\t\tnextDepsGraph,\n\t\t\t\t\tgetTypeSlashName(newDependentModuleData),\n\t\t\t\t\tdependentModuleUpdate.imports.relative,\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph: nextDepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\t}\n\n\tpublic async upsert(localId: LocalModuleId, params: PersistParams) {\n\t\treturn synchronize(async () => {\n\t\t\tconst startTime = Date.now()\n\n\t\t\ttry {\n\t\t\t\tawait this.whenInitialized()\n\t\t\t\treturn await this.upsertBatchLocked({ [localId]: params })\n\t\t\t} finally {\n\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\tlog.debug(\"\u23F1 upsert\", localId, \"in\", duration, \"ms\")\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic async upsertBatch(sources: Record<LocalModuleId, PersistParams>): Promise<void> {\n\t\treturn synchronize(async () => {\n\t\t\tconst startTime = Date.now()\n\t\t\ttry {\n\t\t\t\tawait this.whenInitialized()\n\t\t\t\treturn await this.upsertBatchLocked(sources)\n\t\t\t} finally {\n\t\t\t\tconst duration = Date.now() - startTime\n\t\t\t\tlog.debug(\"\u23F1 upsert batch in\", duration, \"ms\")\n\t\t\t}\n\t\t})\n\t}\n\n\tpublic async delete(localIdOrList: LocalModuleId | LocalModuleId[]) {\n\t\treturn synchronize(() => this.deleteLocked(localIdOrList))\n\t}\n\n\tprivate async deleteLocked(localIdOrList: LocalModuleId | LocalModuleId[]): Promise<void> {\n\t\tconst localIds = Array.isArray(localIdOrList) ? localIdOrList : [localIdOrList]\n\t\tif (!localIds.length) return\n\n\t\tawait this.whenInitialized()\n\n\t\tconst modules = localIds.map(localId => {\n\t\t\tconst persistedModule = this.persistedModules.get(localId)\n\t\t\tassert(persistedModule, \"Trying to delete an unknown module\", localId, \"It was never persisted.\")\n\t\t\treturn persistedModule\n\t\t})\n\n\t\tconst { modulesService } = this\n\t\tassert(modulesService)\n\n\t\tconst deletedModules: typeof modules = []\n\t\tawait Promise.all(\n\t\t\tmodules.map(async m => {\n\t\t\t\ttry {\n\t\t\t\t\tawait modulesService.delete({ moduleId: m.id })\n\t\t\t\t\tdeletedModules.push(m)\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlog.warn(String(error))\n\t\t\t\t}\n\t\t\t}),\n\t\t)\n\t\tassert(deletedModules.length > 0, \"Failed to delete module(s)\")\n\n\t\tlet nextDepsGraph = this.lastSnapshot.depsGraph\n\t\tfor (const module of deletedModules) {\n\t\t\tconst typeSlashName = getTypeSlashName(module)\n\t\t\tnextDepsGraph = deleteNode(nextDepsGraph, typeSlashName)\n\t\t}\n\n\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\tfor (const { localId } of deletedModules) {\n\t\t\t\tdraft.delete(localId)\n\t\t\t\tthis.removeTreeNode(localId)\n\t\t\t}\n\t\t})\n\t\tconst nextTransientSaves = produce(this.transientSaves, draft => {\n\t\t\tfor (const { localId } of deletedModules) {\n\t\t\t\tdraft.delete(localId)\n\t\t\t}\n\t\t})\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: nextTransientSaves,\n\t\t\tdepsGraph: nextDepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\t}\n\n\tpublic async restore(moduleId: GlobalModuleId, name?: string): Promise<PersistedModule> {\n\t\treturn synchronize(() => this.restoreLocked(moduleId, name))\n\t}\n\n\tprivate async restoreLocked(moduleId: GlobalModuleId, name?: string): Promise<PersistedModule> {\n\t\tawait this.whenInitialized()\n\n\t\tconst { modulesService } = this\n\t\tassert(modulesService)\n\t\tconst restoredData = await modulesService.restore({ moduleId, name })\n\n\t\tconst module = await this.createServerModuleFromData(restoredData)\n\t\tconst typeSlashName = getTypeSlashName(module)\n\t\tconst localId = module.localId\n\n\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\tdraft.set(localId, castDraft(module))\n\t\t})\n\t\tconst nextDepsGraph = upsertNode(this.lastSnapshot.depsGraph, typeSlashName, module.imports.relative)\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph: nextDepsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\tthis.updateTreeNodeWithOwnTreeVersion(localId, module)\n\n\t\treturn module\n\t}\n\n\tpublic async publish(localId: LocalModuleId, options: { namespace: string; name: string; version: string }) {\n\t\treturn synchronize(() => this.publishLocked(localId, options))\n\t}\n\n\tprivate async publishLocked(\n\t\tlocalId: LocalModuleId,\n\t\t{ namespace, name, version }: { namespace: string; name: string; version: string },\n\t): Promise<ModulesAPI.Publish> {\n\t\tawait this.whenInitialized()\n\n\t\t// TODO: Wait for any ongoing persistence of this module.\n\t\tconst persistedModule = this.persistedModules.get(localId)\n\t\tassert(persistedModule, \"Trying to publish an unknown module\", localId, \"It was never persisted.\")\n\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\tassert(this.modulesService)\n\t\tconst publish = await this.modulesService.publish({\n\t\t\tmoduleId: persistedModule.id,\n\t\t\tsaveId: persistedModule.saveId,\n\t\t\tnamespace,\n\t\t\tname,\n\t\t\tversion,\n\t\t})\n\n\t\t// Update publish info in the persisted module.\n\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\tconst module = draft.get(localId)\n\t\t\tif (!module) return\n\t\t\tdraft.set(localId, {\n\t\t\t\t...module,\n\t\t\t\tlastPublish: {\n\t\t\t\t\tnamespaceId: publish.namespaceId,\n\t\t\t\t\tname: publish.name,\n\t\t\t\t\tversion: publish.version,\n\t\t\t\t\timportURL: publish.importURL,\n\t\t\t\t},\n\t\t\t})\n\t\t})\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\treturn publish\n\t}\n\n\tpublic async addNpmDependencies(\n\t\tinstallDescriptor: InstallDescriptor | InstallDescriptor[],\n\t): Promise<{ dependenciesMap: DependenciesMap }> {\n\t\treturn synchronize(async () => {\n\t\t\t// Filter out the statically provided specifiers.\n\t\t\tawait this.whenInitialized()\n\n\t\t\tlet currentImportMap: ImportMap\n\t\t\tif (this.dependenciesModule?.importMapContent) {\n\t\t\t\tcurrentImportMap = JSON.parse(this.dependenciesModule?.importMapContent)\n\t\t\t} else {\n\t\t\t\tcurrentImportMap = { imports: {} }\n\t\t\t}\n\n\t\t\tlet currentDependenciesMap: DependenciesMap\n\t\t\tif (this.dependenciesModule?.dependenciesMapContent) {\n\t\t\t\tcurrentDependenciesMap = JSON.parse(this.dependenciesModule?.dependenciesMapContent)\n\t\t\t} else {\n\t\t\t\tcurrentDependenciesMap = { dependencies: {} }\n\t\t\t}\n\n\t\t\tconst importMapPrefixImports = new Set(Object.keys(currentImportMap.imports).filter(i => i.endsWith(\"/\")))\n\t\t\tconst isCoveredByImportMapPrefix = (specifier: string) => {\n\t\t\t\tlet slashIndex = specifier.indexOf(\"/\")\n\t\t\t\twhile (slashIndex !== -1) {\n\t\t\t\t\tconst prefix = specifier.slice(0, slashIndex + 1)\n\t\t\t\t\tif (importMapPrefixImports.has(prefix)) return true\n\t\t\t\t\tslashIndex = specifier.indexOf(\"/\", slashIndex + 1)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tlet descriptors = Array.isArray(installDescriptor) ? installDescriptor : [installDescriptor]\n\t\t\tdescriptors = descriptors.filter(descriptor => {\n\t\t\t\tif (PROVIDED_DEPENDENCIES.has(descriptor.target)) return false\n\t\t\t\tif (isBlockedDependency(descriptor.target)) return false\n\n\t\t\t\t// Filter out specifiers that are already in the import map, including subpaths.\n\t\t\t\tconst importMapKey = getImportMapKey(descriptor)\n\t\t\t\tif (currentImportMap.imports?.[importMapKey]) return false\n\n\t\t\t\t// Check if any prefix entry (ending in '/') covers this specifier.\n\t\t\t\t// This can happen in deduplication cases.\n\t\t\t\t// e.g. \"react\" -> \"react/jsx-runtime/\" -> \"react/jsx-runtime/server.js\"\n\t\t\t\tif (isCoveredByImportMapPrefix(importMapKey)) return false\n\n\t\t\t\treturn true\n\t\t\t})\n\t\t\tif (descriptors.length === 0) return { dependenciesMap: currentDependenciesMap }\n\n\t\t\tdescriptors = descriptors.map(descriptor => {\n\t\t\t\tif (currentDependenciesMap.dependencies[descriptor.target]) {\n\t\t\t\t\t// Make sure to specify the correct version for new subpaths of existing dependencies.\n\n\t\t\t\t\tconst importUrlToParse =\n\t\t\t\t\t\tcurrentImportMap.imports[descriptor.target] ??\n\t\t\t\t\t\tObject.entries(currentImportMap?.imports).find(([key]) => {\n\t\t\t\t\t\t\treturn key.startsWith(descriptor.target)\n\t\t\t\t\t\t})?.[1]\n\n\t\t\t\t\tif (experiments.isOn(\"importMapPruning\") && !importUrlToParse) {\n\t\t\t\t\t\t// Allow import to not exist with experiment on as we're reworking the meaning of dependencies.json\n\t\t\t\t\t\treturn descriptor\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert(importUrlToParse, \"Import map must contain all dependencies from dependencies map\")\n\t\t\t\t\t}\n\n\t\t\t\t\tconst version = parsePackageUrl(importUrlToParse)?.version\n\t\t\t\t\treturn version ? { ...descriptor, target: `${descriptor.target}@${version}` } : descriptor\n\t\t\t\t}\n\n\t\t\t\tconst resolutionVersion = RESOLUTIONS[descriptor.target]\n\t\t\t\tif (resolutionVersion) {\n\t\t\t\t\t// If we have a resolution for this dependency, use the version from the resolution.\n\t\t\t\t\t// TODO: Check why this is needed. We expected that `@jspm/generator` would use `resolutions` also\n\t\t\t\t\t//       when resolving top-level dependencies, but our testing showed that it only uses it for transitive dependencies.\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...descriptor,\n\t\t\t\t\t\ttarget: `${descriptor.target}@${resolutionVersion}`,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn descriptor\n\t\t\t})\n\n\t\t\tconst { importMap: newImportMap, resolvedDependencies } = await addDependencies(\n\t\t\t\tcurrentImportMap,\n\t\t\t\tdescriptors,\n\t\t\t\tPROVIDED_DEPENDENCIES,\n\t\t\t\tRESOLUTIONS,\n\t\t\t)\n\n\t\t\tconst newDependenciesMap = await this.extendCurrentDependenciesMap(resolvedDependencies)\n\t\t\tresolvedDependencies.forEach(({ name, version }) => record(\"npm_dependency_add\", { name, semver: version }))\n\n\t\t\tlog.debug({ newImportMap, newDependenciesMap })\n\t\t\tawait this.updateDependenciesLocked(newImportMap, newDependenciesMap)\n\n\t\t\treturn { dependenciesMap: newDependenciesMap }\n\t\t})\n\t}\n\n\tpublic async reinstallNpmDependencies(): Promise<ImportMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst { currentImportMap, currentDependenciesMap } = this.getCurrentDependencies()\n\n\t\t\t// biome-ignore lint/performance/noDelete: Changing to `undefined` does not cover `in` operator on object\n\t\t\tdelete currentImportMap.scopes\n\n\t\t\tconst { importMap: newImportMap } = await reinstallDependencies(\n\t\t\t\tcurrentImportMap,\n\t\t\t\tPROVIDED_DEPENDENCIES,\n\t\t\t\tRESOLUTIONS,\n\t\t\t)\n\n\t\t\tawait this.updateDependenciesLocked(newImportMap, currentDependenciesMap)\n\n\t\t\treturn newImportMap\n\t\t})\n\t}\n\n\tpublic async uninstallBlockedNpmDependencies(): Promise<ImportMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst { currentImportMap, currentDependenciesMap } = this.getCurrentDependencies()\n\n\t\t\t// Also remove from dependencies map to reflect the changes in the import map.\n\t\t\tconst newDependenciesMap = removeBlockedDependencies(currentDependenciesMap)\n\t\t\tconst newImportMap = await uninstallBlockedDependencies(currentImportMap)\n\n\t\t\tawait this.updateDependenciesLocked(newImportMap, newDependenciesMap)\n\n\t\t\treturn newImportMap\n\t\t})\n\t}\n\n\tpublic async clearNpmDependencies(): Promise<void> {\n\t\treturn synchronize(async () => this.updateDependenciesLocked({ imports: {} }, { dependencies: {} }))\n\t}\n\n\tpublic async removeBlockedNpmDependencies(): Promise<DependenciesMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst { currentImportMap, currentDependenciesMap } = this.getCurrentDependencies()\n\n\t\t\tconst dependenciesMap = removeBlockedDependencies(currentDependenciesMap)\n\n\t\t\tawait this.updateDependenciesLocked(currentImportMap, currentDependenciesMap)\n\n\t\t\treturn dependenciesMap\n\t\t})\n\t}\n\n\tpublic async rebuildImportMapFromDependencies(): Promise<ImportMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst dependenciesMapContent = this.dependenciesModule?.dependenciesMapContent\n\t\t\tconst currentDependenciesMap: DependenciesMap = dependenciesMapContent\n\t\t\t\t? JSON.parse(dependenciesMapContent)\n\t\t\t\t: { dependencies: {} }\n\n\t\t\tconst newImportMap = await generateImportMapFromDependencies(\n\t\t\t\tcurrentDependenciesMap,\n\t\t\t\tPROVIDED_DEPENDENCIES,\n\t\t\t\tRESOLUTIONS,\n\t\t\t)\n\n\t\t\tawait this.updateDependenciesLocked(newImportMap, currentDependenciesMap)\n\n\t\t\treturn newImportMap\n\t\t})\n\t}\n\n\tpublic getLocalModuleBareImports(): Set<string> {\n\t\tconst localModuleBareImports = new Set<string>()\n\t\tfor (const module of this.persistedModules.values()) {\n\t\t\tfor (const bare of module.imports.bare) {\n\t\t\t\tlocalModuleBareImports.add(bare)\n\t\t\t}\n\t\t}\n\t\treturn localModuleBareImports\n\t}\n\n\t/**\n\t * Compose all import maps that get injected into the page:\n\t * 1. Static import map (React, Framer, etc.)\n\t * 2. User dependencies import map (framer-user-importmap)\n\t * 3. Local modules import map (framer-local-modules)\n\t * 4. Any temporary import maps would be runtime-only\n\t */\n\tpublic getComposedProjectImportMap(): ImportMap {\n\t\t// Start with static import map (React, Framer, etc.)\n\t\tlet composedMap: ImportMap = getStaticImportMap()\n\n\t\t// Add user dependencies (framer-user-importmap)\n\t\tif (this.dependenciesModule?.importMapContent) {\n\t\t\tconst userImportMap: ImportMap = JSON.parse(this.dependenciesModule.importMapContent)\n\t\t\tcomposedMap = extendImportMap(composedMap, userImportMap, \"source-wins\")\n\t\t}\n\n\t\t// Add local modules (framer-local-modules)\n\t\t// Local modules are generated from the current project modules.\n\t\tconst localModulesMap = this.createLocalModuleImportMap()\n\t\tcomposedMap = extendImportMap(composedMap, localModulesMap, \"source-wins\")\n\n\t\treturn composedMap\n\t}\n\n\t/**\n\t * Create local module import map similar to what's done in export.\n\t */\n\tprivate createLocalModuleImportMap(): ImportMap {\n\t\tconst imports: Record<string, string> = {}\n\n\t\t// Create an entry for every local module, following the same pattern as export\n\t\tfor (const module of this.persistedModules.values()) {\n\t\t\t// Include ALL module types that have a module file, not just \"code\"\n\t\t\tconst localModule = module as PersistedLocalModule\n\t\t\t// Must have a module file name to build a local module import map specifier\n\t\t\tif (isString(localModule.files.module)) {\n\t\t\t\tconst importSpecifier = localModuleImportMapSpecifier(localModule.localId, localModule.files.module)\n\t\t\t\timports[importSpecifier] = localModule.moduleURL\n\t\t\t}\n\t\t}\n\t\treturn { imports }\n\t}\n\n\t/**\n\t * Reshape external import map into URL-scoped form for the given entry points.\n\t * Allows us to merge the source map into this project\u2019s map without `imports` level conflicts.\n\t */\n\tpublic async scopeExternalImportMap(entryPoints: string[], importMap: ImportMap): Promise<ImportMap> {\n\t\treturn generateImportMapFromEntryPoints(entryPoints, PROVIDED_DEPENDENCIES, RESOLUTIONS, importMap)\n\t}\n\n\t/**\n\t * Generate a pruned project import map by tracing entry points and applying framer post-processing\n\t * (strip provided deps, lift local-module scopes, drop `!missing/`, drop empty scopes).\n\t */\n\tprivate async generatePrunedImportMapFromEntryPoints(\n\t\tentryPoints: string[],\n\t\tbaseImportMap: ImportMap,\n\t): Promise<ImportMap> {\n\t\tconst newImportMap = await generateImportMapFromEntryPoints(\n\t\t\tentryPoints,\n\t\t\tPROVIDED_DEPENDENCIES,\n\t\t\tRESOLUTIONS,\n\t\t\tbaseImportMap,\n\t\t)\n\n\t\t// Import map post-processing rules:\n\t\t// - Remove provided dependencies from top-level imports\n\t\t// - Remove provided dependencies from the broad \"https://ga.jspm.io/\" scope (handled by app-importmap.ejs)\n\t\t// - Preserve provided dependencies in package-specific scopes (e.g. react-reconciler \u2192 scheduler)\n\t\t// - Remove all \"#framer/local/\" entries from imports and scopes\n\t\t// - Drop scopes that become empty after filtering\n\t\t// - Drop scopes that point to local project module directories (moduleURL parent dirs)\n\t\t// - Drop module url scopes that are local modules\n\t\t// - Drop any imports for !missing/ specifiers\n\t\tconst filteredImports = Object.fromEntries(\n\t\t\tObject.entries(newImportMap.imports ?? {}).filter(\n\t\t\t\t([specifier]) => !PROVIDED_DEPENDENCIES.has(specifier) && !hasLocalModuleImportMapPrefix(specifier),\n\t\t\t),\n\t\t)\n\n\t\t// Strip local modules from scopes and drop empty scopes entirely.\n\t\t// Collect local module scope URLs (baseURL: https://.../modules/{moduleId}/{saveId}/) so we can drop them.\n\t\tconst localModuleBaseUrls = new Set([...this.persistedModules.values()].map(m => m.baseURL))\n\t\tconst liftedLocalModuleImports: Record<string, string> = {}\n\n\t\tconst filteredScopesEntries: [string, Record<string, string>][] = []\n\t\tfor (const scopeUrl in newImportMap.scopes) {\n\t\t\tconst scopeMap = newImportMap.scopes[scopeUrl]\n\t\t\tif (!scopeMap) continue\n\n\t\t\tconst isBroadJSPMScope = scopeUrl === \"https://ga.jspm.io/\"\n\t\t\tconst filteredScopeMap: Record<string, string> = Object.fromEntries(\n\t\t\t\tObject.entries(scopeMap).filter(([specifier]) => {\n\t\t\t\t\tif (isBroadJSPMScope && PROVIDED_DEPENDENCIES.has(specifier)) return false\n\t\t\t\t\tif (hasLocalModuleImportMapPrefix(specifier)) return false\n\t\t\t\t\tif (hasMissingModuleImportSpecifierPrefix(specifier)) return false\n\t\t\t\t\treturn true\n\t\t\t\t}),\n\t\t\t)\n\n\t\t\tif (Object.keys(filteredScopeMap).length > 0) {\n\t\t\t\tif (localModuleBaseUrls.has(scopeUrl)) {\n\t\t\t\t\tObject.assign(liftedLocalModuleImports, filteredScopeMap)\n\t\t\t\t} else {\n\t\t\t\t\tfilteredScopesEntries.push([scopeUrl, filteredScopeMap])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst filteredImportMap = {\n\t\t\timports: Object.assign(filteredImports, liftedLocalModuleImports),\n\t\t\t...(filteredScopesEntries.length > 0 ? { scopes: Object.fromEntries(filteredScopesEntries) } : {}),\n\t\t}\n\n\t\tassertIsImportMap(filteredImportMap)\n\t\treturn filteredImportMap\n\t}\n\n\t/**\n\t * Generates and persists a pruned import map alongside a filtered dependencies map.\n\t */\n\tpublic async pruneProjectImportMapFromEntryPoints(\n\t\tentryPoints: string[],\n\t\toptions: { additionalImportMap?: ImportMap; dryRun?: boolean } = {},\n\t): Promise<ImportMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst currentBaseImportMap = this.getComposedProjectImportMap()\n\t\t\tconst baseImportMap = options.additionalImportMap\n\t\t\t\t? extendImportMap(currentBaseImportMap, options.additionalImportMap, \"source-wins\")\n\t\t\t\t: currentBaseImportMap\n\t\t\tconst filteredImportMap = await this.generatePrunedImportMapFromEntryPoints(entryPoints, baseImportMap)\n\n\t\t\tconst dependenciesMapContent = this.dependenciesModule?.dependenciesMapContent\n\t\t\tconst currentDependenciesMap: DependenciesMap = dependenciesMapContent\n\t\t\t\t? JSON.parse(dependenciesMapContent)\n\t\t\t\t: { dependencies: {} }\n\n\t\t\t// Remove all dependencies from dependencies.json that are not in the filtered import map.\n\t\t\tconst importSpecifiers = new Set(Object.keys(filteredImportMap.imports ?? {}))\n\t\t\tconst filteredDependenciesMap = {\n\t\t\t\tdependencies: Object.fromEntries(\n\t\t\t\t\tObject.entries(currentDependenciesMap.dependencies ?? {}).filter(([depName]) =>\n\t\t\t\t\t\timportSpecifiers.has(depName),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t}\n\n\t\t\tif (!options.dryRun) {\n\t\t\t\tawait this.updateDependenciesLocked(filteredImportMap, filteredDependenciesMap)\n\t\t\t} else {\n\t\t\t\tlog.info(\"Dry run import map\", filteredImportMap)\n\t\t\t\tlog.info(\"Dry run dependencies map\", filteredDependenciesMap)\n\t\t\t}\n\n\t\t\treturn filteredImportMap\n\t\t})\n\t}\n\n\tpublic async unsafeUpgradeDependency(\n\t\tdependency: string,\n\t\texpectedSubDependencies: string[],\n\t\tversion?: string,\n\t): Promise<ImportMap> {\n\t\treturn synchronize(async () => {\n\t\t\tconst { currentImportMap, currentDependenciesMap } = this.getCurrentDependencies()\n\n\t\t\tconst newImportMap = await unsafeUpgradeDependency(currentImportMap, dependency, expectedSubDependencies, version)\n\t\t\tconst newPartialDependenciesMap = generateDependenciesFromImportMap(newImportMap)\n\t\t\tconst newDependenciesMap = extendDependencies(newPartialDependenciesMap, currentDependenciesMap)\n\n\t\t\tawait this.updateDependenciesLocked(newImportMap, newDependenciesMap)\n\n\t\t\treturn newImportMap\n\t\t})\n\t}\n\n\tpublic async extendCurrentImportMap(importMap: ImportMap, dependenciesMap: DependenciesMap): Promise<void> {\n\t\treturn synchronize(async () => {\n\t\t\tconst { currentImportMap, currentDependenciesMap } = this.getCurrentDependencies()\n\n\t\t\tconst newImportMap = extendImportMap(currentImportMap, importMap)\n\t\t\tconst newDependenciesMap = extendDependencies(currentDependenciesMap, dependenciesMap)\n\n\t\t\treturn this.updateDependenciesLocked(newImportMap, newDependenciesMap)\n\t\t})\n\t}\n\n\tprivate async extendCurrentDependenciesMap(resolvedDependencies: PackageResolution[]): Promise<DependenciesMap> {\n\t\tconst resolvedDependenciesMap: DependenciesMap[\"dependencies\"] = {}\n\t\tfor (const dep of resolvedDependencies) {\n\t\t\tresolvedDependenciesMap[dep.name] = dep.version\n\t\t}\n\n\t\tconst currentDependenciesMap: DependenciesMap = this.dependenciesModule?.dependenciesMapContent\n\t\t\t? JSON.parse(this.dependenciesModule?.dependenciesMapContent)\n\t\t\t: { dependencies: {} }\n\n\t\tcurrentDependenciesMap.dependencies = Object.assign(resolvedDependenciesMap, currentDependenciesMap.dependencies)\n\n\t\treturn currentDependenciesMap\n\t}\n\n\tprivate getCurrentDependencies(): { currentImportMap: ImportMap; currentDependenciesMap: DependenciesMap } {\n\t\tconst currentImportMap: ImportMap = this.dependenciesModule?.importMapContent\n\t\t\t? JSON.parse(this.dependenciesModule?.importMapContent)\n\t\t\t: { imports: {} }\n\t\tconst currentDependenciesMap: DependenciesMap = this.dependenciesModule?.dependenciesMapContent\n\t\t\t? JSON.parse(this.dependenciesModule?.dependenciesMapContent)\n\t\t\t: { dependencies: {} }\n\n\t\treturn { currentImportMap, currentDependenciesMap }\n\t}\n\n\tprivate async updateDependenciesLocked(newImportMap: ImportMap, newDependenciesMap: DependenciesMap): Promise<void> {\n\t\tconst stringifiedImportMap = JSON.stringify(\n\t\t\tnewImportMap,\n\t\t\tnull,\n\t\t\tCODE_FORMATTING_TAB_WIDTH,\n\t\t) as CodeWithRelativeImports\n\t\tconst stringifiedDependenciesMap = JSON.stringify(\n\t\t\tnewDependenciesMap,\n\t\t\tnull,\n\t\t\tCODE_FORMATTING_TAB_WIDTH,\n\t\t) as CodeWithRelativeImports\n\n\t\tif (\n\t\t\tstringifiedImportMap === this.dependenciesModule?.importMapContent &&\n\t\t\tstringifiedDependenciesMap === this.dependenciesModule?.dependenciesMapContent\n\t\t) {\n\t\t\treturn\n\t\t}\n\n\t\tconst save: ModulesAPI.BatchSave = {\n\t\t\tmoduleId: \"$upsertName\",\n\t\t\tname: DEPENDENCIES_MODULE_NAME,\n\t\t\tsaveId: generateSaveId(),\n\t\t\ttype: ModuleType.Config,\n\t\t\tfiles: [\n\t\t\t\t{ name: \"importMap.json\", type: \"importMap\", content: stringifiedImportMap },\n\t\t\t\t{ name: \"dependencies.json\", type: \"dependencies\", content: stringifiedDependenciesMap },\n\t\t\t],\n\t\t\timports: {\n\t\t\t\tabsolute: [],\n\t\t\t\trelative: [],\n\t\t\t\tbare: [],\n\t\t\t},\n\t\t\tdetached: this.detached,\n\t\t}\n\n\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\tassert(this.modulesService)\n\t\tconst {\n\t\t\tdata: [updatedImportMap],\n\t\t} = await this.modulesService.saveBatch({ batch: [save], copyOnWrite: this.detached })\n\n\t\tassert(updatedImportMap, \"Modules API must return an updated import map after savebatch\")\n\t\tthis.updateTreeNodeWithOwnTreeVersion(DEPENDENCIES_MODULE_TYPE_SLASH_NAME, updatedImportMap)\n\n\t\tconst dependenciesModule: DependenciesModule = {\n\t\t\tkind: \"dependencies\",\n\t\t\timportMapContent: stringifiedImportMap,\n\t\t\tdependenciesMapContent: stringifiedDependenciesMap,\n\t\t\t...updatedImportMap,\n\t\t\tid: asGlobalId(updatedImportMap.id),\n\t\t\tlocalId: asLocalId(updatedImportMap.localId),\n\t\t\ttype: updatedImportMap.type as ModuleType.Config,\n\t\t\tname: updatedImportMap.name as \"dependencies\",\n\t\t}\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: dependenciesModule,\n\t\t\tpersistedModules: this.persistedModules,\n\t\t\ttransientSaves: this.transientSaves,\n\t\t\t// Persistence alone never changes the dependency graph, so we are safe to re-use one from the prev snapshot.\n\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\t}\n\n\tpublic getPersistedDependenciesModule(): DependenciesModule | undefined {\n\t\treturn this.dependenciesModule\n\t}\n\n\t/**\n\t * Iterates over all the module entries and finds one with `id` equals to the provided one.\n\t */\n\tpublic getPersistedModuleByGlobalId(moduleId: GlobalModuleId): PersistedModule | undefined {\n\t\tfor (const module of this.persistedModules.values()) {\n\t\t\tif (module.id === moduleId) return module\n\t\t}\n\t\treturn undefined\n\t}\n\n\tpublic getPersistedModuleByLocalId(localId: LocalModuleId): PersistedModule | undefined {\n\t\treturn this.persistedModules.get(localId)\n\t}\n\n\tpublic getTransientSaveByLocalId(localId: LocalModuleId): TransientModuleSave | undefined {\n\t\treturn this.transientSaves.get(localId)\n\t}\n\n\tprivate async handleRemoteModuleDeleteEvents(events: { id: string }[]): Promise<void> {\n\t\tif (this.useTreeAsLocalModuleList) return\n\t\treturn this.handleRemoteModuleDeletes(events.map(e => asGlobalId(e.id)))\n\t}\n\n\tprivate async handleRemoteModuleDeletes(deletedModuleIds: GlobalModuleId[]): Promise<void> {\n\t\tawait synchronize(async () => {\n\t\t\tconst deletedLocalModuleIds: LocalModuleId[] = []\n\t\t\tconst deletedTypeSlashNames: string[] = []\n\n\t\t\tfor (const id of deletedModuleIds) {\n\t\t\t\tconst persistedModule = this.getPersistedModuleByGlobalId(id)\n\t\t\t\t// This event (from the backend) could theoretically be delayed to a point where the current client no longer has this module in memory\n\t\t\t\tif (!persistedModule) continue\n\t\t\t\tdeletedTypeSlashNames.push(getTypeSlashName(persistedModule))\n\t\t\t\tdeletedLocalModuleIds.push(persistedModule.localId)\n\t\t\t}\n\n\t\t\tconst nextPersistedModules = produce(this.persistedModules, draft => {\n\t\t\t\tfor (const localId of deletedLocalModuleIds) {\n\t\t\t\t\tdraft.delete(localId)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tconst nextTransientSaves = produce(this.transientSaves, draft => {\n\t\t\t\tfor (const localId of deletedLocalModuleIds) {\n\t\t\t\t\tdraft.delete(localId)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tlet nextDepsGraph = this.lastSnapshot.depsGraph\n\t\t\tfor (const typeSlashName of deletedTypeSlashNames) {\n\t\t\t\tnextDepsGraph = deleteNode(nextDepsGraph, typeSlashName)\n\t\t\t}\n\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\tpersistedModules: nextPersistedModules,\n\t\t\t\ttransientSaves: nextTransientSaves,\n\t\t\t\tdepsGraph: nextDepsGraph,\n\t\t\t\tdidRemoteChange: true,\n\t\t\t})\n\t\t})\n\t}\n\n\tprivate async handleRemoteModuleSaveEvents(events: { module: ModulesAPI.ModuleWithSave }[]): Promise<void> {\n\t\tif (this.useTreeAsLocalModuleList) return\n\t\treturn this.handleRemoteModuleSaves(events.map(e => e.module))\n\t}\n\n\tasync handleRemoteModuleSaves(data: readonly ModulesAPI.ModuleWithSave[]): Promise<void> {\n\t\tconst importMapSaveEvents: ModulesAPI.ModuleWithSave[] = []\n\t\tconst moduleSaveEvents: ModulesAPI.ModuleWithSave[] = []\n\t\tfor (const module of data) {\n\t\t\tif (getTypeSlashName(module) === DEPENDENCIES_MODULE_TYPE_SLASH_NAME) {\n\t\t\t\timportMapSaveEvents.push(module)\n\t\t\t} else {\n\t\t\t\tmoduleSaveEvents.push(module)\n\t\t\t}\n\t\t}\n\n\t\tlet dependenciesModule: DependenciesModule | undefined = undefined\n\t\tconst lastImportMapSave =\n\t\t\timportMapSaveEvents.length > 0 ? importMapSaveEvents[importMapSaveEvents.length - 1] : undefined\n\t\tif (lastImportMapSave) {\n\t\t\tconst {\n\t\t\t\timportMapContent,\n\t\t\t\tdependenciesMapContent,\n\t\t\t}: {\n\t\t\t\timportMapContent: string\n\t\t\t\tdependenciesMapContent: string | undefined\n\t\t\t} = await this.getDependenciesFiles(lastImportMapSave)\n\n\t\t\tassert(dependenciesMapContent, \"No dependencies file exists for the remote update!\")\n\n\t\t\tdependenciesModule = {\n\t\t\t\tkind: \"dependencies\" as const,\n\t\t\t\t...lastImportMapSave,\n\t\t\t\tid: asGlobalId(lastImportMapSave.id),\n\t\t\t\tlocalId: asLocalId(lastImportMapSave.localId),\n\t\t\t\ttype: ModuleType.Config,\n\t\t\t\tname: lastImportMapSave.name as typeof DEPENDENCIES_MODULE_NAME,\n\t\t\t\timportMapContent,\n\t\t\t\tdependenciesMapContent: dependenciesMapContent,\n\t\t\t}\n\t\t}\n\n\t\tawait synchronize(async () => {\n\t\t\tif (dependenciesModule) this.dependenciesModule = dependenciesModule\n\n\t\t\tlet nextPersistedModules = this.persistedModules\n\t\t\tlet nextDepsGraph = this.lastSnapshot.depsGraph\n\n\t\t\t// Create all server modules in parallel. (Code components might need to download their source code.)\n\t\t\tconst serverModules = await Promise.all(moduleSaveEvents.map(data => this.createServerModuleFromData(data)))\n\n\t\t\tfor (const module of serverModules) {\n\t\t\t\tconst typeSlashName = getTypeSlashName(module)\n\t\t\t\tconst localId = module.localId\n\t\t\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\t\t\tdraft.set(localId, castDraft(module))\n\t\t\t\t})\n\n\t\t\t\t// There is no transient save for this module so update depsGraph to account for it.\n\t\t\t\tif (!this.transientSaves.has(localId)) {\n\t\t\t\t\tnextDepsGraph = upsertNode(this.lastSnapshot.depsGraph, typeSlashName, module.imports.relative)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\tpersistedModules: nextPersistedModules,\n\t\t\t\ttransientSaves: this.transientSaves,\n\t\t\t\tdepsGraph: nextDepsGraph,\n\t\t\t\tdidRemoteChange: true,\n\t\t\t\tmultiplayerChange: true,\n\t\t\t})\n\t\t})\n\t}\n\n\t/** Tracks retries due to connection errors or server errors. */\n\ttransientSaveRetries = new Map<string, number>()\n\ttransientSaveRelativeImportRetries = new Set<string>()\n\n\tprivate getPatchTransientSave(localId: LocalModuleId, module: PersistedLocalModule, saveId: SaveId) {\n\t\treturn {\n\t\t\tsaveId,\n\t\t\ttype: module.type,\n\t\t\tname: module.name,\n\t\t\tlocalId,\n\t\t\t// TODO: Could we just rely on patching for these?\n\t\t\tmoduleContent: module.moduleContent,\n\t\t\tsourceContent: module.sourceContent,\n\t\t\tsourceMapContent: module.sourceMapContent,\n\t\t\tsubmoduleContents: module.submoduleContents,\n\t\t\tbinaryAssetContents: module.binaryAssetContents,\n\t\t\timports: module.imports,\n\t\t\texports: module.exports,\n\t\t\treExportedModules: module.reExportedModules,\n\t\t\tsourceRevision: module.sourceRevision,\n\t\t\tupdate: module.update,\n\t\t}\n\t}\n\n\t/**\n\t * Upserts a batch of unpersisted modules in a single request. There is a limit to the number of\n\t * files that can be saved in a single request.\n\t */\n\tprivate async upsertBatchLocked(sources: Record<LocalModuleId, PersistParams>): Promise<void> {\n\t\t// Don't persist any transient modules when the document is read only.\n\t\tif (this.readOnlyTree) return\n\n\t\tlet nextPersistedModules = this.persistedModules\n\n\t\t// If a module has not been updated since it was renamed, its in-memory filenames will be\n\t\t// stale until persistence succeeds. To ensure that dependent modules rewrite with the\n\t\t// latest import of the dependency module, provide the up-to-date names when creating the\n\t\t// batch save for dependent modules.\n\t\tconst newFilenames = new Map<TypeSlashName, ModuleFilenames>()\n\t\tconst nodes: [TypeSlashName, readonly RelativeFilePath[]][] = []\n\n\t\t// Build a special version of the dependency graph based on the persisted modules and the\n\t\t// transient module save that we are about to persist. We deliberately use persisted\n\t\t// modules, ignoring transient saves. Optimistically using the transient save ids too early\n\t\t// means if those transient modules are never persisted, that the files we create here would\n\t\t// be invalid.\n\t\tconst typeSlashNameToLocalId = new Map<string, LocalModuleId>()\n\t\tfor (const mod of nextPersistedModules.values()) {\n\t\t\t// For code files, this will be the `ModuleName` not the localIdName.\n\t\t\tconst typeSlashName = getTypeSlashName(mod)\n\t\t\ttypeSlashNameToLocalId.set(typeSlashName, mod.localId)\n\t\t\tnodes.push([typeSlashName, mod.imports.relative])\n\t\t}\n\n\t\t// Both of these steps happen in a first pass to ensure that any modules that depend on\n\t\t// other modules in the batch rewrite imports to the latest save ids. Iterate through the\n\t\t// modules we are about to persist and record the save ids, creating new ones if needed if\n\t\t// there is no transient save. This ensures that any modules that depend on other modules in\n\t\t// the batch rewrite imports to the latest save ids.\n\t\tconst newSaveIds = new Map<TypeSlashName, SaveId>()\n\t\tfor (const id in sources) {\n\t\t\tconst localId = asLocalId(id)\n\t\t\tconst params = sources[localId]\n\t\t\tassert(params, \"No persist params found for\", localId)\n\t\t\t// For code files, this must be the `ModuleName` not the localIdName.\n\t\t\tconst transientSave = this.transientSaves.get(localId)\n\t\t\tconst mod = transientSave ?? nextPersistedModules.get(localId)\n\t\t\tassert(mod, \"No module found for\", localId)\n\n\t\t\tconst typeSlashName = getTypeSlashName(mod)\n\t\t\tnewSaveIds.set(typeSlashName, transientSave?.saveId ?? generateSaveId())\n\t\t\tnewFilenames.set(typeSlashName, filenamesFromModuleName(params.name))\n\t\t\ttypeSlashNameToLocalId.set(typeSlashName, localId)\n\t\t\tif (transientSave) nodes.push([typeSlashName, transientSave.imports.relative])\n\t\t}\n\n\t\t// Create an up-to-date dependency graph that reflects the dependencies of the transient\n\t\t// modules we are persisting.\n\t\tconst depsGraph = createDependencyGraph(nodes)\n\n\t\tconst transientSaves = new Map<LocalModuleId, TransientModuleSave>()\n\n\t\t// Delete the transient saves that we will persist, if the update succeeds they will be\n\t\t// removed from state as they are no longer transient but persisted.\n\t\tconst nextTransientSaves = produce(this.transientSaves, draft => {\n\t\t\tfor (const localId in sources) draft.delete(asLocalId(localId))\n\t\t})\n\n\t\tlet errorToRethrow: unknown\n\t\tlet initialSaveBatchSucceeded = false\n\n\t\ttry {\n\t\t\tconst {\n\t\t\t\tprimaryBatch,\n\t\t\t\tdependentBatch,\n\t\t\t\tdependentLocalIdWaves,\n\t\t\t\tnextPersistedModules: batchNextPersistedModules,\n\t\t\t} = await this.createBatch(\n\t\t\t\tsources,\n\t\t\t\ttransientSaves,\n\t\t\t\tnextPersistedModules,\n\t\t\t\tdepsGraph,\n\t\t\t\ttypeSlashNameToLocalId,\n\t\t\t\tnewSaveIds,\n\t\t\t\tnewFilenames,\n\t\t\t)\n\n\t\t\tassert(!this.readOnlyTree, \"modules storage is read only\")\n\t\t\tassert(this.modulesService)\n\n\t\t\t// The dependent saves in this initial optimistic batch may still reference pre-COW\n\t\t\t// module IDs. If the response remaps IDs, repair waves below supersede them with\n\t\t\t// dependency order preserved. This keeps the common no-remap case to one request.\n\t\t\tconst initialBatch = primaryBatch.concat(dependentBatch)\n\t\t\tconst { data: initialData } = await this.modulesService.saveBatch({\n\t\t\t\tbatch: initialBatch,\n\t\t\t\tcopyOnWrite: this.detached,\n\t\t\t})\n\t\t\tinitialSaveBatchSucceeded = true\n\n\t\t\tconst copyOnWriteCanRemapModuleIds = this.detached || isModulesInTreeOn()\n\t\t\tif (\n\t\t\t\tcopyOnWriteCanRemapModuleIds &&\n\t\t\t\tdependentBatch.length > 0 &&\n\t\t\t\tthis.didSaveBatchRemapModuleIds(initialBatch, initialData)\n\t\t\t) {\n\t\t\t\tlet persistedModulesForNextWave = this.applyBatchSaveDataWithoutTreeUpdates(\n\t\t\t\t\tbatchNextPersistedModules,\n\t\t\t\t\tinitialData,\n\t\t\t\t\ttransientSaves,\n\t\t\t\t)\n\t\t\t\tconst repairSaveIds = this.createRepairSaveIdsForDependentWaves(\n\t\t\t\t\tnewSaveIds,\n\t\t\t\t\tdependentLocalIdWaves,\n\t\t\t\t\tpersistedModulesForNextWave,\n\t\t\t\t)\n\t\t\t\tconst repairData: ModulesAPI.ModuleWithSave[] = []\n\t\t\t\tfor (const dependentLocalIds of dependentLocalIdWaves) {\n\t\t\t\t\tconst rebuiltDependentBatch = await this.createBatchSavesForDependentModules(\n\t\t\t\t\t\tdependentLocalIds,\n\t\t\t\t\t\tpersistedModulesForNextWave,\n\t\t\t\t\t\trepairSaveIds,\n\t\t\t\t\t\tnewFilenames,\n\t\t\t\t\t)\n\t\t\t\t\tconst { data } = await this.modulesService.saveBatch({\n\t\t\t\t\t\tbatch: rebuiltDependentBatch,\n\t\t\t\t\t\tcopyOnWrite: this.detached,\n\t\t\t\t\t})\n\t\t\t\t\trepairData.push(...data)\n\t\t\t\t\tpersistedModulesForNextWave = this.applyDependentSaveDataWithoutTreeUpdates(persistedModulesForNextWave, data)\n\t\t\t\t}\n\t\t\t\tnextPersistedModules = this.applyBatchSaveDataToPersistedModules({\n\t\t\t\t\tnextPersistedModules: batchNextPersistedModules,\n\t\t\t\t\tdata: this.combineLatestSaveData(initialData, repairData),\n\t\t\t\t\ttransientSaves,\n\t\t\t\t\tsources,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tnextPersistedModules = this.applyBatchSaveDataToPersistedModules({\n\t\t\t\t\tnextPersistedModules: batchNextPersistedModules,\n\t\t\t\t\tdata: initialData,\n\t\t\t\t\ttransientSaves,\n\t\t\t\t\tsources,\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// We will reset the nextPersistedModules to what it was before this method started. The\n\t\t\t// nextTransientSaves will already have the transient removed. If this goes to\n\t\t\t// setNextInternalState, we essentially have dropped the transient save as if it never\n\t\t\t// happened.\n\t\t\tnextPersistedModules = this.persistedModules\n\n\t\t\tconst batchId = this.getTransientSavesBatchId(transientSaves)\n\t\t\tconst retryCount = this.transientSaveRetries.get(batchId) ?? 0\n\t\t\tconst { error, dropTransient } = this.handlePersistenceError(e, retryCount, () => {\n\t\t\t\tthis.transientSaveRetries.set(batchId, retryCount + 1)\n\t\t\t\tsetTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tvoid this.retryPersistingBatch({\n\t\t\t\t\t\t\tsources,\n\t\t\t\t\t\t\ttransientSaves,\n\t\t\t\t\t\t\tbatchId,\n\t\t\t\t\t\t\tretryCount,\n\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\tregenerateSaveIds: initialSaveBatchSucceeded,\n\t\t\t\t\t\t}).catch(retryError => {\n\t\t\t\t\t\t\tlog.reportError(retryError, { context: \"ModulesStorage: retryPersistingBatch failed.\" })\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t\t1000 + retryCount * 1000,\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tif (!dropTransient) return\n\t\t\terrorToRethrow = error\n\t\t}\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: nextPersistedModules,\n\t\t\ttransientSaves: nextTransientSaves,\n\t\t\t// Persistence alone never changes the dependency graph, so we are safe to re-use one\n\t\t\t// from the prev snapshot.\n\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\tdidRemoteChange: true,\n\t\t})\n\n\t\tthis.transientSaveRetries.delete(this.getTransientSavesBatchId(transientSaves))\n\n\t\t// Re-throw all errors that have nothing to do with the retry mechanism and let callers\n\t\t// handle those.\n\t\tif (errorToRethrow) throw errorToRethrow\n\t}\n\n\tprivate getTransientSavesBatchId(transientSaves: ReadonlyMap<LocalModuleId, TransientModuleSave>): string {\n\t\treturn Array.from(transientSaves.values())\n\t\t\t.map(save => save.saveId)\n\t\t\t.join(\"-\")\n\t}\n\n\tprivate async retryPersistingBatch({\n\t\tsources,\n\t\ttransientSaves,\n\t\tbatchId,\n\t\tretryCount,\n\t\terror,\n\t\tregenerateSaveIds,\n\t}: {\n\t\tsources: Record<LocalModuleId, PersistParams>\n\t\ttransientSaves: ReadonlyMap<LocalModuleId, TransientModuleSave>\n\t\tbatchId: string\n\t\tretryCount: number\n\t\terror: unknown\n\t\tregenerateSaveIds: boolean\n\t}): Promise<void> {\n\t\t// If we are retrying because of a relative imports error, we need to refresh.\n\t\tif (isRewriteRelativeImportsError(error)) {\n\t\t\tthis.transientSaveRelativeImportRetries.add(batchId)\n\t\t\tawait this.refresh()\n\t\t}\n\n\t\tawait synchronize(async () => {\n\t\t\tif (regenerateSaveIds) {\n\t\t\t\tconst regeneratedBatchId = this.regenerateTransientSaveIdsForRetry(transientSaves)\n\t\t\t\tif (!regeneratedBatchId) return\n\t\t\t\tthis.transientSaveRetries.delete(batchId)\n\t\t\t\tthis.transientSaveRetries.set(regeneratedBatchId, retryCount + 1)\n\t\t\t\tlog.debug(\"retrying saving batchId with fresh save ids:\", batchId)\n\t\t\t\tawait this.upsertBatchLocked(sources)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif (this.areTransientSavesUnchanged(transientSaves)) {\n\t\t\t\tlog.debug(\"retrying saving batchId with same save ids:\", batchId)\n\t\t\t\tawait this.upsertBatchLocked(sources)\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate areTransientSavesUnchanged(\n\t\tattemptedTransientSaves: ReadonlyMap<LocalModuleId, TransientModuleSave>,\n\t): boolean {\n\t\tfor (const [localId, attemptedSave] of attemptedTransientSaves) {\n\t\t\tconst transientSave = this.transientSaves.get(localId)\n\t\t\tif (!transientSave || transientSave.saveId !== attemptedSave.saveId) return false\n\t\t}\n\t\treturn true\n\t}\n\n\tprivate regenerateTransientSaveIdsForRetry(\n\t\tattemptedTransientSaves: ReadonlyMap<LocalModuleId, TransientModuleSave>,\n\t): string | undefined {\n\t\tlet canRegenerate = true\n\t\tconst nextTransientSaves = produce(this.transientSaves, draft => {\n\t\t\tfor (const [localId, attemptedSave] of attemptedTransientSaves) {\n\t\t\t\tconst transientSave = draft.get(localId)\n\t\t\t\tif (!transientSave || transientSave.saveId !== attemptedSave.saveId) {\n\t\t\t\t\tcanRegenerate = false\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const localId of attemptedTransientSaves.keys()) {\n\t\t\t\tconst transientSave = draft.get(localId)\n\t\t\t\tassert(transientSave, \"Expected transient save while regenerating save IDs:\", localId)\n\t\t\t\ttransientSave.saveId = generateSaveId()\n\t\t\t\ttransientSave.update = performance.now()\n\t\t\t}\n\t\t})\n\t\tif (!canRegenerate) return undefined\n\n\t\tthis.setNextInternalState({\n\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\tpersistedModules: this.persistedModules,\n\t\t\ttransientSaves: nextTransientSaves,\n\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\tdidRemoteChange: false,\n\t\t})\n\n\t\tconst regeneratedTransientSaves = new Map<LocalModuleId, TransientModuleSave>()\n\t\tfor (const localId of attemptedTransientSaves.keys()) {\n\t\t\tconst transientSave = nextTransientSaves.get(localId)\n\t\t\tassert(transientSave, \"Expected regenerated transient save ID:\", localId)\n\t\t\tregeneratedTransientSaves.set(localId, transientSave)\n\t\t}\n\t\treturn this.getTransientSavesBatchId(regeneratedTransientSaves)\n\t}\n\n\tprivate async createBatchSavesForDependentModules(\n\t\tdependentLocalIds: readonly LocalModuleId[],\n\t\tpersistedModules: PersistedModules,\n\t\tnewSaveIds: ReadonlyMap<TypeSlashName, SaveId>,\n\t\tnewFilenames: ReadonlyMap<TypeSlashName, ModuleFilenames>,\n\t): Promise<ModulesAPI.BatchSave[]> {\n\t\tconst batch: ModulesAPI.BatchSave[] = []\n\t\tfor (const dependentLocalId of dependentLocalIds) {\n\t\t\tbatch.push(\n\t\t\t\tawait this.createBatchSaveForDependentModule(dependentLocalId, persistedModules, newSaveIds, newFilenames),\n\t\t\t)\n\t\t}\n\t\treturn batch\n\t}\n\n\tprivate didSaveBatchRemapModuleIds(\n\t\tbatch: readonly ModulesAPI.BatchSave[],\n\t\tdata: readonly ModulesAPI.ModuleWithSave[],\n\t): boolean {\n\t\tconst moduleBySaveId = new Map(data.map(module => [module.saveId, module]))\n\t\treturn batch.some(save => {\n\t\t\tif (save.moduleId === \"$new\" || save.moduleId === \"$upsertName\") return false\n\t\t\tconst module = moduleBySaveId.get(save.saveId)\n\t\t\treturn module !== undefined && module.id !== save.moduleId\n\t\t})\n\t}\n\n\tprivate createRepairSaveIdsForDependentWaves(\n\t\tnewSaveIds: ReadonlyMap<TypeSlashName, SaveId>,\n\t\tdependentLocalIdWaves: readonly (readonly LocalModuleId[])[],\n\t\tpersistedModules: PersistedModules,\n\t): Map<TypeSlashName, SaveId> {\n\t\tconst repairSaveIds = new Map(newSaveIds)\n\t\tfor (const dependentLocalIds of dependentLocalIdWaves) {\n\t\t\tfor (const dependentLocalId of dependentLocalIds) {\n\t\t\t\tconst module = persistedModules.get(dependentLocalId)\n\t\t\t\tassert(module, dependentLocalId, \"is not found in persistedModules\")\n\t\t\t\trepairSaveIds.set(getTypeSlashName(module), generateSaveId())\n\t\t\t}\n\t\t}\n\t\treturn repairSaveIds\n\t}\n\n\tprivate combineLatestSaveData(\n\t\tinitialData: readonly ModulesAPI.ModuleWithSave[],\n\t\trepairData: readonly ModulesAPI.ModuleWithSave[],\n\t): ModulesAPI.ModuleWithSave[] {\n\t\tconst latestByLocalId = new Map<string, ModulesAPI.ModuleWithSave>()\n\t\tfor (const module of initialData) latestByLocalId.set(module.localId, module)\n\t\tfor (const module of repairData) latestByLocalId.set(module.localId, module)\n\t\treturn Array.from(latestByLocalId.values())\n\t}\n\n\tprivate applyBatchSaveDataWithoutTreeUpdates(\n\t\tnextPersistedModules: PersistedModules,\n\t\tdata: readonly ModulesAPI.ModuleWithSave[],\n\t\ttransientSaves: Map<LocalModuleId, TransientModuleSave>,\n\t): PersistedModules {\n\t\treturn produce(nextPersistedModules, draft => {\n\t\t\tfor (const module of data) {\n\t\t\t\tconst localId = asLocalId(module.localId)\n\t\t\t\tconst transientSave = transientSaves.get(localId)\n\t\t\t\tif (transientSave) {\n\t\t\t\t\tdraft.set(\n\t\t\t\t\t\tlocalId,\n\t\t\t\t\t\tthis.createPersistedLocalModuleFromSaveData(module, transientSave) as PersistedLocalModuleDraft,\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tconst prevModule = draft.get(localId)\n\t\t\t\t\tassert(prevModule, localId, \"is not in persistedModules\")\n\t\t\t\t\tthis.applyDependentModuleSaveData(prevModule, module)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate applyDependentSaveDataWithoutTreeUpdates(\n\t\tnextPersistedModules: PersistedModules,\n\t\tdata: readonly ModulesAPI.ModuleWithSave[],\n\t): PersistedModules {\n\t\treturn produce(nextPersistedModules, draft => {\n\t\t\tfor (const module of data) {\n\t\t\t\tconst localId = asLocalId(module.localId)\n\t\t\t\tconst prevModule = draft.get(localId)\n\t\t\t\tassert(prevModule, localId, \"is not in persistedModules\")\n\t\t\t\tthis.applyDependentModuleSaveData(prevModule, module)\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate applyBatchSaveDataToPersistedModules({\n\t\tnextPersistedModules,\n\t\tdata,\n\t\ttransientSaves,\n\t\tsources,\n\t}: {\n\t\tnextPersistedModules: PersistedModules\n\t\tdata: readonly ModulesAPI.ModuleWithSave[]\n\t\ttransientSaves: Map<LocalModuleId, TransientModuleSave>\n\t\tsources: Record<LocalModuleId, PersistParams>\n\t}): PersistedModules {\n\t\treturn produce(nextPersistedModules, draft => {\n\t\t\tfor (const module of data) {\n\t\t\t\tconst localId = asLocalId(module.localId)\n\t\t\t\tconst transientSave = transientSaves.get(localId)\n\t\t\t\t// If the module is not in our list of transient saves, it was a dependency.\n\t\t\t\tif (!transientSave) {\n\t\t\t\t\tconst prevModule = draft.get(localId)\n\t\t\t\t\tassert(prevModule, localId, \"is not in persistedModules\")\n\t\t\t\t\tthis.updateTreeNodeWithOwnTreeVersion(localId, module)\n\t\t\t\t\tthis.applyDependentModuleSaveData(prevModule, module)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tconst persistedModule = this.createPersistedLocalModuleFromSaveData(module, transientSave)\n\t\t\t\tconst errors = sources[localId]?.errors\n\t\t\t\t// The kit structure in stored in the trasient module instead of the persist params\n\t\t\t\tconst kitSectionsStructure = transientSave.kitSectionsStructure\n\t\t\t\tconst treeVersion = transientSave.treeVersion ?? this.treeStore.remoteTreeVersion\n\t\t\t\tconst isUpToDate = this.updateTreeNode(\n\t\t\t\t\tmodule.localId,\n\t\t\t\t\ttreeVersion,\n\t\t\t\t\tpersistedModule,\n\t\t\t\t\terrors,\n\t\t\t\t\tkitSectionsStructure,\n\t\t\t\t)\n\t\t\t\tif (!isUpToDate) return\n\n\t\t\t\tdraft.set(localId, persistedModule as PersistedLocalModuleDraft)\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate createPersistedLocalModuleFromSaveData(\n\t\tmodule: ModulesAPI.ModuleWithSave,\n\t\ttransientSave: TransientModuleSave,\n\t): PersistedLocalModule {\n\t\treturn {\n\t\t\tkind: \"local\",\n\t\t\t...module,\n\t\t\tid: asGlobalId(module.id),\n\t\t\tlocalId: asLocalId(module.localId),\n\t\t\timports: transientSave.imports,\n\t\t\tmoduleURL: module.baseURL + module.files.module,\n\t\t\t// We take the files' content from the transientSave we've just persisted\n\t\t\t// because that content stays the same after the persistence.\n\t\t\tsourceContent: transientSave.sourceContent,\n\t\t\tsourceMapContent: transientSave.sourceMapContent,\n\t\t\tmoduleContent: transientSave.moduleContent,\n\t\t\tsubmoduleContents: transientSave.submoduleContents,\n\t\t\tbinaryAssetContents: transientSave.binaryAssetContents,\n\t\t\tsourceRevision: transientSave.sourceRevision,\n\t\t\tannotations: transientSave.annotations,\n\t\t\tupdate: transientSave.update,\n\t\t}\n\t}\n\n\t/**\n\t * For dependent modules, we only update select fields that can change as a result of a\n\t * dependency module persistence.\n\t *\n\t * Source and module contents stay the same because we keep the CodeWithRelativeImports version\n\t * of it and that one doesn't change when a dependency module is updated.\n\t */\n\tprivate applyDependentModuleSaveData(prevModule: Draft<PersistedModule>, module: ModulesAPI.ModuleWithSave): void {\n\t\tprevModule.id = asGlobalId(module.id)\n\t\tprevModule.saveId = module.saveId\n\t\tprevModule.moduleURL = module.baseURL + module.files.module\n\t\tprevModule.baseURL = module.baseURL\n\t}\n\n\tprivate async createBatch(\n\t\tsources: Record<LocalModuleId, PersistParams>,\n\t\ttransientSaves: Map<LocalModuleId, TransientModuleSave>,\n\t\tnextPersistedModules: PersistedModules,\n\t\tdepsGraph: DependencyGraph,\n\t\ttypeSlashNameToLocalId: Map<TypeSlashName, LocalModuleId>,\n\t\tnewSaveIds: Map<TypeSlashName, SaveId>,\n\t\tnewFilenames: Map<TypeSlashName, ModuleFilenames>,\n\t): Promise<CreatedBatch> {\n\t\tconst primaryBatch: ModulesAPI.BatchSave[] = []\n\t\tconst dependentBatch: ModulesAPI.BatchSave[] = []\n\t\tconst dependentTypeSlashNamesToSave: TypeSlashName[] = []\n\n\t\tfor (const id in sources) {\n\t\t\tconst localId = asLocalId(id)\n\t\t\tconst params = sources[localId]\n\t\t\tassert(params, \"No persist params found for\", localId)\n\n\t\t\tlet transientSave = this.transientSaves.get(localId)\n\t\t\tif (!transientSave) {\n\t\t\t\tlet module = nextPersistedModules.get(localId)\n\t\t\t\tassert(\n\t\t\t\t\tmodule,\n\t\t\t\t\t`Trying to persist ${localId} but it doesn't have neither a corresponding transient save nor an existing persisted module.`,\n\t\t\t\t)\n\n\t\t\t\tif (module.kind === \"server\") {\n\t\t\t\t\tmodule = await this.createLocalModuleFromModule(module)\n\t\t\t\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\t\t\t\tif (!module) return\n\t\t\t\t\t\tdraft.set(module.localId, module as PersistedLocalModuleDraft)\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t\t// We must have created a save id for this module in an earlier pass, dependencies\n\t\t\t\t// of the module will use that id for absolute url imports.\n\t\t\t\tconst saveId = newSaveIds.get(localId)\n\t\t\t\tassert(saveId, \"No save id found for\", localId)\n\n\t\t\t\ttransientSave = this.getPatchTransientSave(localId, module, saveId)\n\t\t\t}\n\n\t\t\ttransientSaves.set(localId, transientSave)\n\n\t\t\tconst save = await this.createBatchSaveForUpdatedModule(\n\t\t\t\tthis.persistedModules.get(localId)?.id ?? \"$upsertName\",\n\t\t\t\ttransientSave,\n\t\t\t\tnextPersistedModules,\n\t\t\t\tnewSaveIds,\n\t\t\t\tnewFilenames,\n\t\t\t\tparams,\n\t\t\t)\n\t\t\tprimaryBatch.push(save)\n\t\t}\n\n\t\t// Collect all dependencies to update. We record to the dependency to allow us to handle\n\t\t// dependents of different module types in different ways.\n\t\tconst dependentTypeSlashNamesByLocalId = new Map<LocalModuleId, Set<TypeSlashName>>()\n\t\tfor (const id in sources) {\n\t\t\tconst localId = asLocalId(id)\n\t\t\tconst params = sources[localId]\n\t\t\tassert(params, \"No persist params found for\", localId)\n\n\t\t\tconst typeSlashName = getTypeSlashName(params)\n\t\t\tconst dependentTypeSlashNames = new Set<TypeSlashName>()\n\t\t\tcollectModuleAndItsDependentsRecursively(depsGraph, typeSlashName, dependentTypeSlashNames)\n\t\t\tdependentTypeSlashNamesByLocalId.set(localId, dependentTypeSlashNames)\n\t\t}\n\n\t\t// Ensure all dependent modules are local modules so that we have their source content and\n\t\t// can rewrite relative imports to the latest absolute urls.\n\t\tconst serverModules: Promise<PersistedLocalModuleDraft>[] = []\n\t\tfor (const dependentTypeSlashNames of dependentTypeSlashNamesByLocalId.values()) {\n\t\t\tfor (const dependentTypeSlashName of dependentTypeSlashNames) {\n\t\t\t\tconst localId = typeSlashNameToLocalId.get(dependentTypeSlashName)\n\t\t\t\tassert(localId, \"Cannot find localId for\", dependentTypeSlashName)\n\n\t\t\t\tconst module = nextPersistedModules.get(localId)\n\t\t\t\tif (module?.kind !== \"server\") continue\n\t\t\t\tserverModules.push(this.createLocalModuleFromModule(module))\n\t\t\t}\n\t\t}\n\n\t\tif (serverModules.length > 0) {\n\t\t\tconst createdLocalModules = await Promise.all(serverModules)\n\t\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\t\tfor (const module of createdLocalModules) {\n\t\t\t\t\tdraft.set(module.localId, module)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\n\t\t// Create new saveIds for all the affected modules. We will need them when rewriting the\n\t\t// relative imports as `saveId` is a part of the module URL we use as a replacement.\n\t\tfor (const dependentTypeSlashNames of dependentTypeSlashNamesByLocalId.values()) {\n\t\t\tfor (const dependentTypeSlashName of dependentTypeSlashNames) {\n\t\t\t\tif (newSaveIds.has(dependentTypeSlashName)) continue\n\t\t\t\tnewSaveIds.set(dependentTypeSlashName, generateSaveId())\n\t\t\t}\n\t\t}\n\n\t\t// Only create a single save for each dependent module even if it is a dependent of multiple\n\t\t// transient modules in the batch.\n\t\tconst seenDependentTypeSlashNames = new Set<TypeSlashName>()\n\n\t\tfor (const [localId, dependentTypeSlashNames] of dependentTypeSlashNamesByLocalId) {\n\t\t\tconst [type] = splitTypeSlashName(localId)\n\t\t\tfor (const dependentTypeSlashName of dependentTypeSlashNames) {\n\t\t\t\tconst dependentLocalId = typeSlashNameToLocalId.get(dependentTypeSlashName)\n\t\t\t\tassert(dependentLocalId, \"Cannot find localId for\", dependentTypeSlashName)\n\n\t\t\t\tif (transientSaves.has(dependentLocalId)) continue\n\t\t\t\tif (seenDependentTypeSlashNames.has(dependentTypeSlashName)) continue\n\n\t\t\t\tconst dependentModule = nextPersistedModules.get(dependentLocalId)\n\t\t\t\tconst hasLocalModuleImportMapEntries =\n\t\t\t\t\tdependentModule?.metadata[ModuleMetadata.LocalModuleImportMapEntries] === true\n\n\t\t\t\t// Webpages (and in the future, collections), don't need to have\n\t\t\t\t// their local relative imports rewritten to the latest absolute\n\t\t\t\t// urls when a dependency changes, since they use static import map\n\t\t\t\t// specifiers. In that case, don't add those modules to the batch to\n\t\t\t\t// reduce the impact of saving a module with lots of dependents.\n\t\t\t\t// However, if the module already exists with absolute urls, we must\n\t\t\t\t// rewrite them one last time to the import map specifiers.\n\t\t\t\tif (hasLocalModuleImportMapEntries && this.moduleUsesLocalImportMapSpecifiers(dependentTypeSlashName)) {\n\t\t\t\t\t// When the dependency module is a code file, and the dependent module imports it\n\t\t\t\t\t// directly, even if a dependent module uses import map specifiers, it needs to\n\t\t\t\t\t// update the import map specifiers since the file name may have changed if the\n\t\t\t\t\t// dependency module has been renamed since the last time it was updated.\n\t\t\t\t\tif (type !== ModuleType.Code || !depsGraph[dependentTypeSlashName]?.dependencies.has(localId)) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Only track the dependent module as seen if we are adding it to the batch.\n\t\t\t\tseenDependentTypeSlashNames.add(dependentTypeSlashName)\n\t\t\t\tdependentTypeSlashNamesToSave.push(dependentTypeSlashName)\n\n\t\t\t\tconst dependentSave = await this.createBatchSaveForDependentModule(\n\t\t\t\t\tdependentLocalId,\n\t\t\t\t\tnextPersistedModules,\n\t\t\t\t\tnewSaveIds,\n\t\t\t\t\tnewFilenames,\n\t\t\t\t)\n\t\t\t\tdependentBatch.push(dependentSave)\n\t\t\t}\n\t\t}\n\n\t\tconst dependentLocalIdWaves = this.createDependentLocalIdWaves(\n\t\t\tdependentTypeSlashNamesToSave,\n\t\t\tdepsGraph,\n\t\t\ttypeSlashNameToLocalId,\n\t\t)\n\n\t\treturn { primaryBatch, dependentBatch, dependentLocalIdWaves, nextPersistedModules }\n\t}\n\n\tprivate createDependentLocalIdWaves(\n\t\tdependentTypeSlashNames: readonly TypeSlashName[],\n\t\tdepsGraph: DependencyGraph,\n\t\ttypeSlashNameToLocalId: ReadonlyMap<TypeSlashName, LocalModuleId>,\n\t): LocalModuleId[][] {\n\t\tconst dependentTypeSlashNameSet = new Set(dependentTypeSlashNames)\n\t\tconst depthByTypeSlashName = new Map<TypeSlashName, number>()\n\t\tconst visitingTypeSlashNames = new Set<TypeSlashName>()\n\n\t\tconst getDepth = (typeSlashName: TypeSlashName): number => {\n\t\t\tconst existingDepth = depthByTypeSlashName.get(typeSlashName)\n\t\t\tif (existingDepth !== undefined) return existingDepth\n\t\t\tif (visitingTypeSlashNames.has(typeSlashName)) return 1\n\n\t\t\tvisitingTypeSlashNames.add(typeSlashName)\n\t\t\tlet depth = 1\n\t\t\tfor (const dependencyTypeSlashName of depsGraph[typeSlashName]?.dependencies ?? []) {\n\t\t\t\tif (dependentTypeSlashNameSet.has(dependencyTypeSlashName)) {\n\t\t\t\t\tdepth = Math.max(depth, getDepth(dependencyTypeSlashName) + 1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tvisitingTypeSlashNames.delete(typeSlashName)\n\t\t\tdepthByTypeSlashName.set(typeSlashName, depth)\n\t\t\treturn depth\n\t\t}\n\n\t\tconst waves: LocalModuleId[][] = []\n\t\tfor (const dependentTypeSlashName of dependentTypeSlashNames) {\n\t\t\tconst depth = getDepth(dependentTypeSlashName)\n\t\t\tconst localId = typeSlashNameToLocalId.get(dependentTypeSlashName)\n\t\t\tassert(localId, \"Cannot find localId for\", dependentTypeSlashName)\n\t\t\tconst wave = waves[depth - 1] ?? []\n\t\t\twave.push(localId)\n\t\t\twaves[depth - 1] = wave\n\t\t}\n\n\t\treturn waves.filter(wave => wave.length > 0)\n\t}\n\n\tprivate handlePersistenceError(error: unknown, retryCount: number, onRetry: () => void) {\n\t\t// We care about fetch errors or api status codes. But the errors we receive here are\n\t\t// ServiceErrors that have been reconstructed from an throw in the service implementation\n\t\t// that was sent over postMessage.\n\t\tconst message = error instanceof Error ? error.message : \"\"\n\t\tconst code = error instanceof ServiceError ? error.code : 0\n\t\tconst status = error instanceof ServiceError ? error.status : 0\n\n\t\t// We retry if either it is a fetch error, which Fetcher.ts will rethrow as a connection\n\t\t// error. Or an http error except 400 bad request, 401 unauthorized, or 403 forbidden.\n\t\t// 401s are handled independently by the AccessTokenRefresher, so retrying the save is\n\t\t// pointless and can produce a tight retry loop when the session is unrecoverable.\n\t\tconst duplicateSaveError = code === ErrorCodes.ClientDuplicateSaveId\n\t\tconst connectionError = code === ErrorCodes.ConnectionError\n\t\tconst retriableHttpError = status >= 300 && status !== 400 && status !== 401 && status !== 403\n\t\tconst canRetry = connectionError || retriableHttpError || isRewriteRelativeImportsError(error)\n\n\t\tconst MAX_RETRIES = 20\n\t\tconst MAX_RELATIVE_IMPORTS_RETRIES = 2\n\n\t\tif (isRewriteRelativeImportsError(error)) {\n\t\t\tif (!canRetry || retryCount >= MAX_RELATIVE_IMPORTS_RETRIES) {\n\t\t\t\tlog.reportError(\"Relative imports error, exceeded max retries, making document read only:\", {\n\t\t\t\t\tmissing: error.persistedMissingRelativeImports,\n\t\t\t\t})\n\t\t\t\tthis.makeDocumentReadOnly()\n\t\t\t\ttoast({\n\t\t\t\t\ttype: \"add\",\n\t\t\t\t\tvariant: \"warning\",\n\t\t\t\t\tprimaryText: \"Cannot save changes.\",\n\t\t\t\t\tsecondaryText: \"Please reload.\",\n\t\t\t\t\tkey: \"client-outdated\",\n\t\t\t\t\tduration: Number.POSITIVE_INFINITY,\n\t\t\t\t\ticon: \"warning\",\n\t\t\t\t\tshowCloseButton: \"never\",\n\t\t\t\t\taction: {\n\t\t\t\t\t\ttitle: \"Reload\",\n\t\t\t\t\t\tonClick: () => {\n\t\t\t\t\t\t\tlog.reportError(\"ModulesStorage: Reloaded due to relative imports error.\", {\n\t\t\t\t\t\t\t\tmissing: error.persistedMissingRelativeImports,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\twindow.top!.location.reload()\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t\treturn { error: error, dropTransient: true }\n\t\t\t}\n\n\t\t\t// We allow temporary network errors, in which case we will do nothing, the internal\n\t\t\t// state will remain the same including the transient save. We will try again soon.\n\t\t\tlog.debug(\"Relative imports error, will retry:\", {\n\t\t\t\tmissing: error.persistedMissingRelativeImports,\n\t\t\t})\n\t\t\tonRetry()\n\t\t\treturn { error: error, dropTransient: false }\n\t\t} else if (duplicateSaveError && retryCount > 0) {\n\t\t\t// If we have retried the server might tell us the save id already exists. Which happens\n\t\t\t// if the response was lost in a network error. We basically do nothing in that case,\n\t\t\t// except remove the transient.\n\t\t\tlog.debug(\"Ignoring duplicated save id.\")\n\t\t} else if (duplicateSaveError) {\n\t\t\t// If it is a duplicate save error without a retry, that points to some bad logic. We\n\t\t\t// report and drop the offending transient save.\n\t\t\tlog.debug(\"Duplicate save id error, will drop transient save:\", error)\n\t\t\treturn { error: error, dropTransient: true }\n\t\t} else if (canRetry && retryCount < MAX_RETRIES) {\n\t\t\t// We allow temporary network errors, in which case we will do nothing, the internal\n\t\t\t// state will remain the same including the transient save. We will try again soon.\n\t\t\tlog.info(\"Connection error, will retry:\", { message, code, status, retryCount })\n\t\t\tonRetry()\n\t\t\treturn { dropTransient: false }\n\t\t} else if (canRetry) {\n\t\t\tlog.error(\"Error saving: too many retries, will drop transient save:\", {\n\t\t\t\tmessage,\n\t\t\t\tcode,\n\t\t\t\tstatus,\n\t\t\t\tretryCount,\n\t\t\t})\n\t\t} else {\n\t\t\tlog.debug(\"Error saving, will drop transient save:\", error)\n\t\t\treturn { error, dropTransient: true }\n\t\t}\n\n\t\treturn { dropTransient: false }\n\t}\n\n\tprivate moduleUsesLocalImportMapSpecifiers(typeSlashName: TypeSlashName) {\n\t\tconst [type, name] = splitTypeSlashName(typeSlashName)\n\n\t\t// Layout Templates can always use import map specifiers.\n\t\tif (type === ModuleType.LayoutTemplate) return true\n\n\t\t// Metadata modules are always loaded alongside their associated page\n\t\t// modules, so they can safely use import map specifiers. This ensures\n\t\t// that collections imported by the metadata module stay in sync with\n\t\t// the same collections imported by the page module.\n\t\tif (type === ModuleType.WebPageMetadata || type === ModuleType.SiteMetadata) return true\n\n\t\t// Collection modules can be used as external modules in some flows.\n\t\t// Until that is no longer supported it's not safe to assume local\n\t\t// modules are available.\n\t\tif (type === ModuleType.Collection) return experiments.isOn(\"collectionLocalModuleImportMapEntries\")\n\n\t\tif (type === ModuleType.Screen) {\n\t\t\tconst page = this.treeStore.tree.get(name)\n\t\t\t// If the module is no longer in the tree, it is either a deleted Web Page, or a deleted\n\t\t\t// Prototype Screen. It's safe to return true for a deleted Prototype Screen because\n\t\t\t// deleting a Canvas Page, removes references to the prototype in all other scopes,\n\t\t\t// meaning users do not have to expect a deleted prototype screen to be updated to\n\t\t\t// reflect updates to dependencies.\n\t\t\tif (isNull(page)) return true\n\t\t\t// If Screens are Web Pages, they can use import map specifiers for their\n\t\t\t// local dependencies.\n\t\t\tif (isWebPageNode(page)) return true\n\t\t}\n\n\t\treturn false\n\t}\n\n\t/** This will process the results from a transient save. This might update the tree, at which\n\t * point we must also update the this.persistedModules to match before any async/await or timers. */\n\tprivate processTransientSaveData(\n\t\t{ nextPersistedModules, transientSave, data }: TransientSaveResult,\n\t\terrors?: ErrorNode[],\n\t\tkitSectionsStructure?: KitSection[],\n\t): {\n\t\tnextPersistedModules: PersistedModules\n\t\tupdatedModuleLocalId: LocalModuleId\n\t} {\n\t\tconst treeVersion = transientSave.treeVersion ?? this.treeStore.remoteTreeVersion\n\n\t\tlet updatedModuleLocalId: LocalModuleId | undefined = undefined\n\t\tnextPersistedModules = produce(nextPersistedModules, draft => {\n\t\t\tconst dataIterator = data.values()\n\n\t\t\t// The changed module is coming first in the data array,\n\t\t\t// the order is guaranteed by the API.\n\t\t\tconst changedModule: ModulesAPI.ModuleWithSave = dataIterator.next().value!\n\t\t\tupdatedModuleLocalId = asLocalId(changedModule.localId)\n\n\t\t\tconst persistedModule = this.createPersistedLocalModuleFromSaveData(changedModule, transientSave)\n\n\t\t\tconst isUpToDate = this.updateTreeNode(\n\t\t\t\tchangedModule.localId,\n\t\t\t\ttreeVersion,\n\t\t\t\tpersistedModule,\n\t\t\t\terrors,\n\t\t\t\tkitSectionsStructure,\n\t\t\t)\n\t\t\tif (!isUpToDate) return\n\n\t\t\tdraft.set(updatedModuleLocalId, persistedModule as PersistedLocalModuleDraft)\n\n\t\t\t// The rest are dependent modules\n\t\t\tfor (const dependentModule of dataIterator) {\n\t\t\t\tconst prevModule: Draft<PersistedModule> | undefined = draft.get(asLocalId(dependentModule.localId))\n\t\t\t\tassert(prevModule, dependentModule.localId, \"is not in persistedModules\")\n\t\t\t\tthis.updateTreeNodeWithOwnTreeVersion(dependentModule.localId, dependentModule)\n\t\t\t\tthis.applyDependentModuleSaveData(prevModule, dependentModule)\n\t\t\t}\n\t\t})\n\t\tassert(updatedModuleLocalId, \"Updated module\", transientSave, \"is not found in the response\")\n\n\t\treturn {\n\t\t\tnextPersistedModules,\n\t\t\tupdatedModuleLocalId,\n\t\t}\n\t}\n\n\tprivate setNextInternalState({\n\t\tdependenciesModule,\n\t\tpersistedModules,\n\t\ttransientSaves,\n\t\tdepsGraph,\n\t\tdidRemoteChange,\n\t\tmultiplayerChange = false,\n\t}: {\n\t\tdependenciesModule: DependenciesModule | undefined\n\t\tpersistedModules: PersistedModules\n\t\ttransientSaves: TransientSaves\n\t\tdepsGraph: DependencyGraph\n\t\t/** True if the changes we\u2019re applying also affected the backend. */\n\t\tdidRemoteChange: boolean\n\t\t/** True if the state update is caused by a multiplayer event. */\n\t\tmultiplayerChange?: boolean\n\t}): void {\n\t\tthis.dependenciesModule = dependenciesModule\n\t\tthis.persistedModules = persistedModules\n\t\tthis.transientSaves = transientSaves\n\n\t\tconst snapshot = takeStateSnapshot(\n\t\t\tdependenciesModule,\n\t\t\tthis.lastSnapshot.dependenciesModule,\n\t\t\tpersistedModules,\n\t\t\ttransientSaves,\n\t\t\tdepsGraph,\n\t\t\tthis.lastSnapshot.modules,\n\t\t\tthis.initialized,\n\t\t\tdidRemoteChange,\n\t\t\tmultiplayerChange,\n\t\t)\n\n\t\tconst prevInitialized = this.lastSnapshot.initialized\n\n\t\tthis.lastSnapshot = {\n\t\t\tdependenciesModule: snapshot.dependenciesModule,\n\t\t\tmodules: snapshot.modules,\n\t\t\tdepsGraph: snapshot.depsGraph,\n\t\t\tinitialized: snapshot.initialized,\n\t\t}\n\n\t\t// If nothing changed in the publicly shared state do not notify subscribers.\n\t\tif (snapshot.metadata.patches.length === 0 && snapshot.initialized === prevInitialized) return\n\n\t\tthis.notifyListeners(snapshot)\n\t}\n\n\t/**\n\t * Queues a download of the source content for a module. This is used to ensure that we are not hitting the browser's request limit.\n\t *\n\t * 1200 is the arbitrary number that we got from the browser's request limit testing.\n\t */\n\tprivate downloadQueue = new LimitedRunner(1200)\n\n\t/** Will download the source content and compile it to get the module content, source map, and imports. */\n\tasync createLocalModuleFromModule(module: PersistedServerModule): Promise<PersistedLocalModuleDraft> {\n\t\tlog.debug(\"compiling server module:\", module.localId)\n\t\tlet sourceContent = module.sourceContent\n\t\tif (!sourceContent) {\n\t\t\tsourceContent = await this.fetchSourceContentFromData(module)\n\t\t}\n\n\t\tconst submoduleContents: SubmoduleContents = {}\n\t\tconst binaryAssetContents: BinaryAssets = {}\n\n\t\tconst downloadQueue = this.downloadQueue\n\n\t\tconst tasks = new Array<Promise<void>>()\n\n\t\tfor (const filename of module.submodules) {\n\t\t\ttasks.push(\n\t\t\t\tdownloadQueue.run(async () => {\n\t\t\t\t\tconst response = await fetch(module.baseURL + filename)\n\t\t\t\t\tsubmoduleContents[filename as keyof SubmoduleContents] = await response.text()\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\tfor (const filename of module.binaryAssets) {\n\t\t\ttasks.push(\n\t\t\t\tdownloadQueue.run(async () => {\n\t\t\t\t\tconst response = await fetch(module.baseURL + filename)\n\t\t\t\t\tconst buffer = await response.arrayBuffer()\n\t\t\t\t\tbinaryAssetContents[filename as keyof BinaryAssets] = new Uint8Array(buffer)\n\t\t\t\t}),\n\t\t\t)\n\t\t}\n\n\t\tawait Promise.all(tasks)\n\n\t\tconst typeSlashName = getTypeSlashName(module)\n\t\tconst compilation = await this.compile({\n\t\t\tlocalId: module.localId,\n\t\t\tname: typeSlashName,\n\t\t\tsource: sourceContent,\n\t\t\ttype: module.type,\n\t\t\tincludeSourceMap: shouldIncludeSourceMap(module.type),\n\t\t})\n\n\t\t// We've made a pending server module local, so don't need to do it next\n\t\t// time the scope switches.\n\t\tfor (const [key, list] of this.lazyServerModulesForTransientSaves) {\n\t\t\tlist.delete(typeSlashName)\n\t\t\tif (list.size === 0) this.lazyServerModulesForTransientSaves.delete(key)\n\t\t}\n\n\t\treturn {\n\t\t\t...module,\n\t\t\tkind: \"local\",\n\t\t\tid: module.id,\n\t\t\tlocalId: module.localId,\n\t\t\tsourceContent,\n\t\t\tmoduleContent: compilation.code,\n\t\t\tsourceMapContent: compilation.sourceMap,\n\t\t\tsubmoduleContents,\n\t\t\tbinaryAssetContents,\n\t\t\timports: compilation.imports,\n\t\t\tsourceRevision: sourceRevisionForPersistedModule(module),\n\t\t\tannotations: compilation.annotations,\n\t\t} satisfies PersistedLocalModule as PersistedLocalModuleDraft\n\t}\n\n\tprivate async createBatchSaveForUpdatedModule(\n\t\tmoduleId: \"$new\" | \"$upsertName\" | GlobalModuleId,\n\t\tsave: TransientModuleSave,\n\t\tpersistedModules: PersistedModules,\n\t\tnewSaveIds: ReadonlyMap<TypeSlashName, SaveId>,\n\t\tnewFilenames: ReadonlyMap<TypeSlashName, ModuleFilenames>,\n\t\tparams: PersistParams,\n\t): Promise<ModulesAPI.BatchSave> {\n\t\tconst typeSlashName = getTypeSlashName(save)\n\t\tconst {\n\t\t\tlocalId,\n\t\t\tmoduleContent,\n\t\t\tsourceContent,\n\t\t\tsourceMapContent,\n\t\t\tsubmoduleContents = {},\n\t\t\tbinaryAssetContents = {},\n\t\t\tmetadata: transientMetadata,\n\t\t\tsourceRevision: transientSourceRevision,\n\t\t\timports,\n\t\t\ttype: transientType,\n\t\t\tname: transientName,\n\t\t\tannotations: _annotations,\n\t\t\tupdate: _update,\n\t\t\t// Only keys we want to pass on to the API should remain.\n\t\t\t// We use rest props because it will automatically pipe through any new values that we add.\n\t\t\t...transientRest\n\t\t} = save\n\n\t\t// Arguments validation\n\t\tswitch (moduleId) {\n\t\t\tcase \"$new\":\n\t\t\t\tassert(localId === undefined, `Attempted to create ${typeSlashName} but it already has localId: ${localId}`)\n\t\t\t\tbreak\n\n\t\t\tcase \"$upsertName\":\n\t\t\t// We rely on fall-through here.\n\t\t\t// eslint-disable-next-line no-fallthrough\n\t\t\tdefault:\n\t\t\t\tassert(localId !== undefined, `The transient save for the provided moduleId: ${moduleId} doesn't have localId`)\n\t\t}\n\n\t\t// We use rest props here because it will automatically pipe through any new values that we add.\n\t\tconst { type, name, metadata, files: additionalFiles, ...rest } = params\n\t\tassert(\n\t\t\ttype === transientType && name === transientName,\n\t\t\t`Mismatched type/name between save and parameters: ${type}/${name} !== ${transientType}/${transientName}`,\n\t\t)\n\n\t\tconst filenames = filenamesFromModuleName(name)\n\n\t\tlet content: string = moduleContent\n\t\tif (imports.relative.length > 0) {\n\t\t\tcontent = await this.replaceRelativeImportsWithAbsolute(\n\t\t\t\ttypeSlashName,\n\t\t\t\tmoduleContent,\n\t\t\t\timports.relative,\n\t\t\t\tpersistedModules,\n\t\t\t\tnewSaveIds,\n\t\t\t\tgetKeys(submoduleContents),\n\t\t\t\tnewFilenames,\n\t\t\t)\n\t\t}\n\t\tif (sourceMapContent) {\n\t\t\tcontent += `\\n//# sourceMappingURL=./${filenames.sourceMap}`\n\t\t}\n\n\t\t// Keep any user-provided files and add the module and source code.\n\t\tconst files = (additionalFiles ?? []).concat([\n\t\t\t{ name: filenames.module, type: \"module\", content },\n\t\t\t{ name: filenames.source, type: \"source\", content: sourceContent },\n\t\t])\n\t\tif (sourceMapContent) {\n\t\t\tfiles.push({ name: filenames.sourceMap, type: \"sourceMap\", content: sourceMapContent })\n\t\t}\n\n\t\t// Add submodules to the files array.\n\t\tfor (const [filename, submoduleContent] of Object.entries(submoduleContents)) {\n\t\t\tfiles.push({ name: filename, type: \"submodule\", content: submoduleContent })\n\t\t}\n\n\t\t// Add binary assets to the files array.\n\t\tfor (const [filename, binaryAsset] of Object.entries(binaryAssetContents)) {\n\t\t\tfiles.push({ name: filename, type: \"binaryAsset\", bytes: binaryAsset })\n\t\t}\n\n\t\t// Only add the metadata field if we\u2019re fully patching the previous value (to prevent data loss).\n\t\tconst maybeMetadata: { metadata?: ModulesAPI.BatchSave[\"metadata\"] } = {}\n\t\tif (transientMetadata || metadata) {\n\t\t\tif (localId) {\n\t\t\t\t// Metadata is patched in the client, so we need to look up last known persisted data.\n\t\t\t\t// TODO: We may want to support this on the server to avoid losing keys in rare cases.\n\t\t\t\tconst persistedSave = persistedModules.get(asLocalId(localId))\n\t\t\t\tassert(\n\t\t\t\t\t// We don't know if upserts are creating or updating so we have to allow them.\n\t\t\t\t\tpersistedSave || moduleId === \"$upsertName\",\n\t\t\t\t\t`Cannot safely update metadata for ${moduleId} (${localId})`,\n\t\t\t\t)\n\t\t\t\tmaybeMetadata.metadata = {\n\t\t\t\t\t...persistedSave?.metadata,\n\t\t\t\t\t...transientMetadata,\n\t\t\t\t\t...metadata,\n\t\t\t\t\t// Track the source revision in the metadata to make debugging easier.\n\t\t\t\t\t// This should supersede any source revision passed through on the\n\t\t\t\t\t// persist params as the revision on the transient module was the\n\t\t\t\t\t// revision of the source at the time it was generated.\n\t\t\t\t\t[ModuleMetadata.SourceRevision]: transientSourceRevision,\n\t\t\t\t} as UnsafeJSON\n\t\t\t} else {\n\t\t\t\t// We're creating a new module, so no need to check persisted metadata.\n\t\t\t\tmaybeMetadata.metadata = {\n\t\t\t\t\t...transientMetadata,\n\t\t\t\t\t...metadata,\n\t\t\t\t\t[ModuleMetadata.SourceRevision]: transientSourceRevision,\n\t\t\t\t} as UnsafeJSON\n\t\t\t}\n\t\t}\n\n\t\t// Combine transient save data, computed values, and parameters into one object for the API.\n\t\treturn {\n\t\t\t...transientRest,\n\t\t\tmoduleId,\n\t\t\ttype,\n\t\t\tname,\n\t\t\tfiles,\n\t\t\timports,\n\t\t\tdetached: this.detached,\n\t\t\t...rest,\n\t\t\t...maybeMetadata,\n\t\t}\n\t}\n\n\tprivate async createBatchSaveForDependentModule(\n\t\tlocalId: LocalModuleId,\n\t\tpersistedModules: PersistedModules,\n\t\tnewSaveIds: ReadonlyMap<TypeSlashName, SaveId>,\n\t\tdependencyFilenames: ReadonlyMap<TypeSlashName, ModuleFilenames>,\n\t): Promise<ModulesAPI.BatchSave> {\n\t\tconst module = persistedModules.get(localId)\n\t\tassert(module, localId, \"is not found in persistedModules\")\n\t\tassert(module.kind === \"local\", \"persisted module is not a local module\")\n\n\t\tconst typeSlashName = getTypeSlashName(module)\n\t\tconst filenames = filenamesFromModuleName(module.name)\n\n\t\tconst imports = module.imports\n\t\tlet content: string = module.moduleContent\n\t\tif (imports.relative.length > 0) {\n\t\t\tcontent = await this.replaceRelativeImportsWithAbsolute(\n\t\t\t\ttypeSlashName,\n\t\t\t\tmodule.moduleContent,\n\t\t\t\timports.relative,\n\t\t\t\tpersistedModules,\n\t\t\t\tnewSaveIds,\n\t\t\t\tgetKeys(module.submoduleContents),\n\t\t\t\tdependencyFilenames,\n\t\t\t)\n\t\t}\n\n\t\tconst saveId = newSaveIds.get(typeSlashName)\n\t\tassert(saveId, \"newSaveIds don't contain saveId for\", typeSlashName)\n\n\t\t// Only add the metadata field if we\u2019re fully patching the previous value (to prevent data loss).\n\t\tconst maybeMetadata: { metadata?: ModulesAPI.BatchSave[\"metadata\"] } = {}\n\t\tconst nextLocalModuleImportMapEntriesValue = this.moduleUsesLocalImportMapSpecifiers(typeSlashName)\n\t\tif (module.metadata[ModuleMetadata.LocalModuleImportMapEntries] !== nextLocalModuleImportMapEntriesValue) {\n\t\t\t// Update ModuleMetadata.LocalModuleImportMapEntries to the reflect\n\t\t\t// the state after replacing the relative imports.\n\t\t\tmaybeMetadata.metadata = {\n\t\t\t\t...module.metadata,\n\t\t\t\t[ModuleMetadata.LocalModuleImportMapEntries]: nextLocalModuleImportMapEntriesValue,\n\t\t\t} as UnsafeJSON\n\t\t}\n\n\t\treturn {\n\t\t\ttype: module.type,\n\t\t\tmoduleId: module.id,\n\t\t\tname: module.name,\n\t\t\tsaveId,\n\t\t\t// For the dependent modules we are using patching and only update moduleContent because the import URLs are updated,\n\t\t\t// while the source code remains the same, i.e. relative imports there stay the same, as well as all of the other files.\n\t\t\tpatchSaveId: module.saveId,\n\t\t\tfiles: [{ name: filenames.module, type: \"module\", content }],\n\t\t\t// FIXME: Stop sending imports with patch saves\n\t\t\timports,\n\t\t\tdetached: this.detached,\n\t\t\t...maybeMetadata,\n\t\t}\n\t}\n\n\tprivate findPersistedModuleLocalIdByTypeSlashName(\n\t\tpersistedModules: PersistedModules,\n\t\ttypeSlashName: TypeSlashName,\n\t): LocalModuleId | undefined {\n\t\tconst persistedLocalIdsByTypeSlashName = this.ensurePersistedLocalIdsByTypeSlashNameCacheFor(persistedModules)\n\t\treturn persistedLocalIdsByTypeSlashName.get(typeSlashName)\n\t}\n\n\tprivate ensurePersistedLocalIdsByTypeSlashNameCacheFor(\n\t\tpersistedModules: PersistedModules,\n\t): ReadonlyMap<TypeSlashName, LocalModuleId> {\n\t\tlet persistedLocalIdsByTypeSlashName = this.persistedLocalIdsByTypeSlashNameCache.get(persistedModules)\n\t\tif (!persistedLocalIdsByTypeSlashName) {\n\t\t\tpersistedLocalIdsByTypeSlashName = buildPersistedLocalIdsByTypeSlashName(persistedModules)\n\t\t\tthis.persistedLocalIdsByTypeSlashNameCache.set(persistedModules, persistedLocalIdsByTypeSlashName)\n\t\t}\n\t\treturn persistedLocalIdsByTypeSlashName\n\t}\n\n\tprivate async replaceRelativeImportsWithAbsolute(\n\t\ttypeSlashName: TypeSlashName,\n\t\tmoduleContent: CodeWithRelativeImports,\n\t\trelativeImports: Iterable<string>,\n\t\tpersistedModules: PersistedModules,\n\t\tnewSaveIds: ReadonlyMap<TypeSlashName, SaveId>,\n\t\tsubmodules: readonly SubmoduleFilename[],\n\t\tnewFileNames: ReadonlyMap<TypeSlashName, ModuleFilenames> | undefined,\n\t): Promise<string> {\n\t\tconst { modulesCDN } = getServiceMap()\n\t\tconst replacementMap: ReplacementMap = {}\n\n\t\tfor (const filename of submodules) {\n\t\t\t// Submodules share the same absolute URL prefix with the main\n\t\t\t// module. Therefore we can use relative imports. This also\n\t\t\t// ensures that imports keep working when duplicating projects\n\t\t\t// or changing the saveId because a dependency did change.\n\t\t\tconst submoduleImport = getSubmoduleImport(filename)\n\t\t\treplacementMap[submoduleImport] = submoduleImport\n\t\t}\n\n\t\t// If the main module uses import map entries to avoid needless saves\n\t\t// when dependencies change, flag that and rewrite relative imports to\n\t\t// these static import map specifiers. Otherwise continue to rewrite the\n\t\t// import to the latest full absolute module url that changes with every\n\t\t// save.\n\t\tconst usesImportMapEntries = this.moduleUsesLocalImportMapSpecifiers(typeSlashName)\n\n\t\tconst missingDependencyTypeSlashNames = new Set<string>()\n\t\tfor (const relativeImportSpecifier of relativeImports) {\n\t\t\tif (relativeImportSpecifier in replacementMap) continue\n\n\t\t\tconst dependencyTypeSlashName = normalizePath(relativeImportSpecifier, typeSlashName)\n\t\t\t// Note: it is possible for userCode to reference a path without a\n\t\t\t// moduleType, at the base of the virtual path, this will not\n\t\t\t// resolve but will result in some console errors. eg: code file\n\t\t\t// with import of `../Foo.tsx` will results in a\n\t\t\t// dependencyTypeSlashName === `Foo.tsx` which is technically\n\t\t\t// invalid.\n\t\t\tif (!dependencyTypeSlashName) continue\n\n\t\t\tconst dependencyLocalId = this.findPersistedModuleLocalIdByTypeSlashName(\n\t\t\t\tpersistedModules,\n\t\t\t\tdependencyTypeSlashName,\n\t\t\t)\n\n\t\t\t// There can be a situation when an imported module doesn't actually exist,\n\t\t\t// it will end up in an error during evaluation.\n\t\t\tif (!dependencyLocalId) {\n\t\t\t\tmissingDependencyTypeSlashNames.add(dependencyTypeSlashName)\n\t\t\t\tlog.error(\"Cannot resolve\", relativeImportSpecifier, \"from\", typeSlashName)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// We are using the latest \"persisted\" version of the dependencies.\n\t\t\tconst dependencyModule = persistedModules.get(dependencyLocalId)\n\t\t\tassert(dependencyModule)\n\n\t\t\tconst { id: depId, files } = dependencyModule\n\t\t\tconst depSaveId = newSaveIds.get(dependencyTypeSlashName) ?? dependencyModule.saveId\n\n\t\t\t// When updating a dependency that is being updated for the first time after being\n\t\t\t// renamed, the persisted module doesn't have the latest module name, so we use the\n\t\t\t// provided one.\n\t\t\tconst sourceName = newFileNames?.get(dependencyTypeSlashName)?.module ?? files.module\n\t\t\tassert(isString(sourceName), \"Must have a module file name to build a local module import map specifier.\")\n\t\t\treplacementMap[relativeImportSpecifier] = usesImportMapEntries\n\t\t\t\t? localModuleImportMapSpecifier(dependencyLocalId, sourceName) // Generate the static import map specifier.\n\t\t\t\t: `${modulesCDN}/${depId}/${depSaveId}/${sourceName}` // Generate the full URL to the module.\n\t\t}\n\t\tconst rewriteResult = await rewriteRelativeImports(moduleContent, replacementMap)\n\t\tif (rewriteResult.ok) return rewriteResult.value\n\n\t\t// Missing relative imports in user code files are likely the user's mistake.\n\t\tif (typeSlashName.startsWith(ModuleType.Code)) return rewriteResult.error.partiallyProcessedCode\n\n\t\t// Determine if all of the missing relative imports have been persisted at least once.\n\t\tconst persistedMissingRelativeImports = new Set<TypeSlashName>()\n\t\tconst tree = this.treeStore.tree\n\t\tfor (const relativeImport of rewriteResult.error.unresolvedRelativeImports) {\n\t\t\tconst dependencyTypeSlashName = normalizePath(relativeImport, typeSlashName)\n\t\t\tif (!dependencyTypeSlashName) continue\n\t\t\tconst [type] = splitTypeSlashName(dependencyTypeSlashName)\n\t\t\t// Relative imports of custom code components are probably the users's mistake.\n\t\t\tif (type === ModuleType.Code) continue\n\n\t\t\t// For modules that are not code, the typeSlashName is the localId.\n\t\t\tconst node = tree.getNodeWithTrait(dependencyTypeSlashName, isLocalModuleNode)\n\t\t\tif (!node) continue\n\n\t\t\t// If the LocalModuleNode exists, the module has been persisted at least once.\n\t\t\tpersistedMissingRelativeImports.add(dependencyTypeSlashName)\n\t\t\tbreak\n\t\t}\n\n\t\t// If all of the missing relative imports have been yet to be persisted we can return the\n\t\t// partially processed code. We trust that the module should be persisted shortly as it was\n\t\t// just created, and the creation will cause the relative imports of this dependent to be\n\t\t// rewritten again.\n\t\tif (persistedMissingRelativeImports.size === 0) {\n\t\t\tlog.reportError(\"Failed to rewrite relative imports due to unpersisted relative dependencies\", {\n\t\t\t\trelativeImports,\n\t\t\t\tunresolved: Array.from(rewriteResult.error.unresolvedRelativeImports),\n\t\t\t})\n\n\t\t\treturn rewriteResult.error.partiallyProcessedCode\n\t\t}\n\n\t\tlog.reportError(\"Failed to rewrite relative imports\", {\n\t\t\ttypeSlashName,\n\t\t\tmissing: Array.from(persistedMissingRelativeImports),\n\t\t})\n\n\t\t// We already log the errors when we cannot resolve a relative import above, so no need to\n\t\t// do it here also.\n\t\t//\n\t\t// TODO: consider throwing an error that will prevent the persistence of the modules with\n\t\t//       errors in the first place, the reason it's not yet done is because it can be tricky\n\t\t//       to predict what will break if introduce this new behavior and we also don't cleanup\n\t\t//       \"transient\" saves yet in case the persistence fails. Basically this decision would\n\t\t//       require more investigation before we can proceed with it.\n\t\tthrow new RewriteRelativeImportsError(persistedMissingRelativeImports)\n\t}\n\n\tprivate async getDependenciesFiles({ baseURL, files }: ModulesAPI.ModuleWithSave) {\n\t\tconst [importMapResult, dependenciesMapResult] = await Promise.allSettled([\n\t\t\tthis.downloadQueue.run(async () => {\n\t\t\t\tconst response = await fetch(baseURL + files.importMap)\n\t\t\t\tif (response.ok !== true) throw new Error(\"failed to load importMap file\")\n\t\t\t\treturn response.text()\n\t\t\t}),\n\t\t\tthis.downloadQueue.run(async () => {\n\t\t\t\tconst response = await fetch(baseURL + files.dependencies)\n\t\t\t\tif (response.ok !== true) throw new Error(\"failed to load dependencies file\")\n\t\t\t\treturn response.text()\n\t\t\t}),\n\t\t])\n\n\t\tassert(importMapResult.status === \"fulfilled\", \"The importMap has to exist on the module\")\n\t\tconst importMapContent = importMapResult.value\n\n\t\tlet dependenciesMapContent: string | undefined\n\t\tif (dependenciesMapResult.status === \"fulfilled\") {\n\t\t\tdependenciesMapContent = dependenciesMapResult.value\n\t\t} else {\n\t\t\tlog.warn(\"No dependencies file was found!\")\n\t\t}\n\t\treturn { importMapContent, dependenciesMapContent }\n\t}\n\n\t/**\n\t * Persist json files for a kit. Skips usual dependencies on a transient module since JSON\n\t * doesn't need to be compiled or evaluated.\n\t *\n\t * Sections are treated as additional files and can be accessed deterministically by\n\t * {ModuleId}/{SaveId}/{section.id}.json.\n\t * Vector sets are stored as separate files: {ModuleId}/{SaveId}/{setId}.json\n\t */\n\tasync upsertKit(\n\t\tkit: WireframerKitJSON,\n\t\ticon: string | undefined,\n\t\tclipboardData: { id: string; content: KitClipboardData }[],\n\t\tsets: { id: string; content: VectorSetDictionary }[],\n\t\tassets: Set<string>,\n\t) {\n\t\treturn synchronize(async () => {\n\t\t\tconst source = JSON.stringify(kit)\n\t\t\tconst files: ModulesAPI.BatchSave[\"files\"] = [\n\t\t\t\t{\n\t\t\t\t\tname: \"kit.json\",\n\t\t\t\t\ttype: \"source\",\n\t\t\t\t\tcontent: source,\n\t\t\t\t},\n\t\t\t\t...clipboardData.map(section => ({\n\t\t\t\t\tname: `${section.id}.json`,\n\t\t\t\t\ttype: \"kitSection\",\n\t\t\t\t\tcontent: JSON.stringify(section.content),\n\t\t\t\t})),\n\t\t\t\t...sets.map(set => ({\n\t\t\t\t\tname: `${set.id}.json`,\n\t\t\t\t\ttype: \"kitVectorSetNames\",\n\t\t\t\t\tcontent: JSON.stringify(set.content),\n\t\t\t\t})),\n\t\t\t]\n\n\t\t\tconst now = performance.now()\n\n\t\t\t// A project can only have one kit module.\n\t\t\tconst localId = asLocalId(`${ModuleType.Kit}/kit`)\n\n\t\t\tconst save: ModulesAPI.BatchSave = {\n\t\t\t\ttype: ModuleType.Kit,\n\t\t\t\tfiles,\n\t\t\t\tassets: assets.size > 0 ? Array.from(assets) : undefined,\n\t\t\t\tname: kitModuleName,\n\t\t\t\tmoduleId: this.persistedModules.get(localId)?.id ?? \"$upsertName\",\n\t\t\t\tsaveId: generateSaveId(),\n\t\t\t\tmetadata: {\n\t\t\t\t\t[ModuleMetadata.Kit]: {\n\t\t\t\t\t\tid: kit.id,\n\t\t\t\t\t\ttitle: kit.title,\n\t\t\t\t\t\ticon,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\timports: {\n\t\t\t\t\tabsolute: [],\n\t\t\t\t\trelative: [],\n\t\t\t\t\tbare: [],\n\t\t\t\t},\n\t\t\t\tdetached: false,\n\t\t\t}\n\n\t\t\tassert(this.modulesService)\n\n\t\t\tconst { data } = await this.modulesService.saveBatch({ batch: [save], copyOnWrite: this.detached })\n\n\t\t\tthis.setNextInternalState({\n\t\t\t\tdependenciesModule: this.dependenciesModule,\n\t\t\t\ttransientSaves: this.transientSaves,\n\t\t\t\tpersistedModules: produce(this.persistedModules, draft => {\n\t\t\t\t\tfor (const module of data.values()) {\n\t\t\t\t\t\tif (module.localId !== localId) continue\n\n\t\t\t\t\t\tconst persistedModule: PersistedLocalModule = {\n\t\t\t\t\t\t\tkind: \"local\",\n\t\t\t\t\t\t\t...module,\n\t\t\t\t\t\t\tid: asGlobalId(module.id),\n\t\t\t\t\t\t\tlocalId: asLocalId(module.localId),\n\t\t\t\t\t\t\timports: module.imports,\n\t\t\t\t\t\t\tmoduleURL: module.baseURL + module.files.source,\n\t\t\t\t\t\t\tsourceContent: source,\n\t\t\t\t\t\t\tsourceMapContent: undefined,\n\t\t\t\t\t\t\tmoduleContent: source as CodeWithRelativeImports,\n\t\t\t\t\t\t\tsubmoduleContents: {},\n\t\t\t\t\t\t\tbinaryAssetContents: {},\n\t\t\t\t\t\t\tsourceRevision: undefined,\n\t\t\t\t\t\t\tannotations: undefined,\n\t\t\t\t\t\t\tupdate: now,\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdraft.set(localId, persistedModule as PersistedLocalModuleDraft)\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\t// Nothing depends on/is depended on by a kit - we can reuse the last snapshot's\n\t\t\t\t// dependency graph.\n\t\t\t\tdepsGraph: this.lastSnapshot.depsGraph,\n\t\t\t\tdidRemoteChange: true,\n\t\t\t})\n\t\t})\n\t}\n\n\tasync enqueueKitScreenshots(pageHtml: string, ids: Set<NodeID>, draft: boolean): Promise<void> {\n\t\tconst module = this.persistedModules.get(localModuleIdForStableName(ModuleType.Kit, \"kit\"))\n\t\t// We must have persisted the module at least once to have a moduleId to store screenshots under.\n\t\tassert(module, \"Kit module must have been persisted to enqueue screenshots\")\n\n\t\t// Set the \"saveId\" to save it under as requested, either \"draft\" placeholder or the most recent saveId.\n\t\tconst saveId = draft ? \"draft\" : module.saveId\n\t\tassert(saveId, \"Kit Save ID must be set\")\n\n\t\tassert(this.modulesService)\n\n\t\tawait this.modulesService.enqueueKitScreenshots({\n\t\t\tmoduleId: module.id,\n\t\t\tsaveId,\n\t\t\tids: Array.from(ids),\n\t\t\tkitPageContent: pageHtml,\n\t\t})\n\t}\n\n\ttakeSnapshot(): ModulesStorageSnapshot {\n\t\treturn new ModulesStorageSnapshot(this.persistedModules)\n\t}\n}\n\n/** Generate a moduleURL using the transient save id. */\nfunction moduleURL(transient: TransientModuleSave, persisted: PersistedModule) {\n\treturn `${getServiceMap().modulesCDN}/${persisted.id}/${transient.saveId}/${persisted.files.module}`\n}\n\nfunction takeStateSnapshot(\n\tdependenciesModule: DependenciesModule | undefined,\n\tprevImportMap: DependenciesModuleEntry | undefined,\n\tpersistedModules: PersistedModules,\n\ttransientSaves: TransientSaves,\n\tdepsGraph: DependencyGraph,\n\tprevModules: Immutable<ModulesMap>,\n\tinitialized: boolean,\n\tdidRemoteChange: boolean,\n\tmultiplayerChange: boolean,\n): ModulesStorageStateSnapshot {\n\tconst outdatedModuleTypeSlashNames = new Set(prevModules.keys())\n\tconst transientSaveLocalIds = new Set(transientSaves.keys())\n\tconst deletedTypeSlashNames: TypeSlashName[] = []\n\n\tconst [nextSnapshot, patches] = produceWithPatches(prevModules, draft => {\n\t\tfor (const persistedModule of persistedModules.values()) {\n\t\t\tconst localId = persistedModule.localId\n\t\t\tconst typeSlashName = getTypeSlashName(persistedModule)\n\t\t\tconst transientSave = transientSaves.get(localId)\n\t\t\t// Kits and Config modules are not evaluated, so we skip them, ensuring they are not\n\t\t\t// sent to runtime listeners for evaluation.\n\t\t\tconst type = transientSave?.type ?? persistedModule.type\n\t\t\tif (!isEvaluatedModuleType(type as ModuleType)) continue\n\n\t\t\t// TODO: Should this be the type from ModuleRuntime instead?\n\t\t\tlet nextModuleEntry: Draft<ModuleEntry>\n\t\t\tif (transientSave) {\n\t\t\t\tnextModuleEntry = {\n\t\t\t\t\tkind: \"local\",\n\t\t\t\t\tlocalId,\n\t\t\t\t\ttype: transientSave.type,\n\t\t\t\t\tname: transientSave.name,\n\t\t\t\t\tmoduleURL: moduleURL(transientSave, persistedModule),\n\t\t\t\t\tmoduleContent: transientSave.moduleContent,\n\t\t\t\t\tsourceContent: transientSave.sourceContent,\n\t\t\t\t\tsourceMapContent: transientSave.sourceMapContent,\n\t\t\t\t\tsubmoduleContents: transientSave.submoduleContents,\n\t\t\t\t\tbinaryAssetContents: transientSave.binaryAssetContents,\n\t\t\t\t\trelativeImports: transientSave.imports.relative as string[],\n\t\t\t\t\tfiles: persistedModule.files,\n\t\t\t\t\tsourceRevision: transientSave.sourceRevision,\n\t\t\t\t\tsvgIcon: transientSave.svgIcon,\n\t\t\t\t\tupdate: transientSave.update,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tconst sourceRevision = sourceRevisionForPersistedModule(persistedModule)\n\t\t\t\tnextModuleEntry =\n\t\t\t\t\tpersistedModule.kind === \"local\"\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tkind: \"local\",\n\t\t\t\t\t\t\t\tlocalId,\n\t\t\t\t\t\t\t\ttype: persistedModule.type,\n\t\t\t\t\t\t\t\tname: persistedModule.name,\n\t\t\t\t\t\t\t\tmoduleURL: persistedModule.moduleURL,\n\t\t\t\t\t\t\t\tmoduleContent: persistedModule.moduleContent,\n\t\t\t\t\t\t\t\tsourceContent: persistedModule.sourceContent,\n\t\t\t\t\t\t\t\tsourceMapContent: persistedModule.sourceMapContent,\n\t\t\t\t\t\t\t\tsubmoduleContents: persistedModule.submoduleContents,\n\t\t\t\t\t\t\t\tbinaryAssetContents: persistedModule.binaryAssetContents,\n\t\t\t\t\t\t\t\trelativeImports: persistedModule.imports.relative as string[],\n\t\t\t\t\t\t\t\tfiles: persistedModule.files,\n\t\t\t\t\t\t\t\tsourceRevision,\n\t\t\t\t\t\t\t\tsvgIcon: undefined,\n\t\t\t\t\t\t\t\tupdate: persistedModule.update,\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tkind: \"server\",\n\t\t\t\t\t\t\t\tlocalId,\n\t\t\t\t\t\t\t\ttype: persistedModule.type,\n\t\t\t\t\t\t\t\tname: persistedModule.name,\n\t\t\t\t\t\t\t\tmoduleURL: persistedModule.moduleURL,\n\t\t\t\t\t\t\t\tsourceContent: persistedModule.sourceContent,\n\t\t\t\t\t\t\t\trelativeImports: persistedModule.imports.relative as string[],\n\t\t\t\t\t\t\t\tfiles: persistedModule.files,\n\t\t\t\t\t\t\t\tsourceRevision,\n\t\t\t\t\t\t\t\tupdate: persistedModule.update,\n\t\t\t\t\t\t\t}\n\t\t\t}\n\n\t\t\tsetOrMerge(draft, typeSlashName, nextModuleEntry)\n\n\t\t\ttransientSaveLocalIds.delete(localId)\n\t\t\toutdatedModuleTypeSlashNames.delete(typeSlashName)\n\t\t}\n\n\t\t// Process the transientSaves that do not have a corresponding persistedModule yet (new modules).\n\t\tfor (const transientSaveLocalId of transientSaveLocalIds) {\n\t\t\tconst transientSave = transientSaves.get(transientSaveLocalId)\n\t\t\tassert(transientSave)\n\t\t\t// Here, we are ignoring the \"$new\" transient modules, that don't have a localId yet,\n\t\t\t// so they are not affecting the publicly visible state.\n\t\t\t// FIXME: update the TransientModuleSave type to make localId non-optional\n\t\t\tif (!transientSave.localId) continue\n\n\t\t\tconst filenames = filenamesFromModuleName(transientSave.name)\n\t\t\tconst nextModuleEntry: Draft<LocalModuleEntry> = {\n\t\t\t\tkind: \"local\",\n\t\t\t\tlocalId: transientSave.localId,\n\t\t\t\ttype: transientSave.type,\n\t\t\t\tname: transientSave.name,\n\t\t\t\t// Transient modules that have never been persisted on the backend don't have a real\n\t\t\t\t// moduleURL. But nothing can refer to them except local module. So we invent a\n\t\t\t\t// temporary moduleURL based on just the save id for the modules runtime.\n\t\t\t\tmoduleURL: `./transient/${transientSave.saveId}/${filenames.module}`,\n\t\t\t\tmoduleContent: transientSave.moduleContent,\n\t\t\t\tsourceContent: transientSave.sourceContent,\n\t\t\t\tsourceMapContent: transientSave.sourceMapContent,\n\t\t\t\tsubmoduleContents: transientSave.submoduleContents,\n\t\t\t\tbinaryAssetContents: transientSave.binaryAssetContents,\n\t\t\t\trelativeImports: transientSave.imports.relative as string[],\n\t\t\t\tfiles: filenames,\n\t\t\t\tsourceRevision: transientSave.sourceRevision,\n\t\t\t\tsvgIcon: transientSave.svgIcon,\n\t\t\t\tupdate: transientSave.update,\n\t\t\t}\n\t\t\tsetOrMerge(draft, transientSaveLocalId, nextModuleEntry)\n\t\t\toutdatedModuleTypeSlashNames.delete(getTypeSlashName(nextModuleEntry))\n\t\t}\n\n\t\tfor (const outdated of outdatedModuleTypeSlashNames) {\n\t\t\tdraft.delete(outdated)\n\t\t\tdeletedTypeSlashNames.push(outdated)\n\t\t}\n\t})\n\n\tconst deletedLocalIdsByTypeSlashNames: Record<TypeSlashName, LocalModuleId> = {}\n\tfor (const deletedTypeSlashName of deletedTypeSlashNames) {\n\t\tconst deletedModule = prevModules.get(deletedTypeSlashName)\n\t\tif (!deletedModule) continue\n\n\t\tdeletedLocalIdsByTypeSlashNames[deletedTypeSlashName] = deletedModule.localId\n\t}\n\n\tconst nextDependenciesMap: DependenciesModuleEntry | undefined = produce(prevImportMap, draft => {\n\t\tif (!dependenciesModule) return\n\n\t\tif (!draft) {\n\t\t\tconst value: DependenciesModuleEntry = {\n\t\t\t\tkind: \"dependencies\",\n\t\t\t\tlocalId: DEPENDENCIES_MODULE_TYPE_SLASH_NAME,\n\t\t\t\ttype: dependenciesModule.type,\n\t\t\t\tname: dependenciesModule.name,\n\t\t\t\timportMapContent: dependenciesModule.importMapContent,\n\t\t\t\tdependenciesMapContent: dependenciesModule.dependenciesMapContent,\n\t\t\t}\n\t\t\treturn value\n\t\t}\n\n\t\tdraft.importMapContent = dependenciesModule.importMapContent\n\t\tdraft.dependenciesMapContent = dependenciesModule.dependenciesMapContent\n\t})\n\n\tif (nextDependenciesMap && nextDependenciesMap !== prevImportMap) {\n\t\tpatches.push({\n\t\t\top: prevImportMap ? \"replace\" : \"add\",\n\t\t\tpath: [getTypeSlashName(nextDependenciesMap)],\n\t\t\tvalue: nextDependenciesMap,\n\t\t})\n\t}\n\n\treturn {\n\t\tdependenciesModule: nextDependenciesMap,\n\t\tmodules: nextSnapshot,\n\t\tdeletedLocalIdsByTypeSlashNames,\n\t\tdepsGraph,\n\t\tinitialized,\n\t\tmetadata: {\n\t\t\tpatches,\n\t\t\thasLocalChanges: transientSaves.size > 0,\n\t\t\tdidRemoteChange,\n\t\t\tmultiplayerChange,\n\t\t},\n\t}\n}\n\nfunction setOrMerge(\n\tdraft: Draft<ModulesMap>,\n\ttypeSlashName: TypeSlashName,\n\tentry: Draft<ServerModuleEntry | LocalModuleEntry>,\n) {\n\tconst prevModuleEntry = draft.get(typeSlashName)\n\n\tif (!prevModuleEntry) {\n\t\tdraft.set(typeSlashName, entry)\n\t\treturn\n\t}\n\n\tif (prevModuleEntry.kind !== entry.kind) {\n\t\tdraft.set(typeSlashName, entry)\n\t\treturn\n\t}\n\n\tif (prevModuleEntry.kind === \"server\") {\n\t\tassert(entry.kind === \"server\")\n\t\tassign<ServerModuleEntry>(prevModuleEntry, entry)\n\t\treturn\n\t}\n\n\tassert(entry.kind === \"local\")\n\n\t// We have to merge `relativeImports` and `files` manually because Immer\n\t// wouldn't do a deep merge, it will simple replace the field if the\n\t// reference is new.\n\tif (!isShallowEqualArray(prevModuleEntry.relativeImports, entry.relativeImports)) {\n\t\tprevModuleEntry.relativeImports = entry.relativeImports\n\t}\n\tif (!isShallowObjectEqual(prevModuleEntry.files, entry.files)) {\n\t\tprevModuleEntry.files = entry.files\n\t}\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tconst { relativeImports, files, ...nextEntry } = entry\n\tassign<Omit<LocalModuleEntry, \"relativeImports\" | \"files\">>(prevModuleEntry, nextEntry)\n}\n\nfunction assign<T>(obj1: NonNullable<T>, obj2: NonNullable<T>): void {\n\tObject.assign(obj1, obj2)\n}\n\nfunction isShallowEqualArray(arr1: readonly unknown[] | undefined, arr2: readonly unknown[] | undefined): boolean {\n\tif (!arr1 && !arr2) return true\n\n\tif (arr1 && arr2) {\n\t\tconst length1 = arr1.length\n\t\tif (length1 !== arr2.length) return false\n\t\tfor (let i = 0; i < length1; i++) {\n\t\t\tif (arr1[i] !== arr2[i]) return false\n\t\t}\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunction isSaveEvent(event: ModulesAPI.ModuleEvent): event is {\n\ttype: \"save\"\n\tmodule: ModulesAPI.ModuleWithSave\n} {\n\treturn event.type === \"save\"\n}\n\nfunction isDeleteEvent(event: ModulesAPI.ModuleEvent): event is {\n\ttype: \"delete\"\n\tid: string\n} {\n\treturn event.type === \"delete\"\n}\n\nfunction generateSaveId(): SaveId {\n\treturn randomBase62()\n}\n\nfunction shouldIncludeSourceMap(moduleType: string): boolean {\n\t// Only produce source maps for code, smart components, and shaders.\n\treturn moduleType === ModuleType.Code || moduleType === ModuleType.Canvas || moduleType === ModuleType.Shader\n}\n\nfunction asWritable<T>(arg: readonly T[]): T[] {\n\treturn arg as T[]\n}\n\nfunction replaceModuleSpecifier(code: string, fromSpecifier: string, toSpecifier: string): string {\n\t// TODO: modify `analyzeModuleImports` to return \"global\" index besides just line and column,\n\t//       and use it instead of the regex below to improve safety.\n\treturn code.replace(\n\t\tnew RegExp(`\\\\b(from\\\\s*)([\"'])${escapeRegExp(fromSpecifier)}\\\\2`, \"g\"),\n\t\t`$1${JSON.stringify(toSpecifier)}`,\n\t)\n}\n\n/**\n * Modules generated by Framer put relevant information as annotations on the\n * default export, however, there is no guarantee that this is the first export.\n * To ensure that we gather the right information from the annotations, we use\n * specific ones for these module types.\n */\nfunction annotationsForModuleType(type: ModuleType, annotations: ModuleAnnotations): ModuleAnnotations[number] {\n\tswitch (type) {\n\t\tcase ModuleType.Canvas:\n\t\tcase ModuleType.LayoutTemplate:\n\t\tcase ModuleType.Screen:\n\t\tcase ModuleType.Prototype:\n\t\tcase ModuleType.Collection:\n\t\tcase ModuleType.DraftCollection:\n\t\tcase ModuleType.WebPageMetadata:\n\t\tcase ModuleType.SiteMetadata:\n\t\tcase ModuleType.Snippets:\n\t\tcase ModuleType.Vector:\n\t\tcase ModuleType.VectorSet:\n\t\tcase ModuleType.Kit:\n\t\tcase ModuleType.Shader:\n\t\t\treturn annotations.default\n\t\tcase ModuleType.Code:\n\t\tcase ModuleType.CSS:\n\t\tcase ModuleType.ComponentPresets:\n\t\tcase ModuleType.Config:\n\t\tcase ModuleType.Localization:\n\t\tcase ModuleType.Design:\n\t\t\treturn Object.values(annotations)[0]\n\t\tdefault:\n\t\t\tassertNever(type)\n\t}\n}\n\n/**\n * Potential data loss incident window.\n * See https://www.notion.so/framer/06-09-2025-Data-loss-emergency-266adf6e8c96802e83bcde39894f6f7a\n */\nconst DATA_LOSS_WINDOW = {\n\tstart: new Date(\"2025-09-03T10:00:00Z\").getTime(),\n\tend: new Date(\"2025-09-07T13:00:00Z\").getTime(),\n}\n\n/** Returns true if the last module save id is out of sync with the tree and the time of save was in\n * the period we had potential data loss. */\nfunction checkDataLoss(localModuleNodes: ReadonlyChildList<LocalModuleNode>, save: ModulesAPI.ModuleWithSave): boolean {\n\tfor (const localModuleNode of localModuleNodes) {\n\t\tif (localModuleNode.id !== save.localId) continue\n\t\tif (localModuleNode.save.saveId === save.saveId) return false\n\n\t\tconst savedAt = new Date(save.savedAt).getTime()\n\t\tif (Number.isNaN(savedAt)) return false\n\t\treturn savedAt > DATA_LOSS_WINDOW.start && savedAt < DATA_LOSS_WINDOW.end\n\t}\n\treturn false\n}\n\nfunction buildPersistedLocalIdsByTypeSlashName(\n\tpersistedModules: PersistedModules,\n): ReadonlyMap<TypeSlashName, LocalModuleId> {\n\tconst persistedLocalIdsByTypeSlashName = new Map<TypeSlashName, LocalModuleId>()\n\tfor (const [localId, mod] of persistedModules.entries()) {\n\t\tpersistedLocalIdsByTypeSlashName.set(getTypeSlashName(mod), localId)\n\t}\n\treturn persistedLocalIdsByTypeSlashName\n}\n\nexport class ModulesStorageSnapshot {\n\tconstructor(private readonly persistedModules: PersistedModules) {\n\t\tthis.persistedLocalIdsByTypeSlashName = buildPersistedLocalIdsByTypeSlashName(persistedModules)\n\t}\n\n\tprivate readonly persistedLocalIdsByTypeSlashName: ReadonlyMap<TypeSlashName, LocalModuleId>\n\n\tgetPersistedModuleByLocalId(id: LocalModuleId): PersistedModule | undefined {\n\t\treturn this.persistedModules.get(id)\n\t}\n\n\tgetModuleWithTypeSlashName(typeSlashName: string): PersistedModule | undefined {\n\t\tconst localId = this.persistedLocalIdsByTypeSlashName.get(typeSlashName)\n\t\tif (!localId) return\n\t\treturn this.persistedModules.get(localId)\n\t}\n}\n", "import type { ToasterAddAction } from \"@framerjs/fresco\"\nimport { tabularNumbers } from \"@framerjs/fresco\"\nimport type { BaseEngine } from \"document/base-engine/BaseEngine.ts\"\nimport pluralize from \"pluralize\"\nimport {\n\ttype AssetUploadResult,\n\ttype ImageUploadResult,\n\tisImageUploadResult,\n} from \"../pages/project/lib/UploadService.ts\"\nimport { BatchAssetUploader } from \"./BatchAssetUploader.ts\"\nimport { mimeTypes as supportedImageMimeTypes } from \"./images/supportedFormats.ts\"\nimport { toast } from \"./toaster.ts\"\n\n/**\n * Uploads all images from a list of files using the BatchAssetUploader. Progress is displayed using\n * a single toast to avoid cluttering the UI.\n */\nexport async function batchUploadImages(\n\tengine: BaseEngine,\n\tfiles: FileList | File[],\n\tmaxUploads = Infinity,\n\tuploader?: BatchAssetUploader,\n): Promise<ImageUploadResult[]> {\n\tuploader ??= new BatchAssetUploader(engine, { silent: true })\n\n\tconst unsupportedFiles: File[] = []\n\tconst overMaxUploads: File[] = []\n\tconst runningTasks: Promise<AssetUploadResult>[] = []\n\tfor (const file of files) {\n\t\tif (runningTasks.length >= maxUploads) {\n\t\t\toverMaxUploads.push(file)\n\t\t\tcontinue\n\t\t}\n\t\tif (!supportedImageMimeTypes.includes(file.type)) {\n\t\t\tunsupportedFiles.push(file)\n\t\t\tcontinue\n\t\t}\n\n\t\tconst task = uploader.add(file)\n\t\trunningTasks.push(task)\n\t}\n\n\tif (unsupportedFiles.length > 0) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tkey: \"importUploadImagesUnsupported\",\n\t\t\tvariant: \"warning\",\n\t\t\tprimaryText: <span className={tabularNumbers}>Skipped {unsupportedFiles.length}</span>,\n\t\t\tsecondaryText: \"unsupported images.\",\n\t\t\tduration: 10000,\n\t\t})\n\t}\n\tif (overMaxUploads.length > 0) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tkey: \"importUploadImagesSkipped\",\n\t\t\tvariant: \"warning\",\n\t\t\tprimaryText: <span className={tabularNumbers}>Skipped {overMaxUploads.length}</span>,\n\t\t\tsecondaryText: \"images over field limit.\",\n\t\t\tduration: 10000,\n\t\t})\n\t}\n\n\tcreateBatchProgressToast(uploader, runningTasks).catch(() => {})\n\n\tconst results = await Promise.all(runningTasks)\n\treturn results.filter(isImageUploadResult)\n}\n\n/**\n * Creates and manages a single progress toast for a batch upload.\n */\nexport async function createBatchProgressToast(\n\tuploader: BatchAssetUploader,\n\trunningTasks: Promise<AssetUploadResult>[],\n) {\n\tconst key = \"uploadEmbeddedImagesByUrl\"\n\tconst action: Omit<ToasterAddAction, \"text\"> = {\n\t\ttype: \"add\",\n\t\tkey,\n\t\tvariant: \"progress\",\n\t\ticon: \"image\",\n\t\tduration: Infinity,\n\t\tshowCloseButton: \"never\",\n\t\t// TODO: Allow aborting?\n\t}\n\tfor await (const { completed, started } of uploader.statusUpdates()) {\n\t\ttoast({\n\t\t\t...action,\n\t\t\ttext: (\n\t\t\t\t<span className=\"toast-progress-row\">\n\t\t\t\t\t<span className=\"toast-progress-label toast-emphasis\">Adding images\u2026</span>\n\t\t\t\t\t<span className={`toast-progress-value ${tabularNumbers}`}>\n\t\t\t\t\t\t{completed}/{started}\n\t\t\t\t\t</span>\n\t\t\t\t</span>\n\t\t\t),\n\t\t})\n\t}\n\n\t// Wait for tasks to complete but do not throw here if any fail, we handle the failed uploads\n\t// in the next step.\n\tawait Promise.allSettled(runningTasks)\n\n\tconst { failed: failedUploads } = uploader.status\n\tif (failedUploads > 0) {\n\t\ttoast({\n\t\t\ttype: \"add\",\n\t\t\tkey: \"importUploadImagesFailed\",\n\t\t\tvariant: \"warning\",\n\t\t\tprimaryText: \"Failed to upload\",\n\t\t\tsecondaryText: (\n\t\t\t\t<span className={tabularNumbers}>\n\t\t\t\t\t{failedUploads} {pluralize(\"image\", failedUploads)}.\n\t\t\t\t</span>\n\t\t\t),\n\t\t\tduration: 5000,\n\t\t})\n\t}\n\n\t// Clear progress toast\n\ttoast({ type: \"remove\", key })\n}\n", "import { parseModuleIdentifier } from \"@framerjs/shared\"\nimport type { LocalModuleExportIdentifierString } from \"@framerjs/shared/src/moduleIdentifiers.ts\"\nimport type { CanvasTree, NodeID } from \"document/models/CanvasTree/index.ts\"\nimport { isCollectionItemNode, isCollectionNode } from \"document/models/CanvasTree/nodes/utils/nodeCheck.ts\"\nimport type { CollectionControlDescription } from \"document/models/controlProps/CollectionControlDescription.ts\"\nimport type { CollectionControlProp } from \"document/models/controlProps/CollectionControlProp.ts\"\nimport { ControlType } from \"library/render/types/PropertyControls.ts\"\nimport { isString } from \"utils/typeChecks.ts\"\n\n/**\n * Validates the single/multi-collection reference values of this prop to ensure they exist and haven't been deleted.\n * Any deleted values are omitted for the response. Does nothing if the control prop is not a reference.\n */\nexport function validateControlPropReference(\n\ttree: CanvasTree,\n\tcontrol: CollectionControlDescription,\n\tcontrolProp: CollectionControlProp | undefined,\n): CollectionControlProp | undefined {\n\tconst collectionIdentifier = getReferencedCollectionIdentifierFromControl(control)\n\tif (!controlProp || !collectionIdentifier) return controlProp\n\n\tif (\n\t\tcontrolProp.type === ControlType.CollectionReference &&\n\t\tisString(controlProp.value) &&\n\t\t!collectionHasItemWithId(tree, collectionIdentifier, controlProp.value)\n\t) {\n\t\t// Referenced item was probably deleted. Pretend the prop has no value.\n\t\treturn {\n\t\t\t...controlProp,\n\t\t\tvalue: undefined,\n\t\t}\n\t}\n\n\tif (controlProp.type === ControlType.MultiCollectionReference && Array.isArray(controlProp.value)) {\n\t\treturn {\n\t\t\t...controlProp,\n\t\t\t// Filter out values that were deleted\n\t\t\tvalue: controlProp.value.filter(value => collectionHasItemWithId(tree, collectionIdentifier, value)),\n\t\t}\n\t}\n\n\treturn controlProp\n}\n\nexport function getReferencedCollectionIdentifierFromControl(\n\tcontrol: CollectionControlDescription,\n): LocalModuleExportIdentifierString | null {\n\tif (control.type !== ControlType.CollectionReference && control.type !== ControlType.MultiCollectionReference) {\n\t\treturn null\n\t}\n\n\tconst collectionIdentifier = parseModuleIdentifier(control.dataIdentifier)\n\tif (collectionIdentifier?.kind !== \"localModuleExport\") return null\n\n\treturn collectionIdentifier.value\n}\n\nexport function collectionHasItemWithId(\n\ttree: CanvasTree,\n\tcollectionIdentifier: LocalModuleExportIdentifierString,\n\tid: NodeID,\n) {\n\tconst referencedItem = tree.getNodeWithTrait(id, isCollectionItemNode)\n\tconst parent = referencedItem && tree.getNodeParent(referencedItem)\n\treturn isCollectionNode(parent) && parent.instanceIdentifier === collectionIdentifier\n}\n", "import { assertNever } from \"@framerjs/shared\"\nimport {\n\tcanBePositionAbsolute,\n\tcanBePositionFixed,\n\tcanBePositionSticky,\n\tisPositionAbsolute,\n\tisPositionFixed,\n\tisPositionSticky,\n} from \"document/models/CanvasTree/traits/utils/positionTypeHelpers.ts\"\nimport type { CanvasTree } from \"../../CanvasTree.ts\"\nimport type { CanvasNode } from \"../../nodes/CanvasNode.ts\"\nimport { isSlotPropertyNode } from \"../../nodes/utils/nodeCheck.ts\"\nimport { hasAnyLayout } from \"../WithLayout.ts\"\nimport type { WithPositionType } from \"../WithPositionType.ts\"\nimport type { ReducedRecord } from \"./Reduced.ts\"\nimport { reduceProperty } from \"./reduceProperty.ts\"\n\nexport type PositionType = \"fixed\" | \"sticky\" | \"absolute\" | \"relative\"\n\n/**\n * Determine if a layer's position is parent relative.\n */\nexport function isPositionRelativeToParent(parent: CanvasNode, position: PositionType = \"relative\"): boolean {\n\tif (isSlotPropertyNode(parent)) return true\n\n\t// A layer not in a layout parent cannot be positioned relatively to the\n\t// parent.\n\tif (!hasAnyLayout(parent)) return false\n\n\tswitch (position) {\n\t\tcase \"relative\":\n\t\tcase \"sticky\":\n\t\t\treturn true\n\t\tcase \"absolute\":\n\t\tcase \"fixed\":\n\t\t\treturn false\n\t\tdefault:\n\t\t\tassertNever(position)\n\t}\n}\n\nexport interface ReducedPositionType extends ReducedRecord<\n\tOmit<WithPositionType, \"position\" | \"positionFixedEnabled\" | \"positionStickyEnabled\">\n> {\n\tpositionTypes: Set<PositionType>\n\tonlyNodesWithPositionFixed?: boolean\n}\n\nexport function reducePositionType(tree: CanvasTree, node: CanvasNode, result: ReducedPositionType) {\n\tif (!canBePositionFixed(tree, node)) {\n\t\tresult.onlyNodesWithPositionFixed = false\n\t}\n\n\tif (node.__unsafeIsSlotPropertyChildNode(tree)) {\n\t\tresult.positionTypes.add(\"relative\")\n\t\treturn\n\t}\n\n\tif (canBePositionFixed(tree, node) && isPositionFixed(node)) {\n\t\tresult.positionTypes.add(\"fixed\")\n\t\treturn\n\t}\n\n\tif (canBePositionSticky(node) && isPositionSticky(node)) {\n\t\tresult.positionTypes.add(\"sticky\")\n\t\treduceProperty(\"positionStickyTop\", result, node)\n\t\treduceProperty(\"positionStickyRight\", result, node)\n\t\treduceProperty(\"positionStickyBottom\", result, node)\n\t\treduceProperty(\"positionStickyLeft\", result, node)\n\t\treturn\n\t}\n\n\tif (canBePositionAbsolute(node) && isPositionAbsolute(node)) {\n\t\tresult.positionTypes.add(\"absolute\")\n\t\treturn\n\t}\n\n\tif (node.cache.parentDirected) {\n\t\tresult.positionTypes.add(\"relative\")\n\t\treturn\n\t}\n\n\tresult.positionTypes.add(\"absolute\")\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,YAAQ,yCAAyC,YAAU;AACzD,aAAO,OAAO,QAAQ,gBAAgB,EAAE,EAAE,QAAQ,gBAAgB,EAAE;AAAA,IACtE;AAEA,YAAQ,+BAA+B,YAAU;AAC/C,aAAO,OAAO,QAAQ,gBAAgB,EAAE;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O,6BAA6B;AAAA,EACrC;AAEA,MAAI,KAAK,gCAAgC,IAAI,GAAG;AAC/C,WAAO,cAAc,IAAI,UAAU;AACnC;AAAA,EACD;AAEA,MAAI,mBAAmB,MAAM,IAAI,KAAK,gBAAgB,IAAI,GAAG;AAC5D,WAAO,cAAc,IAAI,OAAO;AAChC;AAAA,EACD;AAEA,MAAI,oBAAoB,IAAI,KAAK,iBAAiB,IAAI,GAAG;AACxD,WAAO,cAAc,IAAI,QAAQ;AACjC,mBAAe,qBAAqB,QAAQ,IAAI;AAChD,mBAAe,uBAAuB,QAAQ,IAAI;AAClD,mBAAe,wBAAwB,QAAQ,IAAI;AACnD,mBAAe,sBAAsB,QAAQ,IAAI;AACjD;AAAA,EACD;AAEA,MAAI,sBAAsB,IAAI,KAAK,mBAAmB,IAAI,GAAG;AAC5D,WAAO,cAAc,IAAI,UAAU;AACnC;AAAA,EACD;AAEA,MAAI,KAAK,MAAM,gBAAgB;AAC9B,WAAO,cAAc,IAAI,UAAU;AACnC;AAAA,EACD;AAEA,SAAO,cAAc,IAAI,UAAU;AACpC;",
  "names": ["parse", "err", "A", "E", "K", "Q", "B", "g", "I", "w", "o", "D", "C", "moduleSpecifier", "replacementSpecifier", "MIMEType", "log", "log", "err", "typeSlashName", "isUpToDate", "data", "pluralize"]
}
