tinacms 3.0.2 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,7 @@
1
1
  import type { Cache } from './index';
2
- export declare const makeCacheDir: (dir: string, fs: any, path: any, os: any) => Promise<string>;
3
- export declare const NodeCache: (dir: string) => Promise<Cache>;
2
+ type FsModule = typeof import('node:fs');
3
+ type PathModule = typeof import('node:path');
4
+ type OsModule = typeof import('node:os');
5
+ export declare const makeCacheDir: (dir: string, fsArg: FsModule, pathArg: PathModule, osArg: OsModule) => string | null;
6
+ export declare const NodeCache: (dir: string) => Promise<Cache | null>;
7
+ export {};
package/dist/client.js CHANGED
@@ -1,11 +1,123 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
5
  };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/cache/node-cache.ts
12
+ var node_cache_exports = {};
13
+ __export(node_cache_exports, {
14
+ NodeCache: () => NodeCache,
15
+ makeCacheDir: () => makeCacheDir
16
+ });
17
+ var resolveModule, getRootPath, makeCacheDir, NodeCache;
18
+ var init_node_cache = __esm({
19
+ "src/cache/node-cache.ts"() {
20
+ resolveModule = (mod) => {
21
+ if (mod && typeof mod === "object" && "default" in mod && mod.default) {
22
+ return mod.default;
23
+ }
24
+ return mod;
25
+ };
26
+ getRootPath = (pathParts, pathArg) => {
27
+ if (pathParts.length === 0) return null;
28
+ const isWindows = pathArg.sep === "\\";
29
+ const root = pathParts[0];
30
+ return isWindows ? `${root}${pathArg.sep}` : `${pathArg.sep}${root}`;
31
+ };
32
+ makeCacheDir = (dir, fsArg, pathArg, osArg) => {
33
+ const normalizedDir = pathArg.normalize(dir);
34
+ const pathParts = normalizedDir.split(pathArg.sep).filter(Boolean);
35
+ const cacheHash = pathParts[pathParts.length - 1];
36
+ const rootPath = getRootPath(pathParts, pathArg);
37
+ const rootExists = rootPath && fsArg.existsSync(rootPath);
38
+ const cacheDir = rootExists ? normalizedDir : pathArg.join(osArg.tmpdir(), cacheHash);
39
+ try {
40
+ fsArg.mkdirSync(cacheDir, { recursive: true });
41
+ } catch (error) {
42
+ console.warn(
43
+ `Warning: Failed to create cache directory: ${error.message}. Caching will be disabled.`
44
+ );
45
+ return null;
46
+ }
47
+ return cacheDir;
48
+ };
49
+ NodeCache = async (dir) => {
50
+ try {
51
+ const [fsModule, pathModule, osModule, cryptoModule] = await Promise.all([
52
+ import("node:fs"),
53
+ import("node:path"),
54
+ import("node:os"),
55
+ import("node:crypto")
56
+ ]);
57
+ const fs = resolveModule(fsModule);
58
+ const path = resolveModule(pathModule);
59
+ const os = resolveModule(osModule);
60
+ const crypto = resolveModule(cryptoModule);
61
+ if (typeof path?.join !== "function") {
62
+ console.warn(
63
+ "Warning: Node.js path module not available. Caching will be disabled."
64
+ );
65
+ return null;
66
+ }
67
+ const cacheDir = makeCacheDir(dir, fs, path, os);
68
+ if (cacheDir === null) {
69
+ return null;
70
+ }
71
+ return {
72
+ makeKey: (key) => {
73
+ const input = key && key instanceof Object ? JSON.stringify(key) : key || "";
74
+ return crypto.createHash("sha256").update(input).digest("hex");
75
+ },
76
+ get: async (key) => {
77
+ let readValue;
78
+ const cacheFilename = path.join(cacheDir, key);
79
+ try {
80
+ const data = await fs.promises.readFile(cacheFilename, "utf-8");
81
+ readValue = JSON.parse(data);
82
+ } catch (e) {
83
+ if (e.code !== "ENOENT") {
84
+ console.warn(
85
+ `Warning: Failed to read cache file ${cacheFilename}: ${e.message}`
86
+ );
87
+ }
88
+ }
89
+ return readValue;
90
+ },
91
+ set: async (key, value) => {
92
+ const cacheFilename = path.join(cacheDir, key);
93
+ try {
94
+ await fs.promises.writeFile(cacheFilename, JSON.stringify(value), {
95
+ encoding: "utf-8",
96
+ flag: "wx"
97
+ });
98
+ } catch (e) {
99
+ if (e.code !== "EEXIST") {
100
+ console.warn(
101
+ `Warning: Failed to write cache file ${cacheFilename}: ${e.message}`
102
+ );
103
+ }
104
+ }
105
+ }
106
+ };
107
+ } catch (e) {
108
+ console.warn(
109
+ "Warning: Failed to initialize cache. Caching will be disabled.",
110
+ e.message
111
+ );
112
+ return null;
113
+ }
114
+ };
115
+ }
116
+ });
117
+
118
+ // src/unifiedClient/index.ts
7
119
  import AsyncLock from "async-lock";
8
- const TINA_HOST = "content.tinajs.io";
120
+ var TINA_HOST = "content.tinajs.io";
9
121
  function replaceGithubPathSplit(url, replacement) {
10
122
  const parts = url.split("github/");
11
123
  if (parts.length > 1 && replacement) {
@@ -14,7 +126,15 @@ function replaceGithubPathSplit(url, replacement) {
14
126
  return url;
15
127
  }
16
128
  }
17
- class TinaClient {
129
+ var TinaClient = class {
130
+ apiUrl;
131
+ readonlyToken;
132
+ queries;
133
+ errorPolicy;
134
+ initialized = false;
135
+ cacheLock;
136
+ cacheDir;
137
+ cache;
18
138
  constructor({
19
139
  token,
20
140
  url,
@@ -22,16 +142,8 @@ class TinaClient {
22
142
  errorPolicy,
23
143
  cacheDir
24
144
  }) {
25
- __publicField(this, "apiUrl");
26
- __publicField(this, "readonlyToken");
27
- __publicField(this, "queries");
28
- __publicField(this, "errorPolicy");
29
- __publicField(this, "initialized", false);
30
- __publicField(this, "cacheLock");
31
- __publicField(this, "cacheDir");
32
- __publicField(this, "cache");
33
145
  this.apiUrl = url;
34
- this.readonlyToken = token == null ? void 0 : token.trim();
146
+ this.readonlyToken = token?.trim();
35
147
  this.queries = queries(this);
36
148
  this.errorPolicy = errorPolicy || "throw";
37
149
  this.cacheDir = cacheDir || "";
@@ -41,10 +153,12 @@ class TinaClient {
41
153
  return;
42
154
  }
43
155
  try {
44
- if (this.cacheDir && typeof window === "undefined" && typeof require !== "undefined") {
45
- const { NodeCache } = await import("./node-cache-c9558e1e.js");
46
- this.cache = await NodeCache(this.cacheDir);
47
- this.cacheLock = new AsyncLock();
156
+ if (this.cacheDir && typeof window === "undefined") {
157
+ const { NodeCache: NodeCache2 } = await Promise.resolve().then(() => (init_node_cache(), node_cache_exports));
158
+ this.cache = await NodeCache2(this.cacheDir);
159
+ if (this.cache) {
160
+ this.cacheLock = new AsyncLock();
161
+ }
48
162
  }
49
163
  } catch (e) {
50
164
  console.error(e);
@@ -52,7 +166,6 @@ class TinaClient {
52
166
  this.initialized = true;
53
167
  }
54
168
  async request({ errorPolicy, ...args }, options) {
55
- var _a;
56
169
  await this.init();
57
170
  const errorPolicyDefined = errorPolicy || this.errorPolicy;
58
171
  const headers = new Headers();
@@ -60,17 +173,17 @@ class TinaClient {
60
173
  headers.append("X-API-KEY", this.readonlyToken);
61
174
  }
62
175
  headers.append("Content-Type", "application/json");
63
- if (options == null ? void 0 : options.fetchOptions) {
64
- if ((_a = options == null ? void 0 : options.fetchOptions) == null ? void 0 : _a.headers) {
176
+ if (options?.fetchOptions) {
177
+ if (options?.fetchOptions?.headers) {
65
178
  Object.entries(options.fetchOptions.headers).forEach(([key2, value]) => {
66
179
  headers.append(key2, value);
67
180
  });
68
181
  }
69
182
  }
70
- const { headers: _, ...providedFetchOptions } = (options == null ? void 0 : options.fetchOptions) || {};
183
+ const { headers: _, ...providedFetchOptions } = options?.fetchOptions || {};
71
184
  const bodyString = JSON.stringify({
72
185
  query: args.query,
73
- variables: (args == null ? void 0 : args.variables) || {}
186
+ variables: args?.variables || {}
74
187
  });
75
188
  const optionsObject = {
76
189
  method: "POST",
@@ -80,7 +193,7 @@ class TinaClient {
80
193
  ...providedFetchOptions
81
194
  };
82
195
  const draftBranch = headers.get("x-branch");
83
- const url = replaceGithubPathSplit((args == null ? void 0 : args.url) || this.apiUrl, draftBranch);
196
+ const url = replaceGithubPathSplit(args?.url || this.apiUrl, draftBranch);
84
197
  let key = "";
85
198
  let result;
86
199
  if (this.cache) {
@@ -107,7 +220,7 @@ class TinaClient {
107
220
  }
108
221
  return result;
109
222
  }
110
- }
223
+ };
111
224
  async function requestFromServer(url, query, optionsObject, errorPolicyDefined) {
112
225
  const res = await fetch(url, optionsObject);
113
226
  if (!res.ok) {
@@ -128,8 +241,8 @@ async function requestFromServer(url, query, optionsObject, errorPolicyDefined)
128
241
  );
129
242
  }
130
243
  const result = {
131
- data: json == null ? void 0 : json.data,
132
- errors: (json == null ? void 0 : json.errors) || null,
244
+ data: json?.data,
245
+ errors: json?.errors || null,
133
246
  query
134
247
  };
135
248
  return result;
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { isHotkey } from "is-hotkey";
15
15
  import clsx$1, { clsx } from "clsx";
16
16
  import { Slot } from "@radix-ui/react-slot";
17
17
  import { isLangSupported, formatCodeBlock, insertEmptyCodeBlock, unwrapCodeBlock, isCodeBlockEmpty, isSelectionAtCodeBlockStart } from "@udecode/plate-code-block";
18
- import { X, Search, ChevronDown, Check, AlertTriangle, BracesIcon, Plus, AlignCenter as AlignCenter$1, AlignJustify, AlignLeft as AlignLeft$1, AlignRight as AlignRight$1, PaintBucket, Quote, ChevronRight, ChevronsUpDown, FileCode, Baseline, RectangleVertical, Combine, Ungroup, MessageSquare, MessageSquarePlus, Trash, GripVertical, Edit2, Smile, ExternalLink, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, Indent, Keyboard, WrapText, Minus, MoreHorizontal, Outdent, Pilcrow, RotateCcw, RectangleHorizontal, Settings, Strikethrough, Subscript, Superscript, Table, Text as Text$2, Underline, Link2Off, Eye, SeparatorHorizontal, Moon, SunMedium, Twitter, PaintBucketIcon, CombineIcon, SquareSplitHorizontalIcon, Grid2X2Icon, Trash2Icon, ArrowUp, ArrowDown, XIcon, ArrowLeft, ArrowRight, EraserIcon, ChevronDownIcon as ChevronDownIcon$1, ChevronUp, Clock, CalendarCheck, Calendar as Calendar$1, CalendarDays, RotateCw, ChevronLeft, LoaderCircle, TriangleAlert, EllipsisVertical, GitBranchIcon, List as List$1, ListOrdered, Grid3x3Icon, CircleX, Link, Unlink } from "lucide-react";
18
+ import { X, Search, ChevronDown, Check, AlertTriangle, BracesIcon, Plus, AlignCenter as AlignCenter$1, AlignJustify, AlignLeft as AlignLeft$1, AlignRight as AlignRight$1, PaintBucket, Quote, ChevronRight, ChevronsUpDown, FileCode, Baseline, RectangleVertical, Combine, Ungroup, MessageSquare, MessageSquarePlus, Trash, GripVertical, Edit2, Smile, ExternalLink, Heading1, Heading2, Heading3, Heading4, Heading5, Heading6, Indent, Keyboard, WrapText, Minus, MoreHorizontal, Outdent, Pilcrow, RotateCcw, RectangleHorizontal, Settings, Strikethrough, Subscript, Superscript, Table, Text as Text$2, Underline, Link2Off, Eye, SeparatorHorizontal, Moon, SunMedium, Twitter, PaintBucketIcon, CombineIcon, SquareSplitHorizontalIcon, Grid2X2Icon, Trash2Icon, ArrowUp, ArrowDown, XIcon, ArrowLeft, ArrowRight, EraserIcon, ChevronDownIcon as ChevronDownIcon$1, ChevronUp, Clock, CalendarCheck, Calendar as Calendar$1, CalendarDays, RotateCw, ChevronLeft, LoaderCircle, TriangleAlert, History, EllipsisVertical, GitBranchIcon, List as List$1, ListOrdered, Grid3x3Icon, CircleX, Link, Unlink } from "lucide-react";
19
19
  import mermaid from "mermaid";
20
20
  import { cva } from "class-variance-authority";
21
21
  import { Command as Command$2 } from "cmdk";
@@ -38721,9 +38721,6 @@ function BiListUl(props) {
38721
38721
  function BiLockAlt(props) {
38722
38722
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M12 2C9.243 2 7 4.243 7 7v3H6c-1.103 0-2 .897-2 2v8c0 1.103.897 2 2 2h12c1.103 0 2-.897 2-2v-8c0-1.103-.897-2-2-2h-1V7c0-2.757-2.243-5-5-5zm6 10 .002 8H6v-8h12zm-9-2V7c0-1.654 1.346-3 3-3s3 1.346 3 3v3H9z" }, "child": [] }] })(props);
38723
38723
  }
38724
- function BiLock(props) {
38725
- return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M12 2C9.243 2 7 4.243 7 7v2H6c-1.103 0-2 .897-2 2v9c0 1.103.897 2 2 2h12c1.103 0 2-.897 2-2v-9c0-1.103-.897-2-2-2h-1V7c0-2.757-2.243-5-5-5zM9 7c0-1.654 1.346-3 3-3s3 1.346 3 3v2H9V7zm9.002 13H13v-2.278c.595-.347 1-.985 1-1.722 0-1.103-.897-2-2-2s-2 .897-2 2c0 .736.405 1.375 1 1.722V20H6v-9h12l.002 9z" }, "child": [] }] })(props);
38726
- }
38727
38724
  function BiMenu(props) {
38728
38725
  return GenIcon({ "tag": "svg", "attr": { "viewBox": "0 0 24 24" }, "child": [{ "tag": "path", "attr": { "d": "M4 6h16v2H4zm0 5h16v2H4zm0 5h16v2H4z" }, "child": [] }] })(props);
38729
38726
  }
@@ -43971,7 +43968,7 @@ const Badge = ({
43971
43968
  children
43972
43969
  );
43973
43970
  };
43974
- const tableHeadingStyle = "px-3 py-3 text-left text-xs font-bold text-gray-700 tracking-wider";
43971
+ const tableHeadingStyle = "px-3 py-3 text-left text-xs font-bold text-gray-700 tracking-wider sticky top-0 bg-gray-100 z-20 border-b-2 border-gray-200 ";
43975
43972
  function formatBranchName(str) {
43976
43973
  const pattern = /[^/\w-]+/g;
43977
43974
  const formattedStr = str.replace(pattern, "-");
@@ -44207,6 +44204,9 @@ const BranchSelector = ({
44207
44204
  const [search, setSearch] = React.useState("");
44208
44205
  const [filter2, setFilter] = React.useState("content");
44209
44206
  const [sortValue, setSortValue] = React.useState("default");
44207
+ const [selectedBranch, setSelectedBranch] = React.useState(
44208
+ null
44209
+ );
44210
44210
  const cms = useCMS$1();
44211
44211
  const filteredBranchList = getFilteredBranchList(
44212
44212
  branchList,
@@ -44266,7 +44266,19 @@ const BranchSelector = ({
44266
44266
  }
44267
44267
  ]
44268
44268
  }
44269
- ))), filteredBranchList.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "block relative text-gray-300 italic py-1" }, "No branches to display"), filteredBranchList.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "min-w-[192px] max-h-[24rem] overflow-y-auto w-full h-full rounded-lg shadow-inner bg-white border border-gray-200" }, /* @__PURE__ */ React.createElement("table", { className: "w-full" }, /* @__PURE__ */ React.createElement("thead", { className: "bg-gray-100 border-b-2 border-gray-200" }, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", { className: tableHeadingStyle }, "Branch Name"), /* @__PURE__ */ React.createElement("th", { className: tableHeadingStyle }, "Last Updated"), /* @__PURE__ */ React.createElement("th", null), /* @__PURE__ */ React.createElement("th", null))), /* @__PURE__ */ React.createElement("tbody", null, filteredBranchList.map((branch) => /* @__PURE__ */ React.createElement(
44269
+ ))), filteredBranchList.length === 0 && /* @__PURE__ */ React.createElement("div", { className: "block relative text-gray-300 italic py-1" }, "No branches to display"), filteredBranchList.length > 0 && /* @__PURE__ */ React.createElement(TooltipProvider$1, null, /* @__PURE__ */ React.createElement("div", { className: "rounded-lg border border-gray-200 overflow-hidden" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-[192px] max-h-[24rem] overflow-y-auto w-full h-full shadow-inner bg-white" }, /* @__PURE__ */ React.createElement("table", { className: "w-full table-auto max-h-[24rem]" }, /* @__PURE__ */ React.createElement("thead", { className: "sticky top-0 z-20 bg-gray-100 border-b-2 border-gray-200" }, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", { className: `${tableHeadingStyle} w-auto` }, "Branch Name"), /* @__PURE__ */ React.createElement(
44270
+ "th",
44271
+ {
44272
+ className: `${tableHeadingStyle} w-0 whitespace-nowrap text-left`
44273
+ },
44274
+ "Last Updated"
44275
+ ), /* @__PURE__ */ React.createElement(
44276
+ "th",
44277
+ {
44278
+ className: `${tableHeadingStyle} w-0 whitespace-nowrap text-left`
44279
+ },
44280
+ "Pull Request"
44281
+ ))), /* @__PURE__ */ React.createElement("tbody", null, filteredBranchList.map((branch) => /* @__PURE__ */ React.createElement(
44270
44282
  BranchItem,
44271
44283
  {
44272
44284
  key: branch.name,
@@ -44275,9 +44287,24 @@ const BranchSelector = ({
44275
44287
  onChange,
44276
44288
  refreshBranchList,
44277
44289
  previewFunction,
44278
- cms
44290
+ cms,
44291
+ selectedBranch,
44292
+ onSelectBranch: setSelectedBranch
44279
44293
  }
44280
- ))))));
44294
+ ))))))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end" }, /* @__PURE__ */ React.createElement(
44295
+ Button$2,
44296
+ {
44297
+ variant: "primary",
44298
+ onClick: () => {
44299
+ onChange(selectedBranch);
44300
+ },
44301
+ disabled: !selectedBranch || selectedBranch === currentBranch
44302
+ },
44303
+ "Open branch in editor"
44304
+ )));
44305
+ };
44306
+ const extractPullRequestId = (url) => {
44307
+ return url.split("/").pop() || "";
44281
44308
  };
44282
44309
  const BranchItem = ({
44283
44310
  branch,
@@ -44285,9 +44312,11 @@ const BranchItem = ({
44285
44312
  onChange,
44286
44313
  refreshBranchList,
44287
44314
  previewFunction,
44288
- cms
44315
+ cms,
44316
+ selectedBranch,
44317
+ onSelectBranch
44289
44318
  }) => {
44290
- var _a2, _b;
44319
+ var _a2;
44291
44320
  const [creatingPR, setCreatingPR] = React.useState(false);
44292
44321
  const handleCreatePullRequest = async () => {
44293
44322
  if (creatingPR)
@@ -44311,62 +44340,63 @@ const BranchItem = ({
44311
44340
  }
44312
44341
  };
44313
44342
  const isCurrentBranch = branch.name === currentBranch;
44343
+ const isSelected2 = selectedBranch === branch.name;
44314
44344
  const indexingStatus = (_a2 = branch == null ? void 0 : branch.indexStatus) == null ? void 0 : _a2.status;
44345
+ const handleRowClick = () => {
44346
+ if (indexingStatus === "complete" && !isCurrentBranch) {
44347
+ onSelectBranch(isSelected2 ? null : branch.name);
44348
+ }
44349
+ };
44315
44350
  return /* @__PURE__ */ React.createElement(
44316
44351
  "tr",
44317
44352
  {
44318
- className: `text-base border-l-0 border-t-0 border-r-0 outline-none transition-all ease-out duration-150 ${indexingStatus !== "complete" ? "bg-gray-50 text-gray-400" : isCurrentBranch ? "bg-blue-50 text-blue-800 border-b-0" : "border-b-2 border-gray-50"}`
44353
+ onClick: handleRowClick,
44354
+ className: `text-base border-l-0 transition-colors border-t-0 border-r-0 outline-none transition-all ease-out duration-150 ${indexingStatus !== "complete" ? "bg-gray-50 text-gray-400" : isCurrentBranch ? "border-b-2 border-gray-50" : isSelected2 ? "bg-blue-100 text-blue-900 border-b-2 border-blue-50 cursor-pointer" : "border-b-2 border-gray-50 hover:bg-gray-50/50 cursor-pointer"}`
44319
44355
  },
44320
- /* @__PURE__ */ React.createElement("td", { className: "pl-3 pr-3 py-1.5 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1" }, branch.protected && /* @__PURE__ */ React.createElement(BiLock, { className: "w-5 h-auto opacity-70 text-blue-500 flex-shrink-0" }), /* @__PURE__ */ React.createElement("span", { className: "text-sm leading-tight truncate" }, branch.name)), indexingStatus !== "complete" && /* @__PURE__ */ React.createElement("div", { className: "w-fit mt-1" }, /* @__PURE__ */ React.createElement(IndexStatus, { indexingStatus: branch.indexStatus.status })))),
44356
+ /* @__PURE__ */ React.createElement(
44357
+ "td",
44358
+ {
44359
+ className: `pl-3 pr-3 max-w-xs ${isCurrentBranch ? "py-2.5" : "py-1.5"}`
44360
+ },
44361
+ /* @__PURE__ */ React.createElement("div", { className: "flex flex-col" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 min-w-0" }, branch.protected ? /* @__PURE__ */ React.createElement(BiLockAlt, { className: "w-4 h-auto opacity-70 text-blue-500 flex-shrink-0" }) : /* @__PURE__ */ React.createElement(BiGitBranch, { className: "w-4 h-auto opacity-70 text-gray-600 flex-shrink-0" }), /* @__PURE__ */ React.createElement(Tooltip$1, { delayDuration: 300 }, /* @__PURE__ */ React.createElement(TooltipTrigger$1, { asChild: true }, /* @__PURE__ */ React.createElement("span", { className: "text-sm leading-tight truncate block min-w-0 cursor-default" }, branch.name)), /* @__PURE__ */ React.createElement(TooltipPortal, null, /* @__PURE__ */ React.createElement(TooltipContent$1, { side: "top" }, branch.name)))), isCurrentBranch && /* @__PURE__ */ React.createElement("div", { className: "w-fit mt-1" }, /* @__PURE__ */ React.createElement(
44362
+ Badge,
44363
+ {
44364
+ calloutStyle: "info",
44365
+ className: "w-fit flex-shrink-0",
44366
+ displayIcon: false
44367
+ },
44368
+ /* @__PURE__ */ React.createElement(BiPencil, { className: "w-3 h-auto inline-block mr-1" }),
44369
+ "Currently editing"
44370
+ )), indexingStatus !== "complete" && /* @__PURE__ */ React.createElement("div", { className: "w-fit mt-1" }, /* @__PURE__ */ React.createElement(IndexStatus, { indexingStatus: branch.indexStatus.status })))
44371
+ ),
44321
44372
  /* @__PURE__ */ React.createElement("td", { className: "px-3 py-1.5 min-w-0" }, creatingPR ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-bold text-blue-600" }, "Creating PR"), /* @__PURE__ */ React.createElement("span", { className: "text-sm leading-tight text-blue-500" }, "Please wait...")), /* @__PURE__ */ React.createElement(FaSpinner, { className: "w-3 h-auto animate-spin text-blue-500" })) : /* @__PURE__ */ React.createElement("span", { className: "text-sm leading-tight whitespace-nowrap" }, formatDistanceToNow$1(new Date(branch.indexStatus.timestamp), {
44322
44373
  addSuffix: true
44323
44374
  }))),
44324
- /* @__PURE__ */ React.createElement("td", { className: "px-3 py-1.5 text-left" }, indexingStatus === "complete" && !isCurrentBranch && /* @__PURE__ */ React.createElement(
44375
+ /* @__PURE__ */ React.createElement("td", { className: "px-3 py-1.5 flex", onClick: (e3) => e3.stopPropagation() }, branch.githubPullRequestUrl ? /* @__PURE__ */ React.createElement(
44325
44376
  Button$2,
44326
44377
  {
44327
44378
  variant: "white",
44328
44379
  size: "custom",
44329
44380
  onClick: () => {
44330
- onChange(branch.name);
44381
+ window.open(branch.githubPullRequestUrl, "_blank");
44331
44382
  },
44332
- className: "cursor-pointer text-sm h-9 px-4 flex items-center gap-1"
44383
+ className: "cursor-pointer h-9 px-2 flex items-center gap-1",
44384
+ title: "Open Git Pull Request"
44333
44385
  },
44334
- /* @__PURE__ */ React.createElement(BiPencil, { className: "h-4 w-auto text-blue-500 opacity-70 -mt-px" }),
44335
- " ",
44336
- "Select"
44337
- ), indexingStatus === "complete" && isCurrentBranch && /* @__PURE__ */ React.createElement(Badge, { calloutStyle: "info", className: "w-fit", displayIcon: false }, /* @__PURE__ */ React.createElement("span", null, "Selected"))),
44338
- /* @__PURE__ */ React.createElement("td", { className: "px-3 py-1.5 text-right" }, /* @__PURE__ */ React.createElement(
44339
- OverflowMenu$1,
44340
- {
44341
- toolbarItems: [
44342
- branch.githubPullRequestUrl && {
44343
- name: "github-pr",
44344
- label: "View in GitHub",
44345
- Icon: /* @__PURE__ */ React.createElement(BiLinkExternal, { className: "w-5 h-auto text-blue-500 opacity-70" }),
44346
- onMouseDown: () => {
44347
- window.open(branch.githubPullRequestUrl, "_blank");
44348
- }
44349
- },
44350
- !branch.githubPullRequestUrl && !branch.protected && !creatingPR && cms.api.tina.usingProtectedBranch() && {
44351
- name: "create-pr",
44352
- label: "Create Pull Request",
44353
- Icon: /* @__PURE__ */ React.createElement(BiGitBranch, { className: "w-5 h-auto text-blue-500 opacity-70" }),
44354
- onMouseDown: () => handleCreatePullRequest()
44355
- },
44356
- typeof previewFunction === "function" && ((_b = previewFunction({ branch: branch.name })) == null ? void 0 : _b.url) && {
44357
- name: "preview",
44358
- label: "Preview",
44359
- onMouseDown: () => {
44360
- var _a3;
44361
- const previewUrl = (_a3 = previewFunction({
44362
- branch: branch.name
44363
- })) == null ? void 0 : _a3.url;
44364
- window.open(previewUrl, "_blank");
44365
- }
44366
- }
44367
- ].filter(Boolean)
44368
- }
44369
- ))
44386
+ /* @__PURE__ */ React.createElement(BiLinkExternal, { className: "h-3.5 w-auto text-gray-700 flex-shrink-0" }),
44387
+ /* @__PURE__ */ React.createElement("span", { className: "text-sm truncate max-w-[120px]" }, "PR: ", extractPullRequestId(branch.githubPullRequestUrl))
44388
+ ) : !branch.protected && !creatingPR && cms.api.tina.usingProtectedBranch() ? /* @__PURE__ */ React.createElement(
44389
+ Button$2,
44390
+ {
44391
+ variant: "white",
44392
+ size: "custom",
44393
+ onClick: handleCreatePullRequest,
44394
+ className: "cursor-pointer h-9 px-2 flex items-center gap-1",
44395
+ title: "Create Pull Request"
44396
+ },
44397
+ /* @__PURE__ */ React.createElement(BiGitBranch, { className: "h-3.5 w-auto text-gray-700 flex-shrink-0" }),
44398
+ /* @__PURE__ */ React.createElement("span", { className: "text-sm whitespace-nowrap" }, "Create PR")
44399
+ ) : null)
44370
44400
  );
44371
44401
  };
44372
44402
  const IndexStatus = ({ indexingStatus }) => {
@@ -46604,7 +46634,7 @@ const NavProvider = ({
46604
46634
  };
46605
46635
  return /* @__PURE__ */ React__default.createElement(NavContext.Provider, { value }, children);
46606
46636
  };
46607
- const version$1 = "3.0.2";
46637
+ const version$1 = "3.1.1";
46608
46638
  const VersionInfo = () => {
46609
46639
  var _a2, _b, _c, _d, _e, _f;
46610
46640
  const cms = useCMS();
@@ -47290,8 +47320,25 @@ const Emoji$1 = ({ className = "", ...props }) => /* @__PURE__ */ React.createEl
47290
47320
  ...props
47291
47321
  }
47292
47322
  );
47323
+ const TooltipProvider = TooltipPrimitive.Provider;
47324
+ const Tooltip = TooltipPrimitive.Root;
47325
+ const TooltipTrigger = TooltipPrimitive.Trigger;
47326
+ const TooltipContent = React.forwardRef(({ className, sideOffset = 4, ...props }, ref) => /* @__PURE__ */ React.createElement(TooltipPrimitive.Portal, null, /* @__PURE__ */ React.createElement(
47327
+ TooltipPrimitive.Content,
47328
+ {
47329
+ ref,
47330
+ sideOffset,
47331
+ className: cn$1(
47332
+ "z-[10000] overflow-hidden rounded bg-[#FFF] px-3 py-1.5 text-xs text-[#504E5E] shadow-sm animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
47333
+ className
47334
+ ),
47335
+ ...props
47336
+ }
47337
+ )));
47338
+ TooltipContent.displayName = TooltipPrimitive.Content.displayName;
47293
47339
  const minimumTimeToShowLoadingIndicator = 1e3;
47294
47340
  const FormsView = ({ loadingPlaceholder } = {}) => {
47341
+ var _a2, _b;
47295
47342
  const cms = useCMS$1();
47296
47343
  const { setFormIsPristine } = React.useContext(SidebarContext);
47297
47344
  const [isShowingLoading, setIsShowingLoading] = React.useState(true);
@@ -47330,7 +47377,15 @@ const FormsView = ({ loadingPlaceholder } = {}) => {
47330
47377
  return /* @__PURE__ */ React.createElement(FormLists, { isEditing });
47331
47378
  }
47332
47379
  const formMetas = cms.plugins.all("form:meta");
47333
- return /* @__PURE__ */ React.createElement(React.Fragment, null, activeForm && /* @__PURE__ */ React.createElement(FormWrapper$1, { isEditing, isMultiform }, /* @__PURE__ */ React.createElement(FormHeader, { activeForm }), formMetas == null ? void 0 : formMetas.map((meta) => /* @__PURE__ */ React.createElement(React.Fragment, { key: meta.name }, /* @__PURE__ */ React.createElement(meta.Component, null))), /* @__PURE__ */ React.createElement(FormBuilder, { form: activeForm, onPristineChange: setFormIsPristine })));
47380
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, activeForm && /* @__PURE__ */ React.createElement(FormWrapper$1, { isEditing, isMultiform }, /* @__PURE__ */ React.createElement(
47381
+ FormHeader,
47382
+ {
47383
+ activeForm,
47384
+ branch: cms.api.admin.api.branch,
47385
+ repoProvider: cms.api.admin.api.schema.config.config.repoProvider,
47386
+ isLocalMode: (_b = (_a2 = cms.api) == null ? void 0 : _a2.tina) == null ? void 0 : _b.isLocalMode
47387
+ }
47388
+ ), formMetas == null ? void 0 : formMetas.map((meta) => /* @__PURE__ */ React.createElement(React.Fragment, { key: meta.name }, /* @__PURE__ */ React.createElement(meta.Component, null))), /* @__PURE__ */ React.createElement(FormBuilder, { form: activeForm, onPristineChange: setFormIsPristine })));
47334
47389
  };
47335
47390
  const FormWrapper$1 = ({ isEditing, children }) => {
47336
47391
  return /* @__PURE__ */ React.createElement(
@@ -47351,9 +47406,54 @@ const FormWrapper$1 = ({ isEditing, children }) => {
47351
47406
  children
47352
47407
  );
47353
47408
  };
47354
- const FormHeader = ({ activeForm }) => {
47409
+ const FormHeader = ({
47410
+ activeForm,
47411
+ repoProvider,
47412
+ branch,
47413
+ isLocalMode
47414
+ }) => {
47355
47415
  const { formIsPristine } = React.useContext(SidebarContext);
47356
- return /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-2 pb-4 flex flex-row flex-nowrap justify-between items-center gap-2 bg-gradient-to-t from-white to-gray-50" }, /* @__PURE__ */ React.createElement(MultiformSelector, { activeForm }), /* @__PURE__ */ React.createElement(FormBreadcrumbs, { className: "w-[calc(100%-3rem)]" }), /* @__PURE__ */ React.createElement(FormStatus, { pristine: formIsPristine }));
47416
+ return /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-2 pb-4 flex flex-row flex-nowrap justify-between items-center gap-2 bg-gradient-to-t from-white to-gray-50" }, /* @__PURE__ */ React.createElement(MultiformSelector, { activeForm }), /* @__PURE__ */ React.createElement(FormBreadcrumbs, { className: "w-[calc(100%-3rem)]" }), /* @__PURE__ */ React.createElement(
47417
+ FileHistoryProvider,
47418
+ {
47419
+ defaultBranchName: repoProvider == null ? void 0 : repoProvider.defaultBranchName,
47420
+ historyUrl: repoProvider == null ? void 0 : repoProvider.historyUrl,
47421
+ contentRelativePath: activeForm.tinaForm.path,
47422
+ tinaBranch: branch,
47423
+ isLocalMode
47424
+ }
47425
+ ), /* @__PURE__ */ React.createElement(FormStatus, { pristine: formIsPristine }));
47426
+ };
47427
+ const FileHistoryProvider = ({
47428
+ contentRelativePath,
47429
+ tinaBranch,
47430
+ defaultBranchName,
47431
+ historyUrl,
47432
+ isLocalMode
47433
+ }) => {
47434
+ if (!historyUrl) {
47435
+ return null;
47436
+ }
47437
+ const branch = isLocalMode ? defaultBranchName || tinaBranch : tinaBranch;
47438
+ if (!branch) {
47439
+ return null;
47440
+ }
47441
+ const { url } = historyUrl({
47442
+ relativePath: contentRelativePath,
47443
+ branch
47444
+ });
47445
+ if (!url) {
47446
+ return null;
47447
+ }
47448
+ return /* @__PURE__ */ React.createElement(TooltipProvider, null, /* @__PURE__ */ React.createElement(Tooltip, null, /* @__PURE__ */ React.createElement(TooltipTrigger, { asChild: true }, /* @__PURE__ */ React.createElement("button", { type: "button" }, /* @__PURE__ */ React.createElement(
47449
+ "a",
47450
+ {
47451
+ href: url,
47452
+ target: "_blank",
47453
+ className: "flex items-center gap-1 border-[0.5px] hover:bg-gray-300/10 transition-all duration-300 border-gray-300 rounded-md p-2"
47454
+ },
47455
+ /* @__PURE__ */ React.createElement(History, { className: "size-4 text-gray-700" })
47456
+ ))), /* @__PURE__ */ React.createElement(TooltipContent, { side: "top", className: "shadow-md" }, "View file history")));
47357
47457
  };
47358
47458
  const FormBreadcrumbs = ({
47359
47459
  rootBreadcrumbName,
@@ -48272,7 +48372,7 @@ function Alerts2({ alerts }) {
48272
48372
  if (!alerts.all.length) {
48273
48373
  return null;
48274
48374
  }
48275
- return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("div", { className: "fixed top-0 left-0 p-6 flex flex-col items-center z-[999999]" }, alerts.all.filter((alert) => {
48375
+ return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("div", { className: "fixed top-6 left-6 flex flex-col items-center z-[999999]" }, alerts.all.filter((alert) => {
48276
48376
  return alert.level !== "error";
48277
48377
  }).map((alert) => {
48278
48378
  return /* @__PURE__ */ React__default.createElement(Alert, { key: alert.id, level: alert.level }, alert.level === "info" && /* @__PURE__ */ React__default.createElement(MdInfo, { className: "w-5 h-auto text-blue-500" }), alert.level === "success" && /* @__PURE__ */ React__default.createElement(MdCheckCircle, { className: "w-5 h-auto text-green-500" }), alert.level === "warn" && /* @__PURE__ */ React__default.createElement(MdWarning, { className: "w-5 h-auto text-yellow-500" }), /* @__PURE__ */ React__default.createElement("p", { className: "m-0 flex-1 max-w-[680px] text-left" }, parseUrlsInText(alert.message.toString())), /* @__PURE__ */ React__default.createElement(
@@ -48606,7 +48706,7 @@ const BranchButton = ({ className = "" }) => {
48606
48706
  variant: "secondary",
48607
48707
  size: "custom",
48608
48708
  className: cn(
48609
- "pointer-events-auto px-3 py-3 flex shrink gap-1 items-center justify-between",
48709
+ "pointer-events-auto px-3 py-3 flex shrink gap-1 items-center justify-between max-w-sm",
48610
48710
  className
48611
48711
  ),
48612
48712
  onClick: () => setOpen(true),
@@ -121067,22 +121167,6 @@ const PageHeader = ({
121067
121167
  return /* @__PURE__ */ React__default.createElement("div", { className: "pt-4 pb-2 px-6" }, /* @__PURE__ */ React__default.createElement("div", { className: "w-full flex justify-between items-end" }, children));
121068
121168
  };
121069
121169
  const PageBody = ({ children }) => /* @__PURE__ */ React__default.createElement("div", { className: "py-4 px-6" }, children);
121070
- const TooltipProvider = TooltipPrimitive.Provider;
121071
- const Tooltip = TooltipPrimitive.Root;
121072
- const TooltipTrigger = TooltipPrimitive.Trigger;
121073
- const TooltipContent = React.forwardRef(({ className, sideOffset = 4, ...props }, ref) => /* @__PURE__ */ React.createElement(TooltipPrimitive.Portal, null, /* @__PURE__ */ React.createElement(
121074
- TooltipPrimitive.Content,
121075
- {
121076
- ref,
121077
- sideOffset,
121078
- className: cn$1(
121079
- "z-[10000] overflow-hidden rounded bg-[#FFF] px-3 py-1.5 text-xs text-[#504E5E] shadow-sm animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
121080
- className
121081
- ),
121082
- ...props
121083
- }
121084
- )));
121085
- TooltipContent.displayName = TooltipPrimitive.Content.displayName;
121086
121170
  const folderRegex = /^.*\/~\/*(.*)$/;
121087
121171
  const parentFolder = (folder) => {
121088
121172
  return {
@@ -122708,6 +122792,7 @@ const RenderForm = ({
122708
122792
  collection,
122709
122793
  mutationInfo
122710
122794
  }) => {
122795
+ var _a2, _b, _c, _d;
122711
122796
  const [formIsPristine, setFormIsPristine] = useState(true);
122712
122797
  const schema = cms.api.tina.schema;
122713
122798
  const schemaCollection = schema.getCollection(collection.name);
@@ -122779,6 +122864,15 @@ const RenderForm = ({
122779
122864
  className: "w-[calc(100%-3rem)]",
122780
122865
  rootBreadcrumbName: `${filename}.${collection.format}`
122781
122866
  }
122867
+ ), /* @__PURE__ */ React__default.createElement(
122868
+ FileHistoryProvider,
122869
+ {
122870
+ defaultBranchName: (_a2 = cms.api.admin.api.schema.config.config.repoProvider) == null ? void 0 : _a2.defaultBranchName,
122871
+ historyUrl: (_b = cms.api.admin.api.schema.config.config.repoProvider) == null ? void 0 : _b.historyUrl,
122872
+ contentRelativePath: relativePath2,
122873
+ tinaBranch: cms.api.admin.api.branch,
122874
+ isLocalMode: (_d = (_c = cms.api) == null ? void 0 : _c.tina) == null ? void 0 : _d.isLocalMode
122875
+ }
122782
122876
  ), /* @__PURE__ */ React__default.createElement(FormStatus, { pristine: formIsPristine }))
122783
122877
  ), activeForm && /* @__PURE__ */ React__default.createElement(FormBuilder, { form: activeForm, onPristineChange: setFormIsPristine }));
122784
122878
  };
@@ -9,8 +9,33 @@ export interface FormHeaderProps {
9
9
  activeFieldName?: string;
10
10
  tinaForm: Form;
11
11
  };
12
+ branch?: string;
13
+ isLocalMode?: boolean;
14
+ repoProvider?: {
15
+ defaultBranchName?: string;
16
+ historyUrl?: (context: {
17
+ relativePath: string;
18
+ branch: string;
19
+ }) => {
20
+ url: string;
21
+ };
22
+ };
23
+ }
24
+ export declare const FormHeader: ({ activeForm, repoProvider, branch, isLocalMode, }: FormHeaderProps) => React.JSX.Element;
25
+ interface RepositoryProviderProps {
26
+ contentRelativePath: string;
27
+ tinaBranch?: string;
28
+ isLocalMode?: boolean;
29
+ defaultBranchName?: string;
30
+ historyUrl?: (context: {
31
+ relativePath: string;
32
+ branch: string;
33
+ }) => {
34
+ url: string;
35
+ };
12
36
  }
13
- export declare const FormHeader: ({ activeForm }: FormHeaderProps) => React.JSX.Element;
37
+ export declare const FileHistoryProvider: ({ contentRelativePath, tinaBranch, defaultBranchName, historyUrl, isLocalMode, }: RepositoryProviderProps) => React.JSX.Element;
14
38
  export declare const FormBreadcrumbs: ({ rootBreadcrumbName, ...props }: {
15
39
  rootBreadcrumbName?: string;
16
40
  } & React.HTMLAttributes<HTMLDivElement>) => React.JSX.Element;
41
+ export {};
@@ -29,7 +29,7 @@ export declare class TinaClient<GenQueries> {
29
29
  initialized: boolean;
30
30
  cacheLock: AsyncLock | undefined;
31
31
  cacheDir: string;
32
- cache: Cache;
32
+ cache: Cache | null;
33
33
  constructor({ token, url, queries, errorPolicy, cacheDir, }: TinaClientArgs<GenQueries>);
34
34
  init(): Promise<void>;
35
35
  request<DataType extends Record<string, any> = any>({ errorPolicy, ...args }: TinaClientRequestArgs, options: {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "tinacms",
3
3
  "type": "module",
4
4
  "typings": "dist/index.d.ts",
5
- "version": "3.0.2",
5
+ "version": "3.1.1",
6
6
  "main": "dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "exports": {
@@ -25,18 +25,11 @@
25
25
  "src/rich-text/static.tsx",
26
26
  "src/rich-text/prism.tsx",
27
27
  "src/react.tsx",
28
- "src/client.ts"
29
- ],
30
- "build": {
31
- "rollupOptions": {
32
- "external": [
33
- "crypto",
34
- "fs",
35
- "path",
36
- "os"
37
- ]
28
+ {
29
+ "name": "src/client.ts",
30
+ "target": "node"
38
31
  }
39
- }
32
+ ]
40
33
  },
41
34
  "license": "Apache-2.0",
42
35
  "dependencies": {
@@ -117,9 +110,9 @@
117
110
  "webfontloader": "1.6.28",
118
111
  "yup": "^1.6.1",
119
112
  "zod": "^3.24.2",
120
- "@tinacms/mdx": "2.0.0",
121
- "@tinacms/schema-tools": "2.0.0",
122
- "@tinacms/search": "1.1.5"
113
+ "@tinacms/mdx": "2.0.1",
114
+ "@tinacms/schema-tools": "2.1.0",
115
+ "@tinacms/search": "1.1.7"
123
116
  },
124
117
  "devDependencies": {
125
118
  "@graphql-tools/utils": "^10.8.1",
@@ -138,7 +131,7 @@
138
131
  "identity-obj-proxy": "^3.0.0",
139
132
  "jest-file-snapshot": "^0.7.0",
140
133
  "lowlight": "^3.3.0",
141
- "next": "14.2.10",
134
+ "next": "14.2.35",
142
135
  "react": "^18.3.1",
143
136
  "react-dom": "^18.3.1",
144
137
  "react-is": "^18.3.1",
@@ -1,4 +0,0 @@
1
- const __viteBrowserExternal = {};
2
- export {
3
- __viteBrowserExternal as default
4
- };
@@ -1,63 +0,0 @@
1
- const makeCacheDir = async (dir, fs, path, os) => {
2
- const pathParts = dir.split(path.sep).filter(Boolean);
3
- const cacheHash = pathParts[pathParts.length - 1];
4
- const rootUser = pathParts[0];
5
- let cacheDir = dir;
6
- if (!fs.existsSync(path.join(path.sep, rootUser))) {
7
- cacheDir = path.join(os.tmpdir(), cacheHash);
8
- }
9
- try {
10
- fs.mkdirSync(cacheDir, { recursive: true });
11
- } catch (error) {
12
- throw new Error(`Failed to create cache directory: ${error.message}`);
13
- }
14
- return cacheDir;
15
- };
16
- const NodeCache = async (dir) => {
17
- const fs = await import("./__vite-browser-external-d06ac358.js");
18
- const path = await import("./__vite-browser-external-d06ac358.js");
19
- const os = await import("./__vite-browser-external-d06ac358.js");
20
- const crypto = await import("./__vite-browser-external-d06ac358.js");
21
- const cacheDir = await makeCacheDir(dir, fs, path, os);
22
- return {
23
- makeKey: (key) => {
24
- const input = key && key instanceof Object ? JSON.stringify(key) : key || "";
25
- return crypto.createHash("sha256").update(input).digest("hex");
26
- },
27
- get: async (key) => {
28
- let readValue;
29
- const cacheFilename = `${cacheDir}/${key}`;
30
- try {
31
- const data = await fs.promises.readFile(cacheFilename, "utf-8");
32
- readValue = JSON.parse(data);
33
- } catch (e) {
34
- if (e.code !== "ENOENT") {
35
- console.error(
36
- `Failed to read cache file to ${cacheFilename}: ${e.message}`
37
- );
38
- }
39
- }
40
- return readValue;
41
- },
42
- set: async (key, value) => {
43
- const cacheFilename = `${cacheDir}/${key}`;
44
- try {
45
- await fs.promises.writeFile(cacheFilename, JSON.stringify(value), {
46
- encoding: "utf-8",
47
- flag: "wx"
48
- // Don't overwrite existing caches
49
- });
50
- } catch (e) {
51
- if (e.code !== "EEXIST") {
52
- console.error(
53
- `Failed to write cache file to ${cacheFilename}: ${e.message}`
54
- );
55
- }
56
- }
57
- }
58
- };
59
- };
60
- export {
61
- NodeCache,
62
- makeCacheDir
63
- };