@bstage-sdk/react 0.1.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bemyfriends Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,432 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ BstageContext: () => BstageContext,
24
+ BstageLocaleProvider: () => BstageLocaleProvider,
25
+ __bstage_registry__: () => __bstage_registry__,
26
+ createTemplate: () => createTemplate,
27
+ registerTemplate: () => registerTemplate,
28
+ useBstageContext: () => useBstageContext,
29
+ useBstageTranslations: () => useBstageTranslations,
30
+ useLocale: () => useLocale,
31
+ useMessages: () => useMessages,
32
+ useNavigation: () => useNavigation,
33
+ usePlatformEvent: () => usePlatformEvent,
34
+ useShadowStyle: () => useShadowStyle,
35
+ useSlotContext: () => useSlotContext
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/createTemplate.tsx
40
+ var import_react = require("react");
41
+ var __bstage_registry__ = /* @__PURE__ */ new Set();
42
+ function createTemplate(Component, options) {
43
+ const { name } = options;
44
+ validateElementName(name);
45
+ const meta = {
46
+ name,
47
+ elementName: name,
48
+ framework: "react",
49
+ ...options.slot && { slot: options.slot },
50
+ ...options.type && { type: options.type }
51
+ };
52
+ function TemplateWrapper(props) {
53
+ return (0, import_react.createElement)(Component, props);
54
+ }
55
+ TemplateWrapper.displayName = `BstageTemplate(${name})`;
56
+ TemplateWrapper.__bstage_meta__ = meta;
57
+ TemplateWrapper.__bstage_options__ = options;
58
+ TemplateWrapper.__bstage_inner__ = Component;
59
+ const wrapper = TemplateWrapper;
60
+ __bstage_registry__.add(wrapper);
61
+ return wrapper;
62
+ }
63
+ var ELEMENT_NAME_RE = /^[a-z][a-z0-9-]*-[a-z0-9-]*$/;
64
+ function validateElementName(name) {
65
+ if (!ELEMENT_NAME_RE.test(name)) {
66
+ throw new Error(
67
+ `createTemplate: \uC798\uBABB\uB41C name "${name}". Custom Element \uC2A4\uD399\uC0C1 \uC18C\uBB38\uC790\uB85C \uC2DC\uC791\uD558\uACE0 \uD558\uC774\uD508\uC744 1\uAC1C \uC774\uC0C1 \uD3EC\uD568\uD574\uC57C \uD558\uBA70, \uC18C\uBB38\uC790\xB7\uC22B\uC790\xB7\uD558\uC774\uD508\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uC608: "bmf-hello"`
68
+ );
69
+ }
70
+ }
71
+
72
+ // src/registerTemplate.ts
73
+ var import_react3 = require("react");
74
+ var import_client = require("react-dom/client");
75
+ var import_core = require("@bstage-sdk/core");
76
+
77
+ // src/BstageContext.tsx
78
+ var import_react2 = require("react");
79
+ var BstageContext = (0, import_react2.createContext)(null);
80
+ function useBstageContext() {
81
+ const ctx = (0, import_react2.useContext)(BstageContext);
82
+ if (!ctx) {
83
+ throw new Error("[bstage] useBstageContext must be used inside a bstage template");
84
+ }
85
+ return ctx;
86
+ }
87
+
88
+ // src/registerTemplate.ts
89
+ function ReadySignal({ host }) {
90
+ (0, import_react3.useEffect)(() => {
91
+ host.dispatchEvent(new CustomEvent("bstage:__ready__", { bubbles: false, composed: false }));
92
+ }, []);
93
+ return null;
94
+ }
95
+ var ReactAdapter = class {
96
+ constructor(options = {}) {
97
+ this.options = options;
98
+ this.root = null;
99
+ this.component = null;
100
+ this.contextValue = null;
101
+ this.host = null;
102
+ }
103
+ mount(component, container, props, bridge) {
104
+ this.component = component;
105
+ this.contextValue = { bridge };
106
+ this.host = bridge.getHost();
107
+ if (this.options.styles && container instanceof ShadowRoot) {
108
+ const style = document.createElement("style");
109
+ style.textContent = this.options.styles;
110
+ container.appendChild(style);
111
+ }
112
+ this.root = (0, import_client.createRoot)(container);
113
+ this.render(props);
114
+ }
115
+ update(props) {
116
+ this.render(props);
117
+ }
118
+ unmount() {
119
+ const root = this.root;
120
+ queueMicrotask(() => root?.unmount());
121
+ this.root = null;
122
+ this.component = null;
123
+ this.contextValue = null;
124
+ this.host = null;
125
+ }
126
+ render(props) {
127
+ if (!this.root || !this.component || !this.contextValue || !this.host) return;
128
+ this.root.render(
129
+ (0, import_react3.createElement)(
130
+ BstageContext.Provider,
131
+ { value: this.contextValue },
132
+ (0, import_react3.createElement)(this.component, props),
133
+ (0, import_react3.createElement)(ReadySignal, { host: this.host })
134
+ )
135
+ );
136
+ }
137
+ };
138
+ function registerTemplate(template) {
139
+ const meta = template.__bstage_meta__;
140
+ const options = template.__bstage_options__;
141
+ const Component = template.__bstage_inner__;
142
+ const tagName = meta.elementName;
143
+ const WebComponent = (0, import_core.createWebComponent)(
144
+ () => new ReactAdapter({ styles: options.styles }),
145
+ Component,
146
+ { ...options, framework: "react" }
147
+ );
148
+ if (!customElements.get(tagName)) {
149
+ customElements.define(tagName, WebComponent);
150
+ }
151
+ (0, import_core.announceElementName)(tagName);
152
+ return WebComponent;
153
+ }
154
+
155
+ // src/hooks/useNavigation.ts
156
+ var import_react4 = require("react");
157
+ function useNavigation() {
158
+ const ctx = (0, import_react4.useContext)(BstageContext);
159
+ const bridge = ctx?.bridge;
160
+ const navigate = (0, import_react4.useCallback)(
161
+ (path, params) => {
162
+ if (bridge) {
163
+ bridge.emit("navigate", { path, params });
164
+ } else {
165
+ const query = params ? "?" + new URLSearchParams(params).toString() : "";
166
+ window.location.href = path + query;
167
+ }
168
+ },
169
+ [bridge]
170
+ );
171
+ const goBack = (0, import_react4.useCallback)(() => {
172
+ if (bridge) {
173
+ bridge.emit("go-back", {});
174
+ } else {
175
+ window.history.back();
176
+ }
177
+ }, [bridge]);
178
+ const openExternal = (0, import_react4.useCallback)(
179
+ (url) => {
180
+ if (bridge) {
181
+ bridge.emit("open-external", { url });
182
+ } else {
183
+ window.open(url, "_blank");
184
+ }
185
+ },
186
+ [bridge]
187
+ );
188
+ return { navigate, goBack, openExternal };
189
+ }
190
+
191
+ // src/hooks/usePlatformEvent.ts
192
+ var import_react5 = require("react");
193
+ function usePlatformEvent(type, handler) {
194
+ const ctx = (0, import_react5.useContext)(BstageContext);
195
+ const bridge = ctx?.bridge;
196
+ const handlerRef = (0, import_react5.useRef)(handler);
197
+ handlerRef.current = handler;
198
+ (0, import_react5.useEffect)(() => {
199
+ if (!bridge) return;
200
+ return bridge.on(type, ((payload) => {
201
+ handlerRef.current(payload);
202
+ }));
203
+ }, [bridge, type]);
204
+ }
205
+
206
+ // src/hooks/useSlotContext.ts
207
+ var import_react6 = require("react");
208
+ function useSlotContext() {
209
+ const [context, setContext] = (0, import_react6.useState)();
210
+ usePlatformEvent("slot.context", (payload) => {
211
+ setContext(payload);
212
+ });
213
+ return context;
214
+ }
215
+
216
+ // src/hooks/useShadowStyle.ts
217
+ var import_react7 = require("react");
218
+ function useShadowStyle(css) {
219
+ const ref = (0, import_react7.useRef)(null);
220
+ const injected = (0, import_react7.useRef)(false);
221
+ (0, import_react7.useEffect)(() => {
222
+ if (injected.current || !ref.current) return;
223
+ const root = ref.current.getRootNode();
224
+ if (!(root instanceof ShadowRoot)) return;
225
+ const hash = hashString(css);
226
+ if (root.querySelector(`style[data-shadow-style="${hash}"]`)) return;
227
+ const style = document.createElement("style");
228
+ style.setAttribute("data-shadow-style", hash);
229
+ style.textContent = css;
230
+ root.appendChild(style);
231
+ injected.current = true;
232
+ });
233
+ return ref;
234
+ }
235
+ function hashString(str) {
236
+ let hash = 0;
237
+ for (let i = 0; i < str.length; i++) {
238
+ hash = Math.imul(31, hash) + str.charCodeAt(i) | 0;
239
+ }
240
+ return (hash >>> 0).toString(36);
241
+ }
242
+
243
+ // src/hooks/useLocale.ts
244
+ var import_react9 = require("react");
245
+ var import_core2 = require("@bstage-sdk/core");
246
+
247
+ // src/LocaleProvider.tsx
248
+ var import_react8 = require("react");
249
+ var LocaleTargetContext = (0, import_react8.createContext)(null);
250
+ function useLocaleTarget() {
251
+ const target = (0, import_react8.useContext)(LocaleTargetContext);
252
+ if (target === null) {
253
+ throw new Error(
254
+ "[bstage] \uB85C\uCF00\uC77C \uD6C5(useLocale/useMessages/useBstageTranslations)\uC740 <BstageLocaleProvider> \uC548\uC5D0\uC11C \uD638\uCD9C\uD574\uC57C \uD569\uB2C8\uB2E4."
255
+ );
256
+ }
257
+ return target;
258
+ }
259
+ function BstageLocaleProvider({
260
+ target = "user",
261
+ children
262
+ }) {
263
+ return (0, import_react8.createElement)(LocaleTargetContext.Provider, { value: target }, children);
264
+ }
265
+
266
+ // src/hooks/useLocale.ts
267
+ function useLocale() {
268
+ const target = useLocaleTarget();
269
+ const subscribe = (0, import_react9.useCallback)((onChange) => (0, import_core2.observeLocale)(onChange, target), [target]);
270
+ const getSnapshot = (0, import_react9.useCallback)(() => (0, import_core2.readLocale)(target), [target]);
271
+ const current = (0, import_react9.useSyncExternalStore)(subscribe, getSnapshot, () => import_core2.DEFAULT_LANGUAGE);
272
+ return { current };
273
+ }
274
+
275
+ // src/hooks/useMessages.ts
276
+ var import_core3 = require("@bstage-sdk/core");
277
+
278
+ // src/devWarn.ts
279
+ var warned = /* @__PURE__ */ new Set();
280
+ function devWarnOnce(dedupeKey, message) {
281
+ if (warned.has(dedupeKey)) return;
282
+ warned.add(dedupeKey);
283
+ console.warn(`[bstage] ${message}`);
284
+ }
285
+
286
+ // src/hooks/useMessages.ts
287
+ function interpolate(template, params) {
288
+ if (!params) return template;
289
+ return template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
290
+ const value = params[key];
291
+ return value === void 0 ? `{{${key}}}` : String(value);
292
+ });
293
+ }
294
+ function useMessages(messages) {
295
+ const { current } = useLocale();
296
+ return (key, params) => {
297
+ if (process.env.NODE_ENV !== "production" && typeof params === "string") {
298
+ devWarnOnce(
299
+ `msg-string-param:${String(key)}`,
300
+ `useMessages\uC758 t('${String(key)}', ...) 2\uBC88\uC9F8 \uC778\uC790\uB294 \uBCF4\uAC04 \uD30C\uB77C\uBBF8\uD130 \uAC1D\uCCB4\uC785\uB2C8\uB2E4. fallback \uBB38\uC790\uC5F4\uC740 \uBB34\uC2DC\uB429\uB2C8\uB2E4.`
301
+ );
302
+ }
303
+ const dict = messages[current] ?? messages[import_core3.DEFAULT_LANGUAGE] ?? Object.values(messages)[0] ?? {};
304
+ const template = dict[key] ?? key;
305
+ return interpolate(template, params);
306
+ };
307
+ }
308
+
309
+ // src/hooks/useBstageTranslations.ts
310
+ var import_react10 = require("react");
311
+ var import_core4 = require("@bstage-sdk/core");
312
+ var requiredDepth = /* @__PURE__ */ new Map();
313
+ function useBstageTranslations() {
314
+ const { current } = useLocale();
315
+ const target = useLocaleTarget();
316
+ const depthKey = `${target}|${current}`;
317
+ const [dicts, setDicts] = (0, import_react10.useState)();
318
+ const [depth, setDepth] = (0, import_react10.useState)(() => requiredDepth.get(depthKey) ?? 1);
319
+ const pendingRef = (0, import_react10.useRef)(false);
320
+ (0, import_react10.useEffect)(() => {
321
+ setDicts(void 0);
322
+ setDepth(requiredDepth.get(depthKey) ?? 1);
323
+ pendingRef.current = false;
324
+ }, [depthKey]);
325
+ (0, import_react10.useEffect)(() => {
326
+ let active = true;
327
+ const chain = (0, import_core4.resolveTranslationChain)(current).slice(0, depth);
328
+ Promise.all(chain.map((locale) => (0, import_core4.fetchTranslations)(locale, target).catch(() => ({})))).then((loaded) => {
329
+ if (!active) return;
330
+ setDicts(loaded);
331
+ pendingRef.current = false;
332
+ }).catch(() => {
333
+ if (active) setDicts([]);
334
+ });
335
+ return () => {
336
+ active = false;
337
+ };
338
+ }, [current, target, depth]);
339
+ const requestFallback = (0, import_react10.useCallback)(
340
+ (chainLength) => {
341
+ if (pendingRef.current) return;
342
+ pendingRef.current = true;
343
+ queueMicrotask(
344
+ () => setDepth((d) => {
345
+ if (d >= chainLength) return d;
346
+ const next = d + 1;
347
+ requiredDepth.set(depthKey, Math.max(requiredDepth.get(depthKey) ?? 1, next));
348
+ return next;
349
+ })
350
+ );
351
+ },
352
+ [depthKey]
353
+ );
354
+ const resolveRaw = (0, import_react10.useCallback)(
355
+ (key) => {
356
+ const resolved = dicts ? (0, import_core4.pickTranslation)(dicts, key) : void 0;
357
+ if (resolved !== void 0) return resolved;
358
+ if (dicts) {
359
+ const chain = (0, import_core4.resolveTranslationChain)(current);
360
+ if (dicts.length < chain.length) {
361
+ requestFallback(chain.length);
362
+ } else if (process.env.NODE_ENV !== "production") {
363
+ devWarnOnce(
364
+ `t-missing-key:${String(key)}`,
365
+ `'${String(key)}'\uB294 \uD50C\uB7AB\uD3FC \uBC88\uC5ED \uC0AC\uC804\uC5D0 \uC5C6\uB294 \uD0A4\uC785\uB2C8\uB2E4(\uC624\uD0C8\uC790\uC774\uAC70\uB098 useMessages \uB300\uC0C1\uC77C \uC218 \uC788\uC74C). \uD0A4 \uBB38\uC790\uC5F4\uC774 \uADF8\uB300\uB85C \uB80C\uB354\uB429\uB2C8\uB2E4.`
366
+ );
367
+ }
368
+ }
369
+ return void 0;
370
+ },
371
+ [dicts, current, requestFallback]
372
+ );
373
+ const t = (0, import_react10.useCallback)(
374
+ (key, params) => {
375
+ if (process.env.NODE_ENV !== "production") {
376
+ if (typeof params === "string") {
377
+ devWarnOnce(
378
+ `t-string-param:${String(key)}`,
379
+ `t('${String(key)}', ...)\uC758 2\uBC88\uC9F8 \uC778\uC790\uB294 \uBCF4\uAC04 \uD30C\uB77C\uBBF8\uD130 \uAC1D\uCCB4\uC785\uB2C8\uB2E4. fallback \uBB38\uC790\uC5F4\uC740 \uBB34\uC2DC\uB418\uACE0 \uD50C\uB7AB\uD3FC \uC0AC\uC804 \uAC12\uC774 \uB80C\uB354\uB429\uB2C8\uB2E4 \u2014 \uD15C\uD50C\uB9BF \uC790\uCCB4 \uBB38\uAD6C\uB294 useMessages\uB97C \uC4F0\uC138\uC694.`
380
+ );
381
+ }
382
+ }
383
+ const raw = resolveRaw(key);
384
+ if (process.env.NODE_ENV !== "production" && raw !== void 0 && /<\d+>/.test(raw)) {
385
+ devWarnOnce(
386
+ `t-rich-text:${String(key)}`,
387
+ `'${String(key)}'\uB294 \uB9AC\uCE58\uD14D\uC2A4\uD2B8(<0>\u2026</0>) \uBB38\uAD6C\uC785\uB2C8\uB2E4. t()\uB294 \uBB38\uC790\uC5F4\uC744 \uBC18\uD658\uD558\uBBC0\uB85C \uD0DC\uADF8\uAC00 \uAE00\uC790\uB85C \uBCF4\uC785\uB2C8\uB2E4 \u2014 tNode('${String(key)}', { tags: { 0: <a href="\u2026" /> } })\uB97C \uC4F0\uC138\uC694.`
388
+ );
389
+ }
390
+ return (0, import_core4.interpolateTranslation)(raw ?? key, params);
391
+ },
392
+ [resolveRaw]
393
+ );
394
+ const tNode = (0, import_react10.useCallback)(
395
+ (key, options) => {
396
+ const raw = resolveRaw(key) ?? key;
397
+ const tokens = (0, import_core4.parseRichText)(raw, options?.params);
398
+ return tokens.map((token, i) => {
399
+ if (token.type === "text") return token.value;
400
+ const element = options?.tags?.[token.index];
401
+ if (!element) {
402
+ if (process.env.NODE_ENV !== "production") {
403
+ devWarnOnce(
404
+ `tnode-missing-tag:${String(key)}:${token.index}`,
405
+ `'${String(key)}'\uC758 <${token.index}> \uD0DC\uADF8\uC5D0 \uB300\uC751\uD558\uB294 \uC5D8\uB9AC\uBA3C\uD2B8\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4 \u2014 tags: { ${token.index}: <a href="\u2026" /> }\uB97C \uB118\uAE30\uC138\uC694. \uC9C0\uAE08\uC740 \uB0B4\uC6A9\uB9CC \uB80C\uB354\uB429\uB2C8\uB2E4.`
406
+ );
407
+ }
408
+ return token.value;
409
+ }
410
+ return (0, import_react10.cloneElement)(element, { key: i }, token.value);
411
+ });
412
+ },
413
+ [resolveRaw]
414
+ );
415
+ return { current, t, tNode, ready: dicts !== void 0 };
416
+ }
417
+ // Annotate the CommonJS export names for ESM import in node:
418
+ 0 && (module.exports = {
419
+ BstageContext,
420
+ BstageLocaleProvider,
421
+ __bstage_registry__,
422
+ createTemplate,
423
+ registerTemplate,
424
+ useBstageContext,
425
+ useBstageTranslations,
426
+ useLocale,
427
+ useMessages,
428
+ useNavigation,
429
+ usePlatformEvent,
430
+ useShadowStyle,
431
+ useSlotContext
432
+ });