@codewheel/jsonapi-frontend-client 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,338 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ <https://fsf.org/>
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, see <https://www.gnu.org/licenses/>.
308
+
309
+ Also add information on how to contact you by electronic and paper mail.
310
+
311
+ If the program is interactive, make it output a short notice like this
312
+ when it starts in an interactive mode:
313
+
314
+ Gnomovision version 69, Copyright (C) year name of author
315
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
316
+ This is free software, and you are welcome to redistribute it
317
+ under certain conditions; type `show c' for details.
318
+
319
+ The hypothetical commands `show w' and `show c' should show the appropriate
320
+ parts of the General Public License. Of course, the commands you use may
321
+ be called something other than `show w' and `show c'; they could even be
322
+ mouse-clicks or menu items--whatever suits your program.
323
+
324
+ You should also get your employer (if you work as a programmer) or your
325
+ school, if any, to sign a "copyright disclaimer" for the program, if
326
+ necessary. Here is a sample; alter the names:
327
+
328
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
329
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
330
+
331
+ <signature of Moe Ghoul>, 1 April 1989
332
+ Moe Ghoul, President of Vice
333
+
334
+ This General Public License does not permit incorporating your program into
335
+ proprietary programs. If your program is a subroutine library, you may
336
+ consider it more useful to permit linking proprietary applications with the
337
+ library. If this is what you want to do, use the GNU Lesser General
338
+ Public License instead of this License.
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # `@codewheel/jsonapi-frontend-client`
2
+
3
+ TypeScript client helpers for Drupal `drupal/jsonapi_frontend`.
4
+
5
+ This package is **optional**. You can always call `/jsonapi/resolve` directly with `fetch()`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm i @codewheel/jsonapi-frontend-client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ Set `DRUPAL_BASE_URL`, then:
16
+
17
+ ```ts
18
+ import { resolvePath, fetchJsonApi } from "@codewheel/jsonapi-frontend-client"
19
+
20
+ const resolved = await resolvePath("/about-us")
21
+ if (resolved.resolved && resolved.kind === "entity") {
22
+ const doc = await fetchJsonApi(resolved.jsonapi_url)
23
+ console.log(doc.data)
24
+ }
25
+ ```
@@ -0,0 +1,45 @@
1
+ import { FetchInit, FetchLike } from "./transport";
2
+ import { JsonApiDocument } from "./types";
3
+ /**
4
+ * Build cache tags for a JSON:API entity URL (e.g. /jsonapi/node/page/{uuid}).
5
+ *
6
+ * These tags are compatible with the jsonapi_frontend revalidation webhook payload.
7
+ */
8
+ export declare function buildEntityCacheTags(jsonapiPath: string): string[];
9
+ /**
10
+ * Build cache tags for a jsonapi_views URL (e.g. /jsonapi/views/blog/page_1).
11
+ */
12
+ export declare function buildViewCacheTags(dataUrl: string): string[];
13
+ export declare function fetchJsonApi<T = JsonApiDocument>(jsonapiPath: string, options?: {
14
+ baseUrl?: string;
15
+ envKey?: string;
16
+ include?: string[];
17
+ fields?: Record<string, string[]>;
18
+ revalidate?: number;
19
+ /** Additional cache tags to include (Next.js only). */
20
+ tags?: string[];
21
+ fetch?: FetchLike;
22
+ headers?: HeadersInit;
23
+ init?: FetchInit;
24
+ }): Promise<T>;
25
+ export declare function fetchView<T = JsonApiDocument>(dataUrl: string, options?: {
26
+ baseUrl?: string;
27
+ envKey?: string;
28
+ /**
29
+ * JSON:API pagination parameters.
30
+ *
31
+ * - number: sets page[offset]
32
+ * - object: sets page[offset] and/or page[limit]
33
+ */
34
+ page?: number | {
35
+ offset?: number;
36
+ limit?: number;
37
+ };
38
+ revalidate?: number;
39
+ /** Additional cache tags to include (Next.js only). */
40
+ tags?: string[];
41
+ fetch?: FetchLike;
42
+ headers?: HeadersInit;
43
+ init?: FetchInit;
44
+ }): Promise<T>;
45
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAuD,MAAM,aAAa,CAAA;AACvG,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAEzC;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,EAAE,CAmBlE;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,EAAE,CAa5D;AAED,wBAAsB,YAAY,CAAC,CAAC,GAAG,eAAe,EACpD,WAAW,EAAE,MAAM,EACnB,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAA;IACjC,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;IACf,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,GACA,OAAO,CAAC,CAAC,CAAC,CAsCZ;AAED,wBAAsB,SAAS,CAAC,CAAC,GAAG,eAAe,EACjD,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IACnD,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;IACf,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,GACA,OAAO,CAAC,CAAC,CAAC,CAyCZ"}
package/dist/fetch.js ADDED
@@ -0,0 +1,103 @@
1
+ import { getDrupalBaseUrlFromOptions, getFetch, mergeHeaders } from "./transport";
2
+ /**
3
+ * Build cache tags for a JSON:API entity URL (e.g. /jsonapi/node/page/{uuid}).
4
+ *
5
+ * These tags are compatible with the jsonapi_frontend revalidation webhook payload.
6
+ */
7
+ export function buildEntityCacheTags(jsonapiPath) {
8
+ const tags = ["drupal"];
9
+ // Parse: /jsonapi/{entity_type}/{bundle}/{uuid}
10
+ const match = jsonapiPath.match(/\/jsonapi\/([^/]+)\/([^/]+)(?:\/([^/?]+))?/);
11
+ if (!match) {
12
+ return tags;
13
+ }
14
+ const [, entityType, bundle, uuid] = match;
15
+ tags.push(`type:${entityType}--${bundle}`);
16
+ tags.push(`bundle:${bundle}`);
17
+ if (uuid) {
18
+ tags.push(`${entityType}:${uuid}`);
19
+ tags.push(`uuid:${uuid}`);
20
+ }
21
+ return tags;
22
+ }
23
+ /**
24
+ * Build cache tags for a jsonapi_views URL (e.g. /jsonapi/views/blog/page_1).
25
+ */
26
+ export function buildViewCacheTags(dataUrl) {
27
+ const tags = ["drupal", "views"];
28
+ const match = dataUrl.match(/\/jsonapi\/views\/([^/]+)\/([^/?]+)/);
29
+ if (!match) {
30
+ return tags;
31
+ }
32
+ const [, viewId, displayId] = match;
33
+ tags.push(`view:${viewId}`);
34
+ tags.push(`view:${viewId}--${displayId}`);
35
+ return tags;
36
+ }
37
+ export async function fetchJsonApi(jsonapiPath, options) {
38
+ const base = getDrupalBaseUrlFromOptions({ baseUrl: options?.baseUrl, envKey: options?.envKey });
39
+ const fetcher = getFetch(options?.fetch);
40
+ const url = new URL(jsonapiPath, base);
41
+ if (options?.include?.length) {
42
+ url.searchParams.set("include", options.include.join(","));
43
+ }
44
+ if (options?.fields) {
45
+ for (const [type, fields] of Object.entries(options.fields)) {
46
+ url.searchParams.set(`fields[${type}]`, fields.join(","));
47
+ }
48
+ }
49
+ const tags = [...buildEntityCacheTags(jsonapiPath), ...(options?.tags ?? [])];
50
+ const headers = mergeHeaders(options?.init?.headers, options?.headers);
51
+ if (!headers.has("Accept")) {
52
+ headers.set("Accept", "application/vnd.api+json");
53
+ }
54
+ const res = await fetcher(url.toString(), {
55
+ ...options?.init,
56
+ headers,
57
+ next: {
58
+ ...(options?.init?.next ?? {}),
59
+ revalidate: options?.revalidate,
60
+ tags: Array.from(new Set([...(options?.init?.next?.tags ?? []), ...tags])),
61
+ },
62
+ });
63
+ if (!res.ok) {
64
+ throw new Error(`JSON:API fetch failed: ${res.status} ${res.statusText}`);
65
+ }
66
+ return (await res.json());
67
+ }
68
+ export async function fetchView(dataUrl, options) {
69
+ const base = getDrupalBaseUrlFromOptions({ baseUrl: options?.baseUrl, envKey: options?.envKey });
70
+ const fetcher = getFetch(options?.fetch);
71
+ const url = new URL(dataUrl, base);
72
+ if (options?.page !== undefined) {
73
+ if (typeof options.page === "number") {
74
+ url.searchParams.set("page[offset]", String(options.page));
75
+ }
76
+ else {
77
+ if (options.page.offset !== undefined) {
78
+ url.searchParams.set("page[offset]", String(options.page.offset));
79
+ }
80
+ if (options.page.limit !== undefined) {
81
+ url.searchParams.set("page[limit]", String(options.page.limit));
82
+ }
83
+ }
84
+ }
85
+ const tags = [...buildViewCacheTags(dataUrl), ...(options?.tags ?? [])];
86
+ const headers = mergeHeaders(options?.init?.headers, options?.headers);
87
+ if (!headers.has("Accept")) {
88
+ headers.set("Accept", "application/vnd.api+json");
89
+ }
90
+ const res = await fetcher(url.toString(), {
91
+ ...options?.init,
92
+ headers,
93
+ next: {
94
+ ...(options?.init?.next ?? {}),
95
+ revalidate: options?.revalidate,
96
+ tags: Array.from(new Set([...(options?.init?.next?.tags ?? []), ...tags])),
97
+ },
98
+ });
99
+ if (!res.ok) {
100
+ throw new Error(`View fetch failed: ${res.status} ${res.statusText}`);
101
+ }
102
+ return (await res.json());
103
+ }
@@ -0,0 +1,8 @@
1
+ export { resolvePath } from "./resolve";
2
+ export { fetchJsonApi, fetchView } from "./fetch";
3
+ export { getDrupalBaseUrl, resolveFileUrl, getFileUrl, getImageStyleUrl } from "./url";
4
+ export { findIncluded, findIncludedByRelationship, findIncludedByRelationshipMultiple, extractImageFromFile, extractMedia, extractMediaField, extractPrimaryImage, extractEmbeddedMediaUuids, parseDrupalMediaTag, } from "./media";
5
+ export type { ResolveResponse, JsonApiDocument, JsonApiResource, JsonApiRelationship, JsonApiLinks, NodeAttributes, } from "./types";
6
+ export type { DrupalImageData, DrupalMediaData } from "./media";
7
+ export type { FetchInit, FetchLike } from "./transport";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AACvC,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AAEjD,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAA;AAEtF,OAAO,EACL,YAAY,EACZ,0BAA0B,EAC1B,kCAAkC,EAClC,oBAAoB,EACpB,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,EACnB,yBAAyB,EACzB,mBAAmB,GACpB,MAAM,SAAS,CAAA;AAEhB,YAAY,EACV,eAAe,EACf,eAAe,EACf,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,cAAc,GACf,MAAM,SAAS,CAAA;AAEhB,YAAY,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAE/D,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { resolvePath } from "./resolve";
2
+ export { fetchJsonApi, fetchView } from "./fetch";
3
+ export { getDrupalBaseUrl, resolveFileUrl, getFileUrl, getImageStyleUrl } from "./url";
4
+ export { findIncluded, findIncludedByRelationship, findIncludedByRelationshipMultiple, extractImageFromFile, extractMedia, extractMediaField, extractPrimaryImage, extractEmbeddedMediaUuids, parseDrupalMediaTag, } from "./media";
@@ -0,0 +1,27 @@
1
+ import { JsonApiResource, JsonApiRelationship } from "./types";
2
+ export interface DrupalImageData {
3
+ src: string;
4
+ alt: string;
5
+ width?: number;
6
+ height?: number;
7
+ title?: string;
8
+ }
9
+ export interface DrupalMediaData {
10
+ type: "image" | "video" | "file" | "remote_video" | "audio" | "unknown";
11
+ name: string;
12
+ url: string | null;
13
+ image?: DrupalImageData;
14
+ mimeType?: string;
15
+ embedUrl?: string;
16
+ resource: JsonApiResource;
17
+ }
18
+ export declare function findIncluded(included: JsonApiResource[] | undefined, type: string, id: string): JsonApiResource | undefined;
19
+ export declare function findIncludedByRelationship(included: JsonApiResource[] | undefined, relationship: JsonApiRelationship | undefined): JsonApiResource | undefined;
20
+ export declare function findIncludedByRelationshipMultiple(included: JsonApiResource[] | undefined, relationship: JsonApiRelationship | undefined): JsonApiResource[];
21
+ export declare function extractImageFromFile(file: JsonApiResource | undefined): DrupalImageData | null;
22
+ export declare function extractMedia(media: JsonApiResource | undefined, included: JsonApiResource[] | undefined): DrupalMediaData | null;
23
+ export declare function extractMediaField(entity: JsonApiResource, fieldName: string, included: JsonApiResource[] | undefined): DrupalMediaData[];
24
+ export declare function extractPrimaryImage(entity: JsonApiResource, included: JsonApiResource[] | undefined): DrupalImageData | null;
25
+ export declare function parseDrupalMediaTag(html: string): string | null;
26
+ export declare function extractEmbeddedMediaUuids(html: string): string[];
27
+ //# sourceMappingURL=media.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.d.ts","sourceRoot":"","sources":["../src/media.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAA;AAG9D,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,GAAG,cAAc,GAAG,OAAO,GAAG,SAAS,CAAA;IACvE,IAAI,EAAE,MAAM,CAAA;IACZ,GAAG,EAAE,MAAM,GAAG,IAAI,CAAA;IAClB,KAAK,CAAC,EAAE,eAAe,CAAA;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,eAAe,CAAA;CAC1B;AAED,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,EACvC,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,GACT,eAAe,GAAG,SAAS,CAE7B;AAED,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,EACvC,YAAY,EAAE,mBAAmB,GAAG,SAAS,GAC5C,eAAe,GAAG,SAAS,CAK7B;AAED,wBAAgB,kCAAkC,CAChD,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,EACvC,YAAY,EAAE,mBAAmB,GAAG,SAAS,GAC5C,eAAe,EAAE,CAUnB;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,eAAe,GAAG,SAAS,GAAG,eAAe,GAAG,IAAI,CAkB9F;AAcD,wBAAgB,YAAY,CAC1B,KAAK,EAAE,eAAe,GAAG,SAAS,EAClC,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,GACtC,eAAe,GAAG,IAAI,CAgGxB;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,eAAe,EACvB,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,GACtC,eAAe,EAAE,CAanB;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,eAAe,EAAE,QAAQ,EAAE,eAAe,EAAE,GAAG,SAAS,GAAG,eAAe,GAAG,IAAI,CAY5H;AAgBD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAG/D;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAUhE"}
package/dist/media.js ADDED
@@ -0,0 +1,167 @@
1
+ import { getFileUrl } from "./url";
2
+ export function findIncluded(included, type, id) {
3
+ return included?.find((item) => item.type === type && item.id === id);
4
+ }
5
+ export function findIncludedByRelationship(included, relationship) {
6
+ if (!relationship?.data || Array.isArray(relationship.data)) {
7
+ return undefined;
8
+ }
9
+ return findIncluded(included, relationship.data.type, relationship.data.id);
10
+ }
11
+ export function findIncludedByRelationshipMultiple(included, relationship) {
12
+ if (!relationship?.data) {
13
+ return [];
14
+ }
15
+ const refs = Array.isArray(relationship.data) ? relationship.data : [relationship.data];
16
+ return refs
17
+ .map((ref) => findIncluded(included, ref.type, ref.id))
18
+ .filter((item) => item !== undefined);
19
+ }
20
+ export function extractImageFromFile(file) {
21
+ if (!file) {
22
+ return null;
23
+ }
24
+ const url = getFileUrl(file);
25
+ if (!url) {
26
+ return null;
27
+ }
28
+ const attrs = file.attributes;
29
+ return {
30
+ src: url,
31
+ alt: attrs?.filename || "",
32
+ width: attrs?.image_style_uri ? undefined : attrs?.width,
33
+ height: attrs?.image_style_uri ? undefined : attrs?.height,
34
+ };
35
+ }
36
+ function getRelationshipMetaString(relationship, key) {
37
+ const data = relationship?.data;
38
+ if (!data || Array.isArray(data)) {
39
+ return undefined;
40
+ }
41
+ const meta = data.meta;
42
+ const value = meta?.[key];
43
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
44
+ }
45
+ export function extractMedia(media, included) {
46
+ if (!media) {
47
+ return null;
48
+ }
49
+ const attrs = media.attributes;
50
+ const relationships = media.relationships;
51
+ const name = attrs?.name || "";
52
+ const mediaType = media.type.replace("media--", "");
53
+ const result = {
54
+ type: "unknown",
55
+ name,
56
+ url: null,
57
+ resource: media,
58
+ };
59
+ switch (mediaType) {
60
+ case "image": {
61
+ result.type = "image";
62
+ const fileRelationship = relationships?.field_media_image;
63
+ const file = findIncludedByRelationship(included, fileRelationship);
64
+ if (file) {
65
+ const imageData = extractImageFromFile(file);
66
+ if (imageData) {
67
+ result.url = imageData.src;
68
+ const alt = getRelationshipMetaString(fileRelationship, "alt");
69
+ const title = getRelationshipMetaString(fileRelationship, "title");
70
+ result.image = {
71
+ ...imageData,
72
+ alt: alt || imageData.alt || name,
73
+ title: title || imageData.title,
74
+ };
75
+ }
76
+ }
77
+ break;
78
+ }
79
+ case "video": {
80
+ result.type = "video";
81
+ const fileRelationship = relationships?.field_media_video_file;
82
+ const file = findIncludedByRelationship(included, fileRelationship);
83
+ if (file) {
84
+ result.url = getFileUrl(file);
85
+ result.mimeType = file.attributes?.filemime || "video/mp4";
86
+ }
87
+ break;
88
+ }
89
+ case "remote_video": {
90
+ result.type = "remote_video";
91
+ const videoUrl = attrs?.field_media_oembed_video;
92
+ result.url = videoUrl || null;
93
+ if (videoUrl) {
94
+ result.embedUrl = getVideoEmbedUrl(videoUrl);
95
+ }
96
+ break;
97
+ }
98
+ case "file":
99
+ case "document": {
100
+ result.type = "file";
101
+ const fileRelationship = relationships?.field_media_file || relationships?.field_media_document;
102
+ const file = findIncludedByRelationship(included, fileRelationship);
103
+ if (file) {
104
+ result.url = getFileUrl(file);
105
+ result.mimeType = file.attributes?.filemime;
106
+ }
107
+ break;
108
+ }
109
+ case "audio": {
110
+ result.type = "audio";
111
+ const fileRelationship = relationships?.field_media_audio_file;
112
+ const file = findIncludedByRelationship(included, fileRelationship);
113
+ if (file) {
114
+ result.url = getFileUrl(file);
115
+ result.mimeType = file.attributes?.filemime || "audio/mpeg";
116
+ }
117
+ break;
118
+ }
119
+ }
120
+ return result;
121
+ }
122
+ export function extractMediaField(entity, fieldName, included) {
123
+ const relationships = entity.relationships;
124
+ const relationship = relationships?.[fieldName];
125
+ if (!relationship) {
126
+ return [];
127
+ }
128
+ const mediaResources = findIncludedByRelationshipMultiple(included, relationship);
129
+ return mediaResources
130
+ .map((media) => extractMedia(media, included))
131
+ .filter((item) => item !== null);
132
+ }
133
+ export function extractPrimaryImage(entity, included) {
134
+ const commonFields = ["field_image", "field_media_image", "field_media", "field_thumbnail", "field_hero_image"];
135
+ for (const fieldName of commonFields) {
136
+ const media = extractMediaField(entity, fieldName, included);
137
+ const imageMedia = media.find((m) => m.type === "image");
138
+ if (imageMedia?.image) {
139
+ return imageMedia.image;
140
+ }
141
+ }
142
+ return null;
143
+ }
144
+ function getVideoEmbedUrl(url) {
145
+ const youtubeMatch = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]+)/);
146
+ if (youtubeMatch) {
147
+ return `https://www.youtube.com/embed/${youtubeMatch[1]}`;
148
+ }
149
+ const vimeoMatch = url.match(/vimeo\.com\/(\d+)/);
150
+ if (vimeoMatch) {
151
+ return `https://player.vimeo.com/video/${vimeoMatch[1]}`;
152
+ }
153
+ return undefined;
154
+ }
155
+ export function parseDrupalMediaTag(html) {
156
+ const match = html.match(/data-entity-uuid=[\"']([^\"']+)[\"']/);
157
+ return match ? match[1] : null;
158
+ }
159
+ export function extractEmbeddedMediaUuids(html) {
160
+ const regex = /<drupal-media[^>]*data-entity-uuid=[\"']([^\"']+)[\"'][^>]*>/g;
161
+ const uuids = [];
162
+ let match;
163
+ while ((match = regex.exec(html)) !== null) {
164
+ uuids.push(match[1]);
165
+ }
166
+ return uuids;
167
+ }
@@ -0,0 +1,15 @@
1
+ import { ResolveResponse } from "./types";
2
+ import { FetchInit, FetchLike } from "./transport";
3
+ /**
4
+ * Resolve a frontend path to a Drupal resource.
5
+ */
6
+ export declare function resolvePath(path: string, options?: {
7
+ baseUrl?: string;
8
+ envKey?: string;
9
+ langcode?: string;
10
+ revalidate?: number;
11
+ fetch?: FetchLike;
12
+ headers?: HeadersInit;
13
+ init?: FetchInit;
14
+ }): Promise<ResolveResponse>;
15
+ //# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAuD,MAAM,aAAa,CAAA;AAEvG;;GAEG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,IAAI,CAAC,EAAE,SAAS,CAAA;CACjB,GACA,OAAO,CAAC,eAAe,CAAC,CA8B1B"}
@@ -0,0 +1,30 @@
1
+ import { getDrupalBaseUrlFromOptions, getFetch, mergeHeaders } from "./transport";
2
+ /**
3
+ * Resolve a frontend path to a Drupal resource.
4
+ */
5
+ export async function resolvePath(path, options) {
6
+ const base = getDrupalBaseUrlFromOptions({ baseUrl: options?.baseUrl, envKey: options?.envKey });
7
+ const fetcher = getFetch(options?.fetch);
8
+ const url = new URL("/jsonapi/resolve", base);
9
+ url.searchParams.set("path", path);
10
+ url.searchParams.set("_format", "json");
11
+ if (options?.langcode) {
12
+ url.searchParams.set("langcode", options.langcode);
13
+ }
14
+ const headers = mergeHeaders(options?.init?.headers, options?.headers);
15
+ if (!headers.has("Accept")) {
16
+ headers.set("Accept", "application/vnd.api+json");
17
+ }
18
+ const res = await fetcher(url.toString(), {
19
+ ...options?.init,
20
+ headers,
21
+ next: {
22
+ ...(options?.init?.next ?? {}),
23
+ revalidate: options?.revalidate,
24
+ },
25
+ });
26
+ if (!res.ok) {
27
+ throw new Error(`Resolver failed: ${res.status} ${res.statusText}`);
28
+ }
29
+ return (await res.json());
30
+ }
@@ -0,0 +1,18 @@
1
+ export type NextFetchOptions = {
2
+ revalidate?: number;
3
+ tags?: string[];
4
+ };
5
+ /**
6
+ * Fetch init that is compatible with both standard Fetch and Next.js fetch extensions.
7
+ */
8
+ export type FetchInit = RequestInit & {
9
+ next?: NextFetchOptions;
10
+ };
11
+ export type FetchLike = (input: RequestInfo | URL, init?: FetchInit) => Promise<Response>;
12
+ export declare function getDrupalBaseUrlFromOptions(options?: {
13
+ baseUrl?: string;
14
+ envKey?: string;
15
+ }): string;
16
+ export declare function getFetch(fetchLike?: FetchLike): FetchLike;
17
+ export declare function mergeHeaders(...headersList: Array<HeadersInit | undefined>): Headers;
18
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../src/transport.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,IAAI,CAAC,EAAE,MAAM,EAAE,CAAA;CAChB,CAAA;AAED;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,WAAW,GAAG;IACpC,IAAI,CAAC,EAAE,gBAAgB,CAAA;CACxB,CAAA;AAED,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,WAAW,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,SAAS,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;AAOzF,wBAAgB,2BAA2B,CAAC,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAMnG;AAED,wBAAgB,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,GAAG,SAAS,CAMzD;AAED,wBAAgB,YAAY,CAAC,GAAG,WAAW,EAAE,KAAK,CAAC,WAAW,GAAG,SAAS,CAAC,GAAG,OAAO,CAOpF"}
@@ -0,0 +1,27 @@
1
+ function getEnvString(key) {
2
+ const value = globalThis.process?.env?.[key];
3
+ return typeof value === "string" && value.trim() !== "" ? value : undefined;
4
+ }
5
+ export function getDrupalBaseUrlFromOptions(options) {
6
+ const baseUrl = options?.baseUrl ?? getEnvString(options?.envKey ?? "DRUPAL_BASE_URL");
7
+ if (!baseUrl) {
8
+ throw new Error(`Missing Drupal base URL (pass baseUrl or set ${options?.envKey ?? "DRUPAL_BASE_URL"})`);
9
+ }
10
+ return baseUrl.replace(/\/$/, "");
11
+ }
12
+ export function getFetch(fetchLike) {
13
+ const f = fetchLike ?? globalThis.fetch;
14
+ if (!f) {
15
+ throw new Error("No fetch implementation available. Provide options.fetch or use Node 18+/modern browsers.");
16
+ }
17
+ return f;
18
+ }
19
+ export function mergeHeaders(...headersList) {
20
+ const headers = new Headers();
21
+ for (const list of headersList) {
22
+ if (!list)
23
+ continue;
24
+ new Headers(list).forEach((value, key) => headers.set(key, value));
25
+ }
26
+ return headers;
27
+ }
@@ -0,0 +1,100 @@
1
+ export type ResolveResponse = {
2
+ resolved: true;
3
+ kind: "entity";
4
+ canonical: string;
5
+ entity: {
6
+ type: string;
7
+ id: string;
8
+ langcode: string;
9
+ };
10
+ redirect: {
11
+ to: string;
12
+ status?: number;
13
+ } | null;
14
+ jsonapi_url: string;
15
+ data_url: null;
16
+ headless: boolean;
17
+ drupal_url: string | null;
18
+ } | {
19
+ resolved: true;
20
+ kind: "view";
21
+ canonical: string;
22
+ entity: null;
23
+ redirect: {
24
+ to: string;
25
+ status?: number;
26
+ } | null;
27
+ jsonapi_url: null;
28
+ data_url: string;
29
+ headless: boolean;
30
+ drupal_url: string | null;
31
+ } | {
32
+ resolved: false;
33
+ kind: null;
34
+ canonical: null;
35
+ entity: null;
36
+ redirect: {
37
+ to: string;
38
+ status?: number;
39
+ } | null;
40
+ jsonapi_url: null;
41
+ data_url: null;
42
+ headless: false;
43
+ drupal_url: null;
44
+ };
45
+ export interface JsonApiDocument<T = JsonApiResource> {
46
+ data: T | T[];
47
+ included?: JsonApiResource[];
48
+ links?: JsonApiLinks;
49
+ meta?: Record<string, unknown>;
50
+ }
51
+ export interface JsonApiResource {
52
+ type: string;
53
+ id: string;
54
+ attributes?: Record<string, unknown>;
55
+ relationships?: Record<string, JsonApiRelationship>;
56
+ links?: JsonApiLinks;
57
+ }
58
+ export interface JsonApiRelationship {
59
+ data: {
60
+ type: string;
61
+ id: string;
62
+ } | {
63
+ type: string;
64
+ id: string;
65
+ }[] | null;
66
+ links?: JsonApiLinks;
67
+ }
68
+ export interface JsonApiLinks {
69
+ self?: string | {
70
+ href: string;
71
+ };
72
+ related?: string | {
73
+ href: string;
74
+ };
75
+ next?: string | {
76
+ href: string;
77
+ };
78
+ prev?: string | {
79
+ href: string;
80
+ };
81
+ }
82
+ export interface NodeAttributes {
83
+ drupal_internal__nid: number;
84
+ title: string;
85
+ created: string;
86
+ changed: string;
87
+ status: boolean;
88
+ path?: {
89
+ alias: string | null;
90
+ pid: number | null;
91
+ langcode: string;
92
+ };
93
+ body?: {
94
+ value: string;
95
+ format: string;
96
+ processed: string;
97
+ summary: string;
98
+ };
99
+ }
100
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/url.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Get the Drupal base URL.
3
+ *
4
+ * Defaults to reading `DRUPAL_BASE_URL` from the environment.
5
+ */
6
+ export declare function getDrupalBaseUrl(options?: {
7
+ baseUrl?: string;
8
+ envKey?: string;
9
+ }): string;
10
+ /**
11
+ * Resolve a Drupal file URL to an absolute URL.
12
+ */
13
+ export declare function resolveFileUrl(url: string | null | undefined, options?: {
14
+ baseUrl?: string;
15
+ envKey?: string;
16
+ }): string | null;
17
+ export declare function getFileUrl(file: {
18
+ attributes?: {
19
+ uri?: {
20
+ url?: string;
21
+ value?: string;
22
+ };
23
+ url?: string;
24
+ };
25
+ } | null | undefined, options?: {
26
+ baseUrl?: string;
27
+ envKey?: string;
28
+ }): string | null;
29
+ /**
30
+ * Build a URL with image style derivative.
31
+ */
32
+ export declare function getImageStyleUrl(originalUrl: string, style: string, options?: {
33
+ baseUrl?: string;
34
+ envKey?: string;
35
+ }): string;
36
+ //# sourceMappingURL=url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../src/url.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAExF;AAED;;GAEG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC9B,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9C,MAAM,GAAG,IAAI,CAoBf;AAED,wBAAgB,UAAU,CACxB,IAAI,EAAE;IACJ,UAAU,CAAC,EAAE;QACX,GAAG,CAAC,EAAE;YAAE,GAAG,CAAC,EAAE,MAAM,CAAC;YAAC,KAAK,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;QACtC,GAAG,CAAC,EAAE,MAAM,CAAA;KACb,CAAA;CACF,GAAG,IAAI,GAAG,SAAS,EACpB,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9C,MAAM,GAAG,IAAI,CAOf;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAiB5H"}
package/dist/url.js ADDED
@@ -0,0 +1,54 @@
1
+ import { getDrupalBaseUrlFromOptions } from "./transport";
2
+ /**
3
+ * Get the Drupal base URL.
4
+ *
5
+ * Defaults to reading `DRUPAL_BASE_URL` from the environment.
6
+ */
7
+ export function getDrupalBaseUrl(options) {
8
+ return getDrupalBaseUrlFromOptions(options);
9
+ }
10
+ /**
11
+ * Resolve a Drupal file URL to an absolute URL.
12
+ */
13
+ export function resolveFileUrl(url, options) {
14
+ if (!url) {
15
+ return null;
16
+ }
17
+ if (url.startsWith("http://") || url.startsWith("https://")) {
18
+ return url;
19
+ }
20
+ if (url.startsWith("data:")) {
21
+ return url;
22
+ }
23
+ if (url.startsWith("//")) {
24
+ return `https:${url}`;
25
+ }
26
+ const base = getDrupalBaseUrlFromOptions(options);
27
+ const path = url.startsWith("/") ? url : `/${url}`;
28
+ return `${base}${path}`;
29
+ }
30
+ export function getFileUrl(file, options) {
31
+ if (!file?.attributes) {
32
+ return null;
33
+ }
34
+ const url = file.attributes.uri?.url || file.attributes.uri?.value || file.attributes.url;
35
+ return resolveFileUrl(url, options);
36
+ }
37
+ /**
38
+ * Build a URL with image style derivative.
39
+ */
40
+ export function getImageStyleUrl(originalUrl, style, options) {
41
+ const resolved = resolveFileUrl(originalUrl, options);
42
+ if (!resolved) {
43
+ return originalUrl;
44
+ }
45
+ if (resolved.includes("/styles/")) {
46
+ return resolved.replace(/\/styles\/[^/]+\//, `/styles/${style}/`);
47
+ }
48
+ const filesMatch = resolved.match(/(.+\/files\/)(.+)$/);
49
+ if (filesMatch) {
50
+ const [, basePath, filePath] = filesMatch;
51
+ return `${basePath}styles/${style}/public/${filePath}`;
52
+ }
53
+ return resolved;
54
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@codewheel/jsonapi-frontend-client",
3
+ "version": "1.0.0",
4
+ "description": "TypeScript client helpers for Drupal drupal/jsonapi_frontend",
5
+ "homepage": "https://github.com/CodeWheel-AI/jsonapi-frontend-client#readme",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/CodeWheel-AI/jsonapi-frontend-client.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/CodeWheel-AI/jsonapi-frontend-client/issues"
12
+ },
13
+ "keywords": [
14
+ "drupal",
15
+ "jsonapi",
16
+ "headless",
17
+ "frontend"
18
+ ],
19
+ "license": "GPL-2.0-or-later",
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "engines": {
23
+ "node": ">=18.0.0"
24
+ },
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -p tsconfig.json",
39
+ "prepack": "npm run build"
40
+ },
41
+ "devDependencies": {
42
+ "typescript": "^5.0.0"
43
+ }
44
+ }