@contentstack/studio-registry 1.8.0 → 1.10.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.
Files changed (37) hide show
  1. package/dist/cjs/index.cjs +1096 -202
  2. package/dist/cjs/index.cjs.map +1 -1
  3. package/dist/esm/common/global-store.js +2 -0
  4. package/dist/esm/common/global-store.js.map +1 -1
  5. package/dist/esm/component-registry/registry-options-processor.js +75 -0
  6. package/dist/esm/component-registry/registry-options-processor.js.map +1 -1
  7. package/dist/esm/component-registry/registry.constant.js +0 -3
  8. package/dist/esm/component-registry/registry.constant.js.map +1 -1
  9. package/dist/esm/component-registry/registry.js +1 -27
  10. package/dist/esm/component-registry/registry.js.map +1 -1
  11. package/dist/esm/data-binder/cslp.js +8 -1
  12. package/dist/esm/data-binder/cslp.js.map +1 -1
  13. package/dist/esm/data-binder/retrieve-data.js +19 -32
  14. package/dist/esm/data-binder/retrieve-data.js.map +1 -1
  15. package/dist/esm/data-binder/retrieve-data.util.js +23 -5
  16. package/dist/esm/data-binder/retrieve-data.util.js.map +1 -1
  17. package/dist/esm/data-binder/state-binding.util.js +158 -0
  18. package/dist/esm/data-binder/state-binding.util.js.map +1 -0
  19. package/dist/esm/design-registry/design-token.js +5 -2
  20. package/dist/esm/design-registry/design-token.js.map +1 -1
  21. package/dist/esm/index.d.ts +488 -27
  22. package/dist/esm/index.js +6 -1
  23. package/dist/esm/index.js.map +1 -1
  24. package/dist/esm/state-store/action-props.util.js +42 -0
  25. package/dist/esm/state-store/action-props.util.js.map +1 -0
  26. package/dist/esm/state-store/function-registry.js +128 -0
  27. package/dist/esm/state-store/function-registry.js.map +1 -0
  28. package/dist/esm/state-store/public-api.js +109 -0
  29. package/dist/esm/state-store/public-api.js.map +1 -0
  30. package/dist/esm/state-store/singleton.js +27 -0
  31. package/dist/esm/state-store/singleton.js.map +1 -0
  32. package/dist/esm/state-store/state-store.js +384 -0
  33. package/dist/esm/state-store/state-store.js.map +1 -0
  34. package/package.json +9 -6
  35. package/LICENSE +0 -21
  36. package/dist/esm/utils/symbols.js +0 -12
  37. package/dist/esm/utils/symbols.js.map +0 -1
@@ -10,6 +10,22 @@ type PropBase<T extends NodePropType, V> = {
10
10
  defaultValue?: V;
11
11
  defaultValueHint?: string;
12
12
  helpText?: string;
13
+ /**
14
+ * Marks the prop as a design prop: its key must be a camelCase CSS property
15
+ * (e.g. `paddingInline`) and its values are CSS values for that property,
16
+ * editable per breakpoint in the Settings tab. The component does NOT
17
+ * receive the raw value — it receives a generated class name (media queries
18
+ * inside) under this prop and must apply it to an element of its choosing.
19
+ * Values live in `node.styles[propKey]`, never in `static_value`, and the
20
+ * prop is excluded from data resolution.
21
+ *
22
+ * Only `choice` (options as `{ label, value: <css value> }`) and `string`
23
+ * props may be marked; the flag is ignored with a console warning on other
24
+ * types, on non-CSS-property keys, and on reserved keys (`default`,
25
+ * `className`, `children`, `style`, `key`, `ref`, or a registered style
26
+ * group's key). `defaultValue` seeds the default breakpoint's value.
27
+ */
28
+ design?: boolean;
13
29
  /**
14
30
  * Validates the prop value. If the value is invalid, return a string with an error message.
15
31
  * @param currentValue - The current value of the prop.
@@ -102,6 +118,27 @@ type ObjectInput = PropBase<NodePropTypes["object"], Record<string, unknown>> &
102
118
  properties?: unknown;
103
119
  };
104
120
  type AnyProp = PropBase<NodePropTypes["any"], any>;
121
+ /**
122
+ * A registered Studio function reference — lets ANY component expose a
123
+ * behavior slot the user wires up in the Studio props panel.
124
+ *
125
+ * The Studio UI renders a dropdown of the app's `registerStudioFunctions`
126
+ * names; the chosen NAME is saved (static value). At render time the SDK
127
+ * swaps the name for a callable `(...args) => callStudioFunction(name, ...args)`,
128
+ * so the component simply invokes its prop:
129
+ *
130
+ * ```tsx
131
+ * registerComponent(Banner, {
132
+ * type: "promo-banner",
133
+ * props: { onCtaClick: { type: "action", displayName: "CTA Click Function" } },
134
+ * });
135
+ *
136
+ * function Banner({ onCtaClick }: { onCtaClick?: (...args: unknown[]) => unknown }) {
137
+ * return <button onClick={() => onCtaClick?.()}>Claim</button>;
138
+ * }
139
+ * ```
140
+ */
141
+ type ActionProp = PropBase<NodePropTypes["action"], string>;
105
142
  /**
106
143
  * Use `json_rte` for props bound to a **Contentstack JSON Rich-Text Editor field**.
107
144
  *
@@ -150,8 +187,8 @@ type PlainTextProp = PropBase<NodePropTypes["plaintext"], string> & {
150
187
  control?: "default" | "large";
151
188
  placeholder?: string;
152
189
  };
153
- type PropsWithNoOptionsRequired = StringProp | BooleanProp | NumberProp | DateStringProp | HrefProp | ImageUrlProp | ObjectProp | ArrayProp | SlotProp;
154
- type PropInput = StringProp | BooleanProp | NumberProp | DateStringProp | HrefProp | ImageUrlProp | ObjectProp | ArrayProp | SlotProp | ChoiceProp | AnyProp | JsonRTEProp | PlainTextProp;
190
+ type PropsWithNoOptionsRequired = StringProp | BooleanProp | NumberProp | DateStringProp | HrefProp | ImageUrlProp | ObjectProp | ArrayProp | SlotProp | ActionProp;
191
+ type PropInput = StringProp | BooleanProp | NumberProp | DateStringProp | HrefProp | ImageUrlProp | ObjectProp | ArrayProp | SlotProp | ChoiceProp | AnyProp | JsonRTEProp | PlainTextProp | ActionProp;
155
192
  type PropTypeOfNoOptionsRequired = PropsWithNoOptionsRequired["type"];
156
193
  type PropType = PropInput["type"];
157
194
  type Props = {
@@ -177,7 +214,6 @@ declare const DATA_SOURCES: {
177
214
  readonly CONTENTSTACK: "contentstack";
178
215
  readonly REPEATER: "repeater";
179
216
  readonly QUERY: "contentstack_queries";
180
- readonly SYMBOL_PROPS: "symbol_props";
181
217
  };
182
218
  declare const INTERNAL_COMPONENT_SECTIONS: {
183
219
  readonly BASIC: "Basic";
@@ -187,10 +223,9 @@ declare const INTERNAL_COMPONENT_SECTIONS: {
187
223
  readonly ADVANCED: "Advanced";
188
224
  readonly REGISTERED_COMPONENTS: "Registered Components";
189
225
  readonly HTML_ELEMENT: "HTML Elements";
190
- readonly SYMBOL: "Symbols";
191
226
  readonly SECTION_COMPOSITION: "Sections";
192
227
  };
193
- declare const INTERNAL_SECTIONS: ("Basic" | "Media" | "Container" | "Smart Containers" | "Advanced" | "Registered Components" | "HTML Elements" | "Symbols" | "Sections")[];
228
+ declare const INTERNAL_SECTIONS: ("Basic" | "Media" | "Container" | "Smart Containers" | "Advanced" | "Registered Components" | "HTML Elements" | "Sections")[];
194
229
  declare const STYLE_SECTIONS_OPTIONS: readonly ["class", "size", "spacing", "position", "visibility", "layout", "typography", "transform", "media", "background", "shadow", "effect", "overflow", "border", "responsive"];
195
230
  /**
196
231
  * The style group is the group of the style sections options.
@@ -222,7 +257,6 @@ declare const INTERNAL_COMPONENTS_NAMES: {
222
257
  readonly ROWS: "vstack";
223
258
  readonly REPEATER: "repeater";
224
259
  readonly CONDITION_BLOCK: "condition-block";
225
- readonly SYMBOL: "symbol";
226
260
  readonly FRAGMENT: "fragment";
227
261
  readonly SECTION_SLOT: "section-slot";
228
262
  readonly HTML_ELEMENT: "html-element";
@@ -292,11 +326,41 @@ interface RegisterComponentSchemaInput<C = unknown> {
292
326
  */
293
327
  thumbnailUrl?: string;
294
328
  /**
295
- * Controls what styles will be provided to the component.
296
- * The styles will be available under the key you define.
297
- * If you set the values against the `default` key, it will be
298
- * passed to the default component prop.
299
- * TODO: add a document link to explain the previous statement.
329
+ * Declares the style groups Studio offers for this component. Each key is one
330
+ * group, shown as its own entry in the Design panel.
331
+ *
332
+ * Every group is compiled at render time into a single CSS class string, and
333
+ * delivered to the component as a prop:
334
+ *
335
+ * - the `default` group arrives as `className`
336
+ * - every other group arrives as a prop named exactly like the group key
337
+ *
338
+ * The component has to apply what it is given. A group whose class never
339
+ * reaches the DOM cannot be styled — the Design panel edits are stored on the
340
+ * node, but nothing renders.
341
+ *
342
+ * @example
343
+ * ```tsx
344
+ * registerComponent({
345
+ * type: "card",
346
+ * component: Card,
347
+ * styles: {
348
+ * default: { styleSections: ["block"] },
349
+ * title: { displayName: "Title", styleSections: ["text"] },
350
+ * },
351
+ * });
352
+ *
353
+ * function Card({ className, title, heading }) {
354
+ * return (
355
+ * <div className={className}>
356
+ * <h2 className={title}>{heading}</h2>
357
+ * </div>
358
+ * );
359
+ * }
360
+ * ```
361
+ *
362
+ * Do not name a group after a registered prop — props are applied last and
363
+ * would overwrite the group's classes.
300
364
  */
301
365
  styles?: {
302
366
  [section: string]: StyleGroupOptions;
@@ -323,7 +387,7 @@ interface RegisterComponentSchemaInput<C = unknown> {
323
387
  */
324
388
  layerIcon?: LayerIcon;
325
389
  /**
326
- * This can be used to store extra metadata for components. For eg for symbols we can store uid here.
390
+ * This can be used to store extra metadata for components. For eg for sections we can store uid here.
327
391
  */
328
392
  metadata?: Record<string, unknown>;
329
393
  }
@@ -344,7 +408,7 @@ interface RegisterComponentSchema<C> extends Required<Omit<RegisterComponentSche
344
408
  [key: string]: PropInput;
345
409
  };
346
410
  }
347
- type Registry = "internal" | "user-defined" | "symbols";
411
+ type Registry = "internal" | "user-defined" | "sections";
348
412
  type RegisterComponentOptionsInput<C = unknown> = Omit<RegisterComponentSchemaInput<C>, "icon">;
349
413
  type RegisterInternalComponentOptionsInput<C = unknown> = RegisterComponentSchemaInput<C>;
350
414
  type InternalComponentRegistryOptions = {
@@ -355,11 +419,14 @@ type StyleSectionCategoriesOptions = keyof typeof STYLE_SECTION_CATEGORIES;
355
419
  type StyleSections = (StyleSectionOptions | StyleSectionCategoriesOptions)[] | "all" | "none";
356
420
  interface StyleGroupOptions {
357
421
  /**
358
- * The classes will be sent to the component.
422
+ * Classes this group always carries. They are merged into the class string
423
+ * the group delivers to the component.
359
424
  */
360
425
  defaultClasses?: DesignClassValue[];
361
426
  /**
362
- *
427
+ * The styles this group starts with. Studio writes them onto the node when
428
+ * the component is added, so authors can then change them from the Design
429
+ * panel.
363
430
  */
364
431
  defaultStyles?: Properties;
365
432
  /**
@@ -419,11 +486,6 @@ declare class ComponentRegistry<C> {
419
486
  * @throws {Error} If a component name is missing.
420
487
  */
421
488
  registerInternalComponent(componentConfigs: RegisterInternalComponentOptionsInput<C>[], options?: InternalComponentRegistryOptions): void;
422
- /**
423
- * Registers list of symbol components in the component registry
424
- * @param componentsConfigs
425
- */
426
- registerSymbolComponent(componentsConfigs: RegisterInternalComponentOptionsInput<C>[]): void;
427
489
  registerSectionComponent(componentsConfigs: RegisterInternalComponentOptionsInput<C>[]): void;
428
490
  /**
429
491
  * Registers one or more components in the component registry.
@@ -1303,21 +1365,24 @@ interface SectionScopedDataSources {
1303
1365
  contentstack: Record<string, any>;
1304
1366
  contentstack_queries: Record<string, any>;
1305
1367
  static_value?: Record<string, unknown>;
1306
- page: DataSources;
1368
+ page?: DataSources;
1307
1369
  repeater?: Record<string, {
1308
1370
  context: unknown;
1309
1371
  }>;
1310
1372
  parentRepeaterUID?: string | null;
1311
1373
  selectedField?: string;
1312
1374
  uidRemapping?: Record<string, string>;
1375
+ cardinality?: "collection" | "single";
1313
1376
  componentPropsFallback?: Record<string, unknown>;
1377
+ fetchRootKey?: string;
1378
+ fetchRootPrefix?: string[];
1314
1379
  }
1315
1380
  interface StudioSpecData {
1316
1381
  dataSources: DataSources;
1317
1382
  static_value: StaticValue;
1318
- symbol_props?: Record<string, any>;
1319
1383
  component_props?: Record<string, any>;
1320
1384
  section_scoped_data?: Record<string, SectionScopedDataSources>;
1385
+ page_data_sources?: DataSources;
1321
1386
  }
1322
1387
  interface ComposableStudioData extends StudioSpecData {
1323
1388
  component_props: Record<string, any> | undefined;
@@ -1462,6 +1527,51 @@ declare const getCslpTag: ({ bindedField, data, }: {
1462
1527
  data: ComposableStudioData;
1463
1528
  }) => any;
1464
1529
 
1530
+ declare function collectStateBindingKeys(node: (Pick<Node, "props"> & {
1531
+ metadata?: {
1532
+ bindings?: Record<string, unknown>;
1533
+ };
1534
+ }) | undefined | null): string[];
1535
+ /**
1536
+ * Snapshot of the given declared state keys — `{ key: currentValue }` —
1537
+ * merged by the renderer into `data.component_props` before prop resolution
1538
+ * so the existing `component_props` path machinery (fallbacks, type
1539
+ * validation, editor error badges) resolves state values unchanged.
1540
+ *
1541
+ * Keys whose current value is `undefined` (declared but unset, no default) are
1542
+ * OMITTED — spreading `{key: undefined}` over `component_props` would wipe an
1543
+ * external/authored value of the same name, silently losing server content.
1544
+ */
1545
+ declare function getStateValuesFor(keys: readonly string[]): Record<string, unknown>;
1546
+ /**
1547
+ * Like getStateValuesFor but reads ONLY the declared defaults, never the live
1548
+ * backend value. Used as the server / hydration baseline so SSR and the client
1549
+ * hydration render agree (a persisted local/session value read on the client
1550
+ * but not the server would otherwise be a hydration mismatch). Undefined
1551
+ * defaults are omitted for the same reason as getStateValuesFor.
1552
+ */
1553
+ declare function getStateDefaultsFor(keys: readonly string[]): Record<string, unknown>;
1554
+ /**
1555
+ * The registered studio FUNCTION a node is bound to, if any.
1556
+ *
1557
+ * Authors assign behavior from the Data Picker's Component Props section
1558
+ * (functions are listed under the state variables): the picker writes an
1559
+ * ordinary `component_props` binding — on an attribute (`metadata.bindings`,
1560
+ * e.g. `attrs.id`) or a prop — whose key is a registered function NAME.
1561
+ * Because functions and data share the source, "is it a function?" is decided
1562
+ * right here: key ∈ function registry → behavior, otherwise it stays a plain
1563
+ * data binding and is ignored by this helper.
1564
+ *
1565
+ * The renderer attaches the returned name as the node's click handler
1566
+ * (`callStudioFunction(name)`), which is what makes assignment work for ANY
1567
+ * component with zero prop declarations.
1568
+ */
1569
+ declare function getNodeBoundFunctionName(node: (Pick<Node, "props"> & {
1570
+ metadata?: {
1571
+ bindings?: Record<string, unknown>;
1572
+ };
1573
+ }) | undefined | null): string | undefined;
1574
+
1465
1575
  interface Breakpoint {
1466
1576
  id: string;
1467
1577
  displayName: string;
@@ -1490,9 +1600,6 @@ declare class BreakpointRegistry {
1490
1600
  processBreakpoints(breakpoints: BreakpointInput): Breakpoint[];
1491
1601
  }
1492
1602
 
1493
- declare const getSymbolUIDFromNode: (symbol: Node) => string;
1494
- declare const getSymbolUIDFromUID: (uid: string) => string;
1495
-
1496
1603
  /**
1497
1604
  * Extracts the composition UID from a section-composition node's metadata.
1498
1605
  * Used to resolve section references to their actual composition identifiers.
@@ -1502,6 +1609,358 @@ declare const getSymbolUIDFromUID: (uid: string) => string;
1502
1609
  */
1503
1610
  declare const getSectionUIDFromNode: (section: Node) => any;
1504
1611
 
1612
+ /**
1613
+ * Type of a declared state variable. Mirrors the bindable prop types the
1614
+ * Data Picker understands so a declared variable can be offered for binding
1615
+ * inside the existing "External Data" (component_props) source.
1616
+ */
1617
+ type StateVariableType = "string" | "number" | "boolean" | "choice" | "array" | "object";
1618
+ /**
1619
+ * A state variable declared either globally (SDK init `state.variables`) or
1620
+ * at module scope via `registerComponentStateVariable`. Declared variables are the ONLY
1621
+ * ones surfaced to authors for binding; ad-hoc keys used with
1622
+ * `useStudioState("some_key")` remain code-only.
1623
+ */
1624
+ interface StateVariableDef {
1625
+ type: StateVariableType;
1626
+ defaultValue?: unknown;
1627
+ /** For `type: "choice"` — the allowed values. */
1628
+ options?: string[];
1629
+ }
1630
+ /**
1631
+ * WHERE shared state is persisted:
1632
+ * - `"session"` — built-in sessionStorage store (DEFAULT when `state` is
1633
+ * configured without `storage` and without custom functions): survives
1634
+ * reloads and hard navigations within the tab, cleared when it closes.
1635
+ * - `"local"` — built-in localStorage store: also survives across visits.
1636
+ * - `"custom"` — Bring Your Own Store: `getState`/`setState` required.
1637
+ */
1638
+ type StudioStateStorage = "local" | "session" | "custom";
1639
+ /**
1640
+ * User-supplied state integration — the "Bring Your Own State" contract.
1641
+ *
1642
+ * Pick a storage option via `storage` — `"local"` / `"session"` use built-in
1643
+ * web-storage stores (no functions needed); `"custom"` delegates to the
1644
+ * user's own store (Redux, Zustand, signals, a plain object…) via
1645
+ * `getState`/`setState`. Omitting `storage`: custom when the functions are
1646
+ * provided, otherwise the built-in SESSION store. Omitting `state` entirely
1647
+ * keeps the SDK's internal in-memory Map (fully backward compatible).
1648
+ */
1649
+ interface StudioStateConfig {
1650
+ /** Storage option — see StudioStateStorage. */
1651
+ storage?: StudioStateStorage;
1652
+ /** Web-storage key for the built-in stores. Default: "cs-studio:state". */
1653
+ storageKey?: string;
1654
+ /** Read a value from the user's store. Required for `storage: "custom"`. */
1655
+ getState?: (key: string) => unknown;
1656
+ /** Write a value to the user's store. Required for `storage: "custom"`. */
1657
+ setState?: (key: string, value: unknown) => void;
1658
+ /**
1659
+ * Optional per-key change notification from the user's store. Lets
1660
+ * mutations that happen OUTSIDE Studio (e.g. a Redux dispatch elsewhere in
1661
+ * the app) propagate into Studio-bound components. Returns an unsubscribe.
1662
+ */
1663
+ subscribe?: (key: string, listener: () => void) => (() => void) | void;
1664
+ /** Author-bindable state variables declared at init. */
1665
+ variables?: Record<string, StateVariableDef>;
1666
+ }
1667
+ /**
1668
+ * WHERE a variable declaration came from — its priority tier.
1669
+ * `component` (registerComponentStateVariable at component module scope) deliberately
1670
+ * OVERRIDES `init` (SDK init `state.variables`), deterministically and
1671
+ * regardless of module evaluation order. Same-tier re-declarations keep the
1672
+ * first definition. Runtime `set` values always beat declared defaults.
1673
+ */
1674
+ type StateVariableTier = "init" | "component";
1675
+ type StateUnsubscribe = () => void;
1676
+ type StateUpdater<T = unknown> = T | ((prev: T | undefined) => T);
1677
+
1678
+ /**
1679
+ * Page-global shared state store — the "Bring Your Own State" (BYOS) core.
1680
+ *
1681
+ * Delegates reads/writes to the user's `getState`/`setState` when configured
1682
+ * (Redux, Zustand, plain object, anything), otherwise falls back to an
1683
+ * internal Map. Reactivity is per-key: `set("cart")` notifies ONLY listeners
1684
+ * subscribed to `"cart"`, so unrelated components never re-render.
1685
+ *
1686
+ * One instance per JS runtime via the globalThis registry slot (see
1687
+ * `singleton.ts`) — every surface (components, sections, templates, custom
1688
+ * code) reads and writes the same store.
1689
+ *
1690
+ * SSR: `set` is a no-op with a dev warning (a mutable process-wide store
1691
+ * would leak state across requests); `get` still delegates so a
1692
+ * server-appropriate `getState` (e.g. request-scoped values) works, falling
1693
+ * back to declared defaults.
1694
+ */
1695
+ declare class StudioStateStore {
1696
+ private userConfig;
1697
+ private internal;
1698
+ private listeners;
1699
+ private variables;
1700
+ /** Priority tier each declaration came from (see StateVariableTier). */
1701
+ private variableTiers;
1702
+ /** Fired when the DECLARED variable set changes (declare/configure/reset). */
1703
+ private variableListeners;
1704
+ /** One bridge subscription per key into the user's own store. */
1705
+ private externalUnsubs;
1706
+ private warnedServerSet;
1707
+ /**
1708
+ * Wire the state backend + init-declared variables. Called once from SDK
1709
+ * init; calling again replaces the config (HMR-safe — variables merge,
1710
+ * they don't reset).
1711
+ *
1712
+ * Storage resolution (see StudioStateStorage):
1713
+ * - `storage: "custom"` → user's getState/setState (required).
1714
+ * - `storage: "local"` → built-in localStorage store.
1715
+ * - `storage: "session"` → built-in sessionStorage store.
1716
+ * - omitted → custom when getState+setState are provided,
1717
+ * otherwise the built-in SESSION store.
1718
+ */
1719
+ configure(config: StudioStateConfig): void;
1720
+ /**
1721
+ * Open a single bridge subscription from the user's own store into this
1722
+ * store's per-key listeners, so mutations made OUTSIDE Studio propagate in.
1723
+ * Idempotent and safe to call from both `subscribe` (first listener) and
1724
+ * `configure` (backend arrived/changed after listeners already existed).
1725
+ */
1726
+ private ensureExternalBridge;
1727
+ isConfigured(): boolean;
1728
+ /**
1729
+ * Register an author-bindable variable.
1730
+ *
1731
+ * Priority: a `component`-tier declaration (registerComponentStateVariable at component
1732
+ * module scope) OVERRIDES an `init`-tier one (SDK init `state.variables`)
1733
+ * for the same key — deterministically, whichever loads first. An init
1734
+ * declaration never overrides a component one; it only fills keys no
1735
+ * component declared. Same-tier re-declarations (module reload, repeated
1736
+ * imports) keep the first definition and dev-warn only when the type
1737
+ * conflicts. Runtime `set` values always beat declared defaults.
1738
+ */
1739
+ declareVariable(key: string, def: StateVariableDef, tier?: StateVariableTier): void;
1740
+ /** All declared (author-bindable) variables. */
1741
+ getVariables(): Record<string, StateVariableDef>;
1742
+ /**
1743
+ * Subscribe to declared-variable-set changes. The SDK's Studio bridge uses
1744
+ * this to push the fresh values snapshot to the Data Picker — apps declare
1745
+ * variables from lazily-imported init code, typically AFTER the component
1746
+ * registry synced, so a one-shot pull at sync time reads an empty set.
1747
+ */
1748
+ subscribeVariablesChanged(listener: () => void): StateUnsubscribe;
1749
+ private notifyVariablesChanged;
1750
+ isDeclared(key: string): boolean;
1751
+ /**
1752
+ * The declared default for a key, ignoring any live backend value. This is
1753
+ * the server / hydration baseline: SSR and the client's hydration render
1754
+ * must agree, so state-bound content renders the default on both and only
1755
+ * switches to a persisted/live value AFTER hydration.
1756
+ */
1757
+ getDeclaredDefault<T = unknown>(key: string): T | undefined;
1758
+ /** Raw backing value with NO declared-default fallback (undefined if unset). */
1759
+ private readRaw;
1760
+ get<T = unknown>(key: string): T | undefined;
1761
+ set<T = unknown>(key: string, next: StateUpdater<T>): void;
1762
+ /**
1763
+ * Per-key subscription. Returns an unsubscribe. When the user supplied
1764
+ * their own `subscribe`, a single bridge per key is also registered so
1765
+ * store mutations made OUTSIDE Studio propagate into Studio listeners.
1766
+ */
1767
+ subscribe(key: string, listener: () => void): StateUnsubscribe;
1768
+ private notify;
1769
+ /**
1770
+ * Soft reset for hosts that want per-page state on a client-side route
1771
+ * change (this is what the public `studioState.reset()` calls). Clears the
1772
+ * SDK-owned internal values and wakes every subscriber to re-read — but
1773
+ * deliberately KEEPS the wired backend, the declared variables, and all live
1774
+ * subscriptions. Tearing those down here (the previous behavior) disconnected
1775
+ * a configured custom store, wiped every declaration, and froze every still-
1776
+ * mounted `useStudioState`. For a full teardown (tests / HMR) use `resetAll`.
1777
+ *
1778
+ * A configured custom or web-storage backend owns its own values and is left
1779
+ * intact — the host resets its own store if it wants those cleared too.
1780
+ */
1781
+ reset(): void;
1782
+ /**
1783
+ * Full teardown — internal values, declarations, config, listeners, and
1784
+ * external bridges. For tests and HMR (the singleton drop), NOT for
1785
+ * route-change resets (see `reset`).
1786
+ */
1787
+ resetAll(): void;
1788
+ }
1789
+
1790
+ /**
1791
+ * Lazily create (or reuse) the page-global StudioStateStore in the SDK's
1792
+ * versioned globalThis slot. Same pattern as the component/design registries
1793
+ * — survives Next.js RSC/client module-graph splits so every surface talks
1794
+ * to the same store instance.
1795
+ */
1796
+ declare function getStateStoreInstance(): StudioStateStore;
1797
+ /** Test-only: drop the singleton so the next access builds a fresh store. */
1798
+ declare function resetStateStoreInstance(): void;
1799
+
1800
+ /**
1801
+ * Declare an author-bindable state variable at component/section module
1802
+ * scope — the "component-declared" tier. Call at module load time (top of
1803
+ * the file, next to the component definition):
1804
+ *
1805
+ * ```ts
1806
+ * registerComponentStateVariable("cart:filter", { type: "string", defaultValue: "" });
1807
+ *
1808
+ * export function CartFilter() {
1809
+ * const [filter, setFilter] = useStudioState<string>("cart:filter");
1810
+ * ...
1811
+ * }
1812
+ * ```
1813
+ *
1814
+ * Declared variables appear for binding inside the existing External Data
1815
+ * source; undeclared keys stay code-only (ad-hoc tier).
1816
+ *
1817
+ * Priority: component-level declarations WIN over the same key declared
1818
+ * globally at init (`state.variables`) — deterministically, regardless of
1819
+ * which module evaluated first. The global declaration is used only for keys
1820
+ * no component declared. Runtime `set` values always beat declared defaults.
1821
+ */
1822
+ declare function registerComponentStateVariable(key: string, options: StateVariableDef): void;
1823
+ /**
1824
+ * Imperative access to the shared state store — for custom user code outside
1825
+ * React (event handlers, analytics glue, business logic):
1826
+ *
1827
+ * ```ts
1828
+ * import { studioState } from "@contentstack/studio-react";
1829
+ *
1830
+ * studioState.set("cart:count", (prev) => (prev ?? 0) + 1);
1831
+ * const count = studioState.get<number>("cart:count");
1832
+ * const stop = studioState.subscribe("cart:count", () => console.log("changed"));
1833
+ * ```
1834
+ *
1835
+ * Same store instance the `useStudioState` hook and author bindings use —
1836
+ * one source of truth across components, sections, templates, and code.
1837
+ */
1838
+ /**
1839
+ * Snapshot of every DECLARED state variable with its CURRENT value —
1840
+ * `[{ key, value }]`. This is what the Studio Data Picker lists under
1841
+ * Component Props so authors can bind the values the app made available
1842
+ * (init `state.variables`, `registerComponentStateVariable`) — e.g. `price → 2999`.
1843
+ *
1844
+ * Only declared variables are enumerable: BYOS user stores expose key-based
1845
+ * `getState` with no key listing, so ad-hoc (code-only) keys can't be swept.
1846
+ */
1847
+ declare function getStudioStateSnapshot(): Array<{
1848
+ key: string;
1849
+ value: unknown;
1850
+ }>;
1851
+ /**
1852
+ * Subscribe to declared-variable-set changes on the page-global store —
1853
+ * passthrough for the Studio bridge (see StudioStateStore.subscribeVariablesChanged).
1854
+ */
1855
+ declare function subscribeStudioStateVariablesChanged(listener: () => void): StateUnsubscribe;
1856
+ declare const studioState: {
1857
+ get<T = unknown>(key: string): T | undefined;
1858
+ set<T = unknown>(key: string, next: StateUpdater<T>): void;
1859
+ subscribe(key: string, listener: () => void): StateUnsubscribe;
1860
+ /** Clear all state — call on client-side route change if you want per-page state. */
1861
+ reset(): void;
1862
+ };
1863
+ /**
1864
+ * Declare a SET of variables at the INIT tier — same priority as SDK init
1865
+ * `state.variables`, so later component-level `registerComponentStateVariable` calls
1866
+ * still override them.
1867
+ *
1868
+ * Purpose: SSR hydration alignment. The server declares variables at module
1869
+ * scope (server init file), but apps typically run the CLIENT init from a
1870
+ * lazily-imported module — AFTER hydration. State-bound nodes then hydrate
1871
+ * against undeclared keys and mismatch the server HTML. Import a tiny module
1872
+ * that calls this at module scope (e.g. from _app) so declarations exist on
1873
+ * the client BEFORE hydration:
1874
+ *
1875
+ * ```ts
1876
+ * // lib/register-state-variables.ts — imported statically by _app
1877
+ * registerGlobalStateVariables(studioStateConfig.variables ?? {});
1878
+ * ```
1879
+ */
1880
+ declare function registerGlobalStateVariables(variables: Record<string, StateVariableDef>): void;
1881
+
1882
+ /**
1883
+ * Context handed to every registered studio function — the same shared state
1884
+ * the `useStudioState` hook and author bindings use. Functions communicate
1885
+ * with components exclusively through this state: a `ctx.set` re-renders
1886
+ * every component bound to that key, wherever it lives.
1887
+ */
1888
+ interface StudioFunctionCtx {
1889
+ get<T = unknown>(key: string): T | undefined;
1890
+ set<T = unknown>(key: string, next: StateUpdater<T>): void;
1891
+ subscribe(key: string, listener: () => void): StateUnsubscribe;
1892
+ }
1893
+ /**
1894
+ * A user-registered custom function. `args` is the primary payload the caller
1895
+ * passed to `callStudioFunction` (e.g. `{ sku: "X1" }` from a button click).
1896
+ * Additional positional arguments — e.g. an action-prop callback invoked as
1897
+ * `onSelect(id, meta)` — are forwarded verbatim as `rest`, so nothing is
1898
+ * dropped between the component call and the function.
1899
+ */
1900
+ type StudioFunction = (ctx: StudioFunctionCtx, args?: Record<string, unknown>, ...rest: unknown[]) => unknown | Promise<unknown>;
1901
+ /**
1902
+ * Subscribe to registry changes (functions added / reset). Used by the SDK's
1903
+ * Studio bridge to push the fresh name list to the Studio props panel whenever
1904
+ * the app registers functions — regardless of whether that happens before or
1905
+ * after the component registry sync.
1906
+ */
1907
+ declare function subscribeStudioFunctionsChanged(listener: () => void): () => void;
1908
+ /**
1909
+ * Register named custom functions — the app's business logic that components
1910
+ * invoke by NAME. Call as many times as you like (e.g. one call per feature
1911
+ * module); registrations MERGE. Re-registering an existing name overwrites it
1912
+ * with a dev warning (supports HMR).
1913
+ *
1914
+ * ```ts
1915
+ * registerStudioFunctions({
1916
+ * "cart:add": (ctx, args) => {
1917
+ * ctx.set("cart:count", (prev) => (prev ?? 0) + 1);
1918
+ * ctx.set("cart:last_added", args?.sku ?? "");
1919
+ * },
1920
+ * "coupon:apply": (ctx, args) => {
1921
+ * const discounts = { SAVE10: 10, SAVE20: 20 };
1922
+ * ctx.set("checkout:discount", discounts[args?.code] ?? 0);
1923
+ * },
1924
+ * });
1925
+ * ```
1926
+ */
1927
+ declare function registerStudioFunctions(functions: Record<string, StudioFunction>): void;
1928
+ /** Names of every registered function — for debugging / future picker UI. */
1929
+ declare function getStudioFunctionNames(): string[];
1930
+ /**
1931
+ * Invoke a registered function by name from ANY component or code.
1932
+ *
1933
+ * ```ts
1934
+ * <button onClick={() => callStudioFunction("cart:add", { sku })}>Add</button>
1935
+ * ```
1936
+ *
1937
+ * Never throws into the UI: a missing name warns and returns undefined; sync
1938
+ * throws and async rejections are caught and logged. The function receives
1939
+ * the shared-state ctx as its first argument.
1940
+ */
1941
+ declare function callStudioFunction(name: string, ...args: unknown[]): unknown;
1942
+ /** Test-only: clear all registered functions. */
1943
+ declare function resetStudioFunctions(): void;
1944
+
1945
+ /**
1946
+ * Swap resolved `action` props (registered function NAMES saved from the
1947
+ * Studio props panel) for real callables before the props reach the
1948
+ * component. Runs in both renderers (live + canvas) right after
1949
+ * `retrievePropValue`, so ANY component — SDK basic or app-registered —
1950
+ * that declares a `{ type: "action" }` prop receives an invokable function:
1951
+ *
1952
+ * ```tsx
1953
+ * function Card({ onBuy }: { onBuy?: (...args: unknown[]) => unknown }) {
1954
+ * return <button onClick={() => onBuy?.({ sku: "X1" })}>Buy</button>;
1955
+ * }
1956
+ * ```
1957
+ *
1958
+ * An unset/empty selection resolves to `undefined` (component can feature-
1959
+ * detect); a missing function name is contained inside `callStudioFunction`
1960
+ * (warn, no crash). Non-action props pass through untouched.
1961
+ */
1962
+ declare function wrapActionProps<T extends Record<string, unknown>>(componentProps: Props | undefined, resolvedProps: T): T;
1963
+
1505
1964
  /**
1506
1965
  * Shape of the slot we own on globalThis. Each field is lazily initialized by
1507
1966
  * the corresponding `get*Instance()` helper; storing `null` keeps the slot
@@ -1511,6 +1970,8 @@ interface GlobalStudioStore {
1511
1970
  componentRegistry: unknown | null;
1512
1971
  designRegistry: unknown | null;
1513
1972
  breakpointManager: unknown | null;
1973
+ stateStore: unknown | null;
1974
+ functionRegistry: unknown | null;
1514
1975
  }
1515
1976
  /**
1516
1977
  * Returns the SDK's versioned slot on globalThis, creating it on first call.
@@ -1528,5 +1989,5 @@ declare function getGlobalStudioStore(): GlobalStudioStore;
1528
1989
  */
1529
1990
  declare function resetGlobalStudioStore(): void;
1530
1991
 
1531
- export { ALLOWED_DESIGN_VALUES_LEVELS, BUILT_IN_COMPONENTS, BreakpointRegistry, ComponentRegistry, DATA_SOURCES, DATA_SOURCES_PREFIX, DEFAULT_DESIGN_TOKENS, DesignRegistry, INTERNAL_COMPONENTS_NAMES, INTERNAL_COMPONENT_SECTIONS, INTERNAL_SECTIONS, JSONRTERegistry, STYLE_SECTIONS_OPTIONS, STYLE_SECTION_CATEGORIES, SYSTEM_COMPONENTS, clearReportedBindingErrorsForNode, convertBindingPath, getBindingString, getComponentRegistryInstance, getCslpPath, getCslpTag, getDataType, getDefaultPropStaticValue, getDesignClassesNames, getDesignRegistryInstance, getFlattenedData, getGlobalStudioStore, getPlaceHolderComponent, getRepeaterBinding, getRepeaterContextPath, getSectionUIDFromNode, getSlotData, getSymbolUIDFromNode, getSymbolUIDFromUID, hasComponentRegistryInstance, hasDesignRegistryInstance, isDataMatchingPropType, isKnownType, normalizeSingleSelectChoiceValue, resetComponentRegistryInstance, resetDesignRegistryInstance, resetGlobalStudioStore, resolveMetadataBindings, retrievePropValue };
1532
- export type { AllowedDesignValues, AllowedDesignValuesLevel, AnyProp, ArrayProp, BooleanProp, Breakpoint, BreakpointInput, CSBindingPath, CSDataSources, ChoiceProp, ComponentRegistryOptions, ComponentType, ComposableStudioData, ContentstackBindingValue, CssVariablesToDesignTokens, CssVariablesToValue, DataSourceItem, DataSources, DateStringProp, DefaultBreakpoint, DesignClassValue, DesignClasses, DesignClassesInput, DesignClassesNames, DesignTokenCssVariable, DesignTokens, DesignTokensInput, DesignTokensInputKeys, DesignTokensOptions, DesignTokensOptionsInput, GetSlots, GetSlotsParams, GlobalDesignTokens, GlobalStudioStore, HrefProp, ICSEntryReference, ImageUrlProp, InternalComponentRegistryOptions, JSONRTERegistryOptions, JsonRTEProp, LayerIcon, LengthToken, MultiChoiceProp, NodeProps, NumberProp, ObjectInput, ObjectProp, PlaceHolders, PlainTextProp, PreProcessedBreakpoint, PreProcessedDesignTokenInput, PropBase, PropInput, PropType, PropTypeOfNoOptionsRequired, PropValidator, Props, PropsWithNoOptionsRequired, RawStaticValue, RegisterComponentOptionsInput, RegisterComponentSchema, RegisterComponentSchemaInput, RegisterInternalComponentOptionsInput, Registry, RepeaterBindingValue, SectionDesignTokens, SectionScopedDataSources, SingleChoiceProp, SlotProp, StaticValue, StaticValueItem, StaticValueUid, StringProp, StudioSpecData, StyleGroupOptions, StyleSectionCategoriesOptions, StyleSectionOptions, StyleSections, TemplateBindingValue };
1992
+ export { ALLOWED_DESIGN_VALUES_LEVELS, BUILT_IN_COMPONENTS, BreakpointRegistry, ComponentRegistry, DATA_SOURCES, DATA_SOURCES_PREFIX, DEFAULT_DESIGN_TOKENS, DesignRegistry, INTERNAL_COMPONENTS_NAMES, INTERNAL_COMPONENT_SECTIONS, INTERNAL_SECTIONS, JSONRTERegistry, STYLE_SECTIONS_OPTIONS, STYLE_SECTION_CATEGORIES, SYSTEM_COMPONENTS, StudioStateStore, callStudioFunction, clearReportedBindingErrorsForNode, collectStateBindingKeys, convertBindingPath, getBindingString, getComponentRegistryInstance, getCslpPath, getCslpTag, getDataType, getDefaultPropStaticValue, getDesignClassesNames, getDesignRegistryInstance, getFlattenedData, getGlobalStudioStore, getNodeBoundFunctionName, getPlaceHolderComponent, getRepeaterBinding, getRepeaterContextPath, getSectionUIDFromNode, getSlotData, getStateDefaultsFor, getStateStoreInstance, getStateValuesFor, getStudioFunctionNames, getStudioStateSnapshot, hasComponentRegistryInstance, hasDesignRegistryInstance, isDataMatchingPropType, isKnownType, normalizeSingleSelectChoiceValue, registerComponentStateVariable, registerGlobalStateVariables, registerStudioFunctions, resetComponentRegistryInstance, resetDesignRegistryInstance, resetGlobalStudioStore, resetStateStoreInstance, resetStudioFunctions, resolveMetadataBindings, retrievePropValue, studioState, subscribeStudioFunctionsChanged, subscribeStudioStateVariablesChanged, wrapActionProps };
1993
+ export type { ActionProp, AllowedDesignValues, AllowedDesignValuesLevel, AnyProp, ArrayProp, BooleanProp, Breakpoint, BreakpointInput, CSBindingPath, CSDataSources, ChoiceProp, ComponentRegistryOptions, ComponentType, ComposableStudioData, ContentstackBindingValue, CssVariablesToDesignTokens, CssVariablesToValue, DataSourceItem, DataSources, DateStringProp, DefaultBreakpoint, DesignClassValue, DesignClasses, DesignClassesInput, DesignClassesNames, DesignTokenCssVariable, DesignTokens, DesignTokensInput, DesignTokensInputKeys, DesignTokensOptions, DesignTokensOptionsInput, GetSlots, GetSlotsParams, GlobalDesignTokens, GlobalStudioStore, HrefProp, ICSEntryReference, ImageUrlProp, InternalComponentRegistryOptions, JSONRTERegistryOptions, JsonRTEProp, LayerIcon, LengthToken, MultiChoiceProp, NodeProps, NumberProp, ObjectInput, ObjectProp, PlaceHolders, PlainTextProp, PreProcessedBreakpoint, PreProcessedDesignTokenInput, PropBase, PropInput, PropType, PropTypeOfNoOptionsRequired, PropValidator, Props, PropsWithNoOptionsRequired, RawStaticValue, RegisterComponentOptionsInput, RegisterComponentSchema, RegisterComponentSchemaInput, RegisterInternalComponentOptionsInput, Registry, RepeaterBindingValue, SectionDesignTokens, SectionScopedDataSources, SingleChoiceProp, SlotProp, StateUnsubscribe, StateUpdater, StateVariableDef, StateVariableTier, StateVariableType, StaticValue, StaticValueItem, StaticValueUid, StringProp, StudioFunction, StudioFunctionCtx, StudioSpecData, StudioStateConfig, StudioStateStorage, StyleGroupOptions, StyleSectionCategoriesOptions, StyleSectionOptions, StyleSections, TemplateBindingValue };
package/dist/esm/index.js CHANGED
@@ -9,8 +9,13 @@ export { JSONRTERegistry } from './json-rte-registry/index.js';
9
9
  export { clearReportedBindingErrorsForNode, retrievePropValue } from './data-binder/retrieve-data.js';
10
10
  export { convertBindingPath, getBindingString, getDataType, getDefaultPropStaticValue, getFlattenedData, getPlaceHolderComponent, getRepeaterContextPath, getSlotData, isDataMatchingPropType, isKnownType, normalizeSingleSelectChoiceValue, resolveMetadataBindings } from './data-binder/retrieve-data.util.js';
11
11
  export { getCslpPath, getCslpTag, getRepeaterBinding } from './data-binder/cslp.js';
12
+ export { collectStateBindingKeys, getNodeBoundFunctionName, getStateDefaultsFor, getStateValuesFor } from './data-binder/state-binding.util.js';
12
13
  export { BreakpointRegistry } from './breakpoint-registry/index.js';
13
- export { getSymbolUIDFromNode, getSymbolUIDFromUID } from './utils/symbols.js';
14
14
  export { getSectionUIDFromNode } from './utils/sections.js';
15
+ export { StudioStateStore } from './state-store/state-store.js';
16
+ export { getStateStoreInstance, resetStateStoreInstance } from './state-store/singleton.js';
17
+ export { getStudioStateSnapshot, registerComponentStateVariable, registerGlobalStateVariables, studioState, subscribeStudioStateVariablesChanged } from './state-store/public-api.js';
18
+ export { callStudioFunction, getStudioFunctionNames, registerStudioFunctions, resetStudioFunctions, subscribeStudioFunctionsChanged } from './state-store/function-registry.js';
19
+ export { wrapActionProps } from './state-store/action-props.util.js';
15
20
  export { getGlobalStudioStore, resetGlobalStudioStore } from './common/global-store.js';
16
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;"}