@fugood/bricks-ctor 2.25.0-beta.6 → 2.25.0-beta.61

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 (133) hide show
  1. package/package.json +4 -24
  2. package/tools/deploy.ts +19 -165
  3. package/tools/mcp-server.ts +17 -26
  4. package/tools/postinstall.ts +21 -235
  5. package/tools/pull.ts +18 -121
  6. package/tools/push-config.ts +19 -0
  7. package/tools/simulator.ts +21 -0
  8. package/compile/action-name-map.ts +0 -1015
  9. package/compile/index.ts +0 -1278
  10. package/compile/util.ts +0 -358
  11. package/index.ts +0 -6
  12. package/skills/bricks-ctor/SKILL.md +0 -32
  13. package/skills/bricks-ctor/rules/animation.md +0 -159
  14. package/skills/bricks-ctor/rules/architecture-patterns.md +0 -69
  15. package/skills/bricks-ctor/rules/automations.md +0 -221
  16. package/skills/bricks-ctor/rules/buttress.md +0 -156
  17. package/skills/bricks-ctor/rules/data-calculation.md +0 -209
  18. package/skills/bricks-ctor/rules/local-sync.md +0 -129
  19. package/skills/bricks-ctor/rules/media-flow.md +0 -158
  20. package/skills/bricks-ctor/rules/remote-data-bank.md +0 -196
  21. package/skills/bricks-ctor/rules/standby-transition.md +0 -124
  22. package/skills/bricks-design/LICENSE.txt +0 -180
  23. package/skills/bricks-design/SKILL.md +0 -66
  24. package/skills/rive-marketplace/SKILL.md +0 -99
  25. package/tools/_git-author.ts +0 -29
  26. package/tools/_shell.ts +0 -173
  27. package/tools/icons/.gitattributes +0 -1
  28. package/tools/icons/fa6pro-glyphmap.json +0 -4686
  29. package/tools/icons/fa6pro-meta.json +0 -1
  30. package/tools/mcp-tools/compile.ts +0 -92
  31. package/tools/mcp-tools/huggingface.ts +0 -762
  32. package/tools/mcp-tools/icons.ts +0 -81
  33. package/tools/mcp-tools/lottie.ts +0 -102
  34. package/tools/mcp-tools/media.ts +0 -110
  35. package/tools/preview-main.mjs +0 -293
  36. package/tools/preview.ts +0 -150
  37. package/types/animation.ts +0 -100
  38. package/types/automation.ts +0 -235
  39. package/types/brick-base.ts +0 -80
  40. package/types/bricks/Camera.ts +0 -246
  41. package/types/bricks/Chart.ts +0 -372
  42. package/types/bricks/GenerativeMedia.ts +0 -290
  43. package/types/bricks/Icon.ts +0 -98
  44. package/types/bricks/Image.ts +0 -114
  45. package/types/bricks/Items.ts +0 -476
  46. package/types/bricks/Lottie.ts +0 -168
  47. package/types/bricks/Maps.ts +0 -262
  48. package/types/bricks/QrCode.ts +0 -117
  49. package/types/bricks/Rect.ts +0 -150
  50. package/types/bricks/RichText.ts +0 -128
  51. package/types/bricks/Rive.ts +0 -220
  52. package/types/bricks/Sketch.ts +0 -254
  53. package/types/bricks/Slideshow.ts +0 -201
  54. package/types/bricks/Svg.ts +0 -99
  55. package/types/bricks/Text.ts +0 -148
  56. package/types/bricks/TextInput.ts +0 -242
  57. package/types/bricks/Video.ts +0 -175
  58. package/types/bricks/VideoStreaming.ts +0 -112
  59. package/types/bricks/WebRtcStream.ts +0 -65
  60. package/types/bricks/WebView.ts +0 -168
  61. package/types/bricks/index.ts +0 -22
  62. package/types/canvas.ts +0 -82
  63. package/types/common.ts +0 -144
  64. package/types/data-calc-command.ts +0 -7005
  65. package/types/data-calc-script.ts +0 -21
  66. package/types/data-calc.ts +0 -11
  67. package/types/data.ts +0 -95
  68. package/types/generators/AlarmClock.ts +0 -110
  69. package/types/generators/Assistant.ts +0 -621
  70. package/types/generators/BleCentral.ts +0 -247
  71. package/types/generators/BlePeripheral.ts +0 -208
  72. package/types/generators/CanvasMap.ts +0 -74
  73. package/types/generators/CastlesPay.ts +0 -87
  74. package/types/generators/DataBank.ts +0 -160
  75. package/types/generators/File.ts +0 -432
  76. package/types/generators/GraphQl.ts +0 -132
  77. package/types/generators/Http.ts +0 -222
  78. package/types/generators/HttpServer.ts +0 -176
  79. package/types/generators/Information.ts +0 -103
  80. package/types/generators/Intent.ts +0 -168
  81. package/types/generators/Iterator.ts +0 -108
  82. package/types/generators/Keyboard.ts +0 -105
  83. package/types/generators/LlmAnthropicCompat.ts +0 -212
  84. package/types/generators/LlmAppleBuiltin.ts +0 -159
  85. package/types/generators/LlmGgml.ts +0 -861
  86. package/types/generators/LlmMediaTekNeuroPilot.ts +0 -235
  87. package/types/generators/LlmMlx.ts +0 -227
  88. package/types/generators/LlmOnnx.ts +0 -213
  89. package/types/generators/LlmOpenAiCompat.ts +0 -312
  90. package/types/generators/LlmQualcommAiEngine.ts +0 -247
  91. package/types/generators/Mcp.ts +0 -637
  92. package/types/generators/McpServer.ts +0 -289
  93. package/types/generators/MediaFlow.ts +0 -170
  94. package/types/generators/MqttBroker.ts +0 -141
  95. package/types/generators/MqttClient.ts +0 -141
  96. package/types/generators/Question.ts +0 -408
  97. package/types/generators/RealtimeTranscription.ts +0 -287
  98. package/types/generators/RerankerGgml.ts +0 -191
  99. package/types/generators/SerialPort.ts +0 -151
  100. package/types/generators/SoundPlayer.ts +0 -94
  101. package/types/generators/SoundRecorder.ts +0 -130
  102. package/types/generators/SpeechToTextGgml.ts +0 -419
  103. package/types/generators/SpeechToTextOnnx.ts +0 -236
  104. package/types/generators/SpeechToTextPlatform.ts +0 -85
  105. package/types/generators/SqLite.ts +0 -159
  106. package/types/generators/Step.ts +0 -107
  107. package/types/generators/SttAppleBuiltin.ts +0 -130
  108. package/types/generators/Tcp.ts +0 -126
  109. package/types/generators/TcpServer.ts +0 -147
  110. package/types/generators/TextToSpeechAppleBuiltin.ts +0 -127
  111. package/types/generators/TextToSpeechGgml.ts +0 -221
  112. package/types/generators/TextToSpeechOnnx.ts +0 -178
  113. package/types/generators/TextToSpeechOpenAiLike.ts +0 -121
  114. package/types/generators/ThermalPrinter.ts +0 -191
  115. package/types/generators/Tick.ts +0 -83
  116. package/types/generators/Udp.ts +0 -120
  117. package/types/generators/VadGgml.ts +0 -250
  118. package/types/generators/VadOnnx.ts +0 -231
  119. package/types/generators/VadTraditional.ts +0 -138
  120. package/types/generators/VectorStore.ts +0 -257
  121. package/types/generators/Watchdog.ts +0 -107
  122. package/types/generators/WebCrawler.ts +0 -103
  123. package/types/generators/WebRtc.ts +0 -181
  124. package/types/generators/WebSocket.ts +0 -148
  125. package/types/generators/index.ts +0 -57
  126. package/types/index.ts +0 -13
  127. package/types/subspace.ts +0 -60
  128. package/types/switch.ts +0 -51
  129. package/types/system.ts +0 -707
  130. package/utils/calc.ts +0 -126
  131. package/utils/data.ts +0 -497
  132. package/utils/event-props.ts +0 -886
  133. package/utils/id.ts +0 -80
@@ -1,221 +0,0 @@
1
- # Automations
2
-
3
- E2E testing and scheduled execution for BRICKS applications. Simulates user behavior and validates application state.
4
-
5
- ## Automation Types
6
-
7
- | Type | Description |
8
- | --------- | ---------------------------------------------------------- |
9
- | `launch` | Run on application launch (restarts app when run manually) |
10
- | `anytime` | Execute anytime via manual trigger |
11
- | `cron` | Scheduled execution using crontab expressions |
12
-
13
- ## Simulation Actions
14
-
15
- Automations can simulate:
16
-
17
- - **Brick Press**: Tap/click on bricks
18
- - **Key Events**: Key up/down for keyboard input
19
- - **HTTP Request**: API calls
20
- - **Execute Action**: Trigger system or generator actions
21
-
22
- ## Assertions
23
-
24
- Automations can validate:
25
-
26
- - **Brick Exists**: Check if brick is rendered
27
- - **Event Triggered**: Verify event from Brick/Generator/Canvas
28
- - **Canvas Changed**: Confirm canvas navigation
29
- - **Property Assert**: Check Data Bank values
30
- - **Property Updated**: Wait for property change
31
- - **Match Screenshot**: Visual regression testing
32
-
33
- ## TypeScript Example
34
-
35
- ```typescript
36
- const testLoginFlow: AutomationTest = {
37
- __typename: 'AutomationTest',
38
- id: makeId('test'),
39
- title: 'Test Login Flow',
40
- timeout: 30000,
41
- trigger_type: 'launch',
42
- cases: [
43
- {
44
- __typename: 'TestCase',
45
- id: makeId('test_case'),
46
- name: 'Wait for login canvas',
47
- run: ['wait_until_canvas_change', () => mainSubspace, () => loginCanvas, 5000],
48
- exit_on_failed: true,
49
- commented: false,
50
- pre_delay: 0,
51
- post_delay: 0,
52
- jump_cond: [],
53
- },
54
- {
55
- __typename: 'TestCase',
56
- id: makeId('test_case'),
57
- name: 'Press username input',
58
- run: ['brick_press', () => mainSubspace, () => usernameInput],
59
- exit_on_failed: true,
60
- commented: false,
61
- pre_delay: 0,
62
- post_delay: 100,
63
- jump_cond: [],
64
- },
65
- {
66
- __typename: 'TestCase',
67
- id: makeId('test_case'),
68
- name: 'Assert username value',
69
- run: ['assert_property', () => mainSubspace, () => usernameData, 'testuser'],
70
- exit_on_failed: true,
71
- commented: false,
72
- pre_delay: 0,
73
- post_delay: 0,
74
- jump_cond: [],
75
- },
76
- {
77
- __typename: 'TestCase',
78
- id: makeId('test_case'),
79
- name: 'Press login button',
80
- run: ['brick_press', () => mainSubspace, () => loginButton],
81
- exit_on_failed: true,
82
- commented: false,
83
- pre_delay: 0,
84
- post_delay: 0,
85
- jump_cond: [],
86
- },
87
- {
88
- __typename: 'TestCase',
89
- id: makeId('test_case'),
90
- name: 'Wait for dashboard',
91
- run: ['wait_until_canvas_change', () => mainSubspace, () => dashboardCanvas, 10000],
92
- exit_on_failed: true,
93
- commented: false,
94
- pre_delay: 0,
95
- post_delay: 0,
96
- jump_cond: [],
97
- },
98
- ],
99
- variables: [],
100
- }
101
- ```
102
-
103
- ## Test Methods
104
-
105
- | Method | Signature | Description |
106
- | ---------------------------- | ------------------------------------------------ | -------------------- |
107
- | `brick_press` | `[subspace, brick, options?]` | Simulate brick press |
108
- | `brick_exists` | `[subspace, brick, frame?]` | Check brick exists |
109
- | `wait_until_brick_exists` | `[subspace, brick, timeout?, frame?]` | Wait for brick |
110
- | `wait_until_event_trigger` | `[subspace, sender, eventKey, timeout?]` | Wait for event |
111
- | `wait_until_canvas_change` | `[subspace, canvas, timeout?]` | Wait for canvas |
112
- | `keydown` | `[keyCode, pressedKey?, flags?]` | Key down event |
113
- | `keyup` | `[keyCode, pressedKey?, flags?]` | Key up event |
114
- | `http_request` | `[url, options?]` | HTTP request |
115
- | `assert_property` | `[subspace, property, value]` | Assert data value |
116
- | `wait_until_property_change` | `[subspace, property, value, timeout?]` | Wait for value |
117
- | `execute_action` | `[subspace, handler, action, params?, options?]` | Execute action |
118
- | `match_screenshot` | `[name, threshold?, maxRetry?]` | Screenshot compare |
119
- | `delay` | `[subspace?, property?, defaultValue?]` | Delay execution |
120
-
121
- ### execute_action Params
122
-
123
- The `params` object in `execute_action` uses **runtime event property keys** from `event-props.ts`, NOT the action config `input` names from type definitions.
124
-
125
- ```typescript
126
- // CORRECT — use runtime event property key
127
- run: ['execute_action', () => subspace0, bricks.bInput.id, 'BRICK_TEXT_INPUT_SET_TEXT',
128
- { BRICK_TEXT_INPUT_TEXT: 'hello' }]
129
-
130
- // WRONG — action config input name doesn't work in automation
131
- run: ['execute_action', () => subspace0, bricks.bInput.id, 'BRICK_TEXT_INPUT_SET_TEXT',
132
- { text: 'hello' }]
133
- ```
134
-
135
- Reference `event-props.ts` for the correct runtime keys (e.g., `BRICK_TEXT_INPUT_TEXT`, `GENERATOR_MQTT_PAYLOAD`).
136
-
137
- ### Prefer UI Interactions Over Direct Generator Calls
138
-
139
- For realistic E2E testing, prefer simulating user actions (set text input + press button) over calling generator actions directly:
140
-
141
- ```typescript
142
- // GOOD — simulates real user behavior
143
- { run: ['execute_action', () => sub, bricks.bInput.id, 'BRICK_TEXT_INPUT_SET_TEXT',
144
- { BRICK_TEXT_INPUT_TEXT: 'hello' }] },
145
- { run: ['brick_press', () => sub, () => bricks.bSendBtn] },
146
- { run: ['wait_until_property_change', () => sub, () => data.dPayload, 'hello', 10000] },
147
-
148
- // AVOID — bypasses UI, doesn't test the full flow
149
- { run: ['execute_action', () => sub, generators.gClient.id, 'GENERATOR_MQTT_PUBLISH',
150
- { topic: 'test', payload: 'hello', qos: '0' }] },
151
- ```
152
-
153
- ## Recording Automations
154
-
155
- In BRICKS Editor Preview mode:
156
-
157
- 1. Perform operations normally
158
- 2. Open menu (right-bottom corner)
159
- 3. Select "Record Events as Automation"
160
- 4. Generated automation appears in Automations list
161
-
162
- ## Running Automations
163
-
164
- ### Manual Run
165
-
166
- `Menu` → `Automations` → Select automation → `Run`
167
-
168
- ### On Launch
169
-
170
- `Bind Device` → `Select Automation` (only `launch` or `cron` types)
171
-
172
- ### Scheduled (Cron)
173
-
174
- `Bind Device` → `Cron Automation` (allows multi-select)
175
-
176
- Use [crontab.guru](https://crontab.guru) to build cron expressions.
177
-
178
- ## Screenshot Testing
179
-
180
- Visual regression testing with screenshot comparison:
181
-
182
- ```typescript
183
- {
184
- __typename: 'TestCase',
185
- id: makeId('test_case'),
186
- name: 'Match dashboard screenshot',
187
- run: ['match_screenshot', 'dashboard-initial-state', 0.01, 3],
188
- exit_on_failed: true,
189
- commented: false,
190
- pre_delay: 500, // Wait for UI to settle
191
- post_delay: 0,
192
- jump_cond: [],
193
- }
194
- ```
195
-
196
- Screenshots can be stored:
197
-
198
- - Local file system
199
- - Media Flow workspace
200
-
201
- First run captures baseline. Use "Run with Update" to update baseline.
202
-
203
- ## Module Support
204
-
205
- Automations work with Modules. Use Manual Run in Preview mode for module testing.
206
-
207
- ## Important Notes
208
-
209
- - **Automation map key**: Always use `'AUTOMATION_MAP_DEFAULT'` as the automation map ID (not `makeId()`). The preview test runner reads from `automationMap['AUTOMATION_MAP_DEFAULT']?.map`.
210
- - **Valid makeId types**: Use `'test'` for AutomationTest, `'test_case'` for TestCase, `'test_var'` for TestVariable. Do NOT use `'automation_test'` or `'automation_test_map'`.
211
- - **handler in execute_action**: Pass the entity's `.id` string (e.g., `bricks.bInput.id`), not a getter function.
212
-
213
- ## Best Practices
214
-
215
- 1. **Test culture**: Create automations for every significant flow
216
- 2. **CI/CD integration**: Use `launch` automations for deployment validation
217
- 3. **Incremental waits**: Use `wait_until_property_change` with appropriate timeouts
218
- 4. **Visual testing**: Add screenshot comparisons for critical UI states
219
- 5. **Cron monitoring**: Schedule health checks for production displays
220
- 6. **Isolation**: Each automation should be independent and idempotent
221
- 7. **UI-first testing**: Simulate real user interactions (text input, button press) rather than calling generators directly
@@ -1,156 +0,0 @@
1
- # Buttress (Remote Inference)
2
-
3
- Backend system for offloading compute-intensive AI generator tasks from BRICKS devices to more powerful machines.
4
-
5
- ## Purpose
6
-
7
- When mobile devices or embedded systems lack hardware for local AI inference (LLM, speech-to-text), Buttress transparently delegates work to a server with appropriate resources (GPU).
8
-
9
- ## How It Works
10
-
11
- 1. **Capability Exchange**: Client and server share hardware capabilities
12
- 2. **Strategy Selection**: System decides local vs. remote execution
13
- 3. **Transparent Offloading**: Generator operates same way, execution happens remotely
14
-
15
- ## Supported Generators
16
-
17
- - LLM (GGML) (LlmMlx.ts) - Local Large Language Model inference with GGML
18
- - LLM (MLX) (LlmGgml.ts) - Local Large Language Model inference with MLX
19
- - Speech-to-Text (GGML) (SpeechToTextGgml.ts) - Local Speech-to-Text inference with GGML
20
-
21
- ## Client Configuration
22
-
23
- In generator properties, configure Buttress settings:
24
-
25
- | Setting | Description |
26
- |---------|-------------|
27
- | `Enabled` | Toggle Buttress offloading |
28
- | `URL` | Buttress server URL (e.g., `http://192.168.1.100:2080`) |
29
- | `Fallback Type` | Action if Buttress unavailable: `use-local` or `no-op` |
30
- | `Strategy` | Execution preference |
31
-
32
- ### Strategy Options
33
-
34
- | Strategy | Description |
35
- |----------|-------------|
36
- | `prefer-local` | Use local if capable, fallback to Buttress |
37
- | `prefer-buttress` | Use Buttress if available, fallback to local |
38
- | `prefer-best` | Auto-select based on capability comparison |
39
-
40
- ## Generator Configuration Example
41
-
42
- ```typescript
43
- import { makeId } from 'bricks-ctor'
44
-
45
- const llmGenerator: GeneratorLLM = {
46
- __typename: 'Generator',
47
- templateKey: 'GENERATOR_LLM',
48
- id: makeId('generator'),
49
- title: 'Chat LLM',
50
- description: '',
51
- property: {
52
- modelUrl: 'https://huggingface.co/ggml-org/gemma-3-12b-it-qat-GGUF/resolve/main/gemma-3-12b-it-qat-q4_0.gguf',
53
- contextSize: 8192,
54
- buttressConnectionSettings: {
55
- enabled: true,
56
- url: 'http://192.168.1.100:2080',
57
- fallbackType: 'use-local',
58
- strategy: 'prefer-best',
59
- },
60
- },
61
- events: {},
62
- switches: [],
63
- }
64
- ```
65
-
66
- ## Server Setup
67
-
68
- ### Requirements
69
- - [Bun](https://bun.sh) v1.3+
70
- - GPU recommended for LLM/STT
71
-
72
- ### Installation
73
-
74
- ```bash
75
- bun add -g @fugood/buttress-server
76
- ```
77
-
78
- ### Start Server
79
-
80
- ```bash
81
- bricks-buttress
82
- # or with config
83
- bricks-buttress --config ./config.toml
84
- ```
85
-
86
- ### CLI Options
87
-
88
- | Option | Description |
89
- |--------|-------------|
90
- | `-p, --port` | Port (default: 2080) |
91
- | `-c, --config` | TOML config file path |
92
- | `-v, --version` | Show version |
93
- | `-h, --help` | Show help |
94
-
95
- ### Environment Variables
96
-
97
- | Variable | Description |
98
- |----------|-------------|
99
- | `HF_TOKEN` | Hugging Face token for model downloads |
100
- | `ENABLE_OPENAI_COMPAT_ENDPOINT` | Set to `1` for OpenAI-compatible API |
101
-
102
- ## Server Configuration (TOML)
103
-
104
- ```toml
105
- [server]
106
- port = 2080
107
-
108
- [runtime]
109
- cache_dir = "./.buttress-cache"
110
- n_threads = 6
111
- flash_attn_type = "on"
112
- cache_type_k = "q8_0"
113
- cache_type_v = "q8_0"
114
-
115
- # LLM Generator
116
- [[generators]]
117
- type = "ggml-llm"
118
- [generators.backend]
119
- variant_preference = ["cuda", "vulkan", "default"]
120
- gpu_memory_fraction = 0.95
121
- [generators.model]
122
- repo_id = "ggml-org/gemma-3-12b-it-qat-GGUF"
123
- download = true
124
- n_ctx = 8192
125
-
126
- # STT Generator
127
- [[generators]]
128
- type = "ggml-stt"
129
- [generators.backend]
130
- variant_preference = ["cuda", "vulkan", "default"]
131
- [generators.model]
132
- repo_id = "BricksDisplay/whisper-ggml"
133
- filename = "ggml-small-q8_0.bin"
134
- download = true
135
- use_gpu = true
136
- ```
137
-
138
- ## Use Cases
139
-
140
- ### Resource-Constrained Devices
141
- Digital signage with basic hardware offloads LLM to powerful server.
142
-
143
- ### Shared GPU Resources
144
- Multiple devices share single GPU server for inference.
145
-
146
- ### Development Testing
147
- Test AI features on lightweight dev machines by connecting to beefy server.
148
-
149
- ## Best Practices
150
-
151
- 1. **Network reliability**: Ensure stable LAN connection to Buttress server
152
- 2. **Fallback strategy**: Configure appropriate fallback for critical features
153
- 3. **Server monitoring**: Monitor Buttress server resource usage
154
- 4. **Model consistency**: Ensure client and server use compatible models
155
- 5. **Security**: Run Buttress on private network, not public internet
156
- 6. **Latency awareness**: Account for network latency in UX design
@@ -1,209 +0,0 @@
1
- # Data Calculation (JS Sandbox)
2
-
3
- Transform and compute Data Bank values using JavaScript scripts.
4
-
5
- ## DataCalculationScript
6
-
7
- JavaScript code executed in a sandbox with access to inputs and outputs.
8
-
9
- ```typescript
10
- import { makeId } from 'bricks-ctor'
11
-
12
- const calculation: DataCalculationScript = {
13
- __typename: 'DataCalculationScript',
14
- id: makeId('property_bank_calc'),
15
- title: 'Format Price',
16
- description: 'Formats price with currency symbol',
17
- note: '',
18
- triggerMode: 'auto', // 'auto' | 'manual'
19
- enableAsync: false,
20
- // Inline code
21
- code: `
22
- const price = inputs.price || 0
23
- const currency = inputs.currency || 'USD'
24
- return new Intl.NumberFormat('en-US', {
25
- style: 'currency',
26
- currency,
27
- }).format(price)
28
- `,
29
- // Or load from file (preferred for longer scripts)
30
- // import { readFile } from 'node:fs/promises'
31
- // code: await readFile(new URL('./format-price.sandbox.js', import.meta.url), 'utf8'),
32
- inputs: [
33
- { key: 'price', data: () => priceData, trigger: true },
34
- { key: 'currency', data: () => currencyData, trigger: false },
35
- ],
36
- output: () => formattedPriceData,
37
- outputs: [], // Additional named outputs
38
- error: null, // or () => errorData for error handling
39
- }
40
- ```
41
-
42
- ## Trigger Modes
43
-
44
- | Mode | Description |
45
- |------|-------------|
46
- | `auto` | Run when input values change (with trigger: true) |
47
- | `manual` | Only run via `PROPERTY_BANK_COMMAND` action |
48
-
49
- Use `manual` to prevent circular dependencies or for explicit control.
50
-
51
- ## Script Sandbox Features
52
-
53
- Scripts run in `use strict` mode with a sandboxed set of globals and libraries.
54
-
55
- ### Built-in Globals
56
-
57
- | Global | Description |
58
- |--------|-------------|
59
- | `inputs` | Object with input values |
60
- | `console` | `{ log, error, warn, info }` for debugging |
61
- | `Platform` | `{ OS, isTV, isPad, isVision, isElectron }` |
62
- | `TextEncoder`, `TextDecoder` | Text encoding/decoding |
63
- | `Buffer` | Node.js Buffer (without `allocUnsafe`) |
64
- | `btoa`, `atob` | Base64 encoding/decoding |
65
-
66
- ### Available Libraries
67
-
68
- **Utility**
69
- | Library | Global | Description |
70
- |---------|--------|-------------|
71
- | [lodash](https://lodash.com) | `_`, `lodash` | Utility (sync: no debounce/delay/defer) |
72
- | [voca](https://vocajs.com) | `voca` | String manipulation |
73
- | [invariant](https://github.com/zertosh/invariant) | `invariant` | Assertions |
74
-
75
- **Data & Encoding**
76
- | Library | Global | Description |
77
- |---------|--------|-------------|
78
- | [json5](https://github.com/json5/json5) | `json5` | JSON5 parsing |
79
- | [qs](https://github.com/ljharb/qs) | `qs` | Query string parsing |
80
- | [url](https://github.com/defunctzombie/node-url) | `url` | URL parsing |
81
- | [bytes](https://github.com/visionmedia/bytes.js) | `bytes` | Byte parsing/formatting |
82
- | [ms](https://github.com/vercel/ms) | `ms` | Millisecond conversion |
83
- | [base45](https://github.com/irony/base45) | `base45` | Base45 encoding |
84
- | [iconv-lite](https://github.com/ashtuchkin/iconv-lite) | `iconv` | Character encoding |
85
-
86
- **Math & Color**
87
- | Library | Global | Description |
88
- |---------|--------|-------------|
89
- | [mathjs](https://mathjs.org) | `math`, `mathjs` | Math library |
90
- | [chroma-js](https://gka.github.io/chroma.js) | `chroma` | Color manipulation |
91
-
92
- **Date/Time**
93
- | Library | Global | Description |
94
- |---------|--------|-------------|
95
- | [moment](https://momentjs.com) | `moment` | Date/time (auto parseFormat) |
96
-
97
- **ID & Hash**
98
- | Library | Global | Description |
99
- |---------|--------|-------------|
100
- | [nanoid](https://github.com/ai/nanoid) | `nanoid` | Unique ID generation |
101
- | [md5](https://github.com/pvorb/node-md5) | `md5` | MD5 hashing |
102
-
103
- **Crypto**
104
- | Library | Global | Description |
105
- |---------|--------|-------------|
106
- | [crypto-browserify](https://github.com/crypto-browserify/crypto-browserify) | `crypto` | Crypto functions |
107
- | [jsrsasign](https://github.com/kjur/jsrsasign) | `kjurJWS` | JWT/JWS signing |
108
- | [cose-js](https://github.com/erdtman/COSE-JS) | `coseVerify` | COSE verification (sync) |
109
-
110
- **Compression**
111
- | Library | Global | Description |
112
- |---------|--------|-------------|
113
- | [fflate](https://github.com/101arrowz/fflate) | `fflate` | `{ zlibSync, unzlibSync, gzipSync, gunzipSync, compressSync, decompressSync, strFromU8 }` |
114
- | [cbor](https://github.com/hildjj/node-cbor) | `cbor` | `{ encode, decode, decodeFirstSync, decodeAllSync }` |
115
-
116
- **File & Document**
117
- | Library | Global | Description |
118
- |---------|--------|-------------|
119
- | fs | `fs` | File system (limited, no download/upload) |
120
- | [officeparser](https://github.com/nicktang) | `parseDocument` | Office document parsing (async) |
121
- | [turndown](https://github.com/mixmark-io/turndown) | `TurndownService` | HTML to Markdown |
122
- | [opencc-js](https://github.com/nk2028/opencc-js) | `OpenCC` | Chinese conversion `{ Converter, ConverterFactory, CustomConverter, Locale }` |
123
- | [toon-format](https://github.com/nicktang) | `TOON` | TOON format parsing |
124
-
125
- ### Runtime Environment
126
-
127
- | Platform | Engine |
128
- |----------|--------|
129
- | Android | Hermes engine sandbox |
130
- | iOS | JavaScriptCore sandbox |
131
-
132
- ### Async Mode
133
-
134
- Enable `enableAsync: true` to unlock additional capabilities:
135
-
136
- **Additional async globals:**
137
- - `Promise`, `setTimeout`, `setInterval`, `setImmediate`
138
- - `clearTimeout`, `clearInterval`, `clearImmediate`
139
- - `requestAnimationFrame`
140
- - Full lodash (including `debounce`, `delay`, `defer`)
141
-
142
- ```typescript
143
- code: `
144
- const result = await new Promise((resolve) => {
145
- setTimeout(() => resolve(inputs.value * 2), 100)
146
- })
147
- return result
148
- `,
149
- enableAsync: true,
150
- ```
151
-
152
- ### Multiple Outputs
153
-
154
- ```typescript
155
- outputs: [
156
- { key: 'total', data: () => totalData },
157
- { key: 'tax', data: () => taxData },
158
- { key: 'subtotal', data: () => subtotalData },
159
- ],
160
- code: `
161
- const subtotal = inputs.price * inputs.quantity
162
- const tax = subtotal * 0.1
163
- const total = subtotal + tax
164
- return { total, tax, subtotal }
165
- `,
166
- ```
167
-
168
- ## Triggering Manually
169
-
170
- Use `PROPERTY_BANK_COMMAND` system action to trigger a manual calculation:
171
-
172
- ```typescript
173
- const triggerCalc: EventAction = {
174
- handler: 'system',
175
- action: {
176
- __actionName: 'PROPERTY_BANK_COMMAND',
177
- parent: 'System',
178
- dataParams: [
179
- { input: () => computeTotalCalc }, // Reference to DataCalculation
180
- ],
181
- },
182
- }
183
- ```
184
-
185
- ## Best Practices
186
-
187
- 1. **Avoid circular deps**: Set non-triggering inputs (`trigger: false`) or use `manual` mode
188
- 2. **Error handling**: Always set `error` output for scripts that might fail
189
- 3. **Keep scripts pure**: Avoid side effects, return computed values
190
- 4. **Debounce rapid updates**: Use `manual` mode + timer for high-frequency inputs
191
-
192
- ## Anti-Patterns (AVOID)
193
-
194
- See [Architecture Patterns](architecture-patterns.md) for the full pattern selection guide.
195
-
196
- ### Using Data Calc as an orchestrator
197
- Scripts that manage state machines, control UI flow, or coordinate multi-step processes belong in Event Action Chains, not here.
198
-
199
- **Symptom**: Script has if/else branches deciding "what happens next" or tracks "current step".
200
-
201
- ### Quick reference
202
-
203
- | If you need to... | Use instead |
204
- |---|---|
205
- | Call an LLM / AI model | Generator (Assistant, LLM, HTTP) |
206
- | Sequence multiple actions | Event Action Chain |
207
- | Set a data value directly | PROPERTY_BANK system action |
208
- | Compute a simple expression | PROPERTY_BANK_EXPRESSION |
209
- | Transform/format/parse data | Data Calculation (correct use) |